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 "CGCXXABI.h"
16 #include "CGDebugInfo.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/TargetBuiltins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
31 static CharUnits
32 ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33                                  const CXXRecordDecl *DerivedClass,
34                                  CastExpr::path_const_iterator Start,
35                                  CastExpr::path_const_iterator End) {
36   CharUnits Offset = CharUnits::Zero();
37 
38   const CXXRecordDecl *RD = DerivedClass;
39 
40   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
41     const CXXBaseSpecifier *Base = *I;
42     assert(!Base->isVirtual() && "Should not see virtual bases here!");
43 
44     // Get the layout.
45     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
46 
47     const CXXRecordDecl *BaseDecl =
48       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
49 
50     // Add the offset.
51     Offset += Layout.getBaseClassOffset(BaseDecl);
52 
53     RD = BaseDecl;
54   }
55 
56   return Offset;
57 }
58 
59 llvm::Constant *
60 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
61                                    CastExpr::path_const_iterator PathBegin,
62                                    CastExpr::path_const_iterator PathEnd) {
63   assert(PathBegin != PathEnd && "Base path should not be empty!");
64 
65   CharUnits Offset =
66     ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
67                                      PathBegin, PathEnd);
68   if (Offset.isZero())
69     return nullptr;
70 
71   llvm::Type *PtrDiffTy =
72   Types.ConvertType(getContext().getPointerDiffType());
73 
74   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
75 }
76 
77 /// Gets the address of a direct base class within a complete object.
78 /// This should only be used for (1) non-virtual bases or (2) virtual bases
79 /// when the type is known to be complete (e.g. in complete destructors).
80 ///
81 /// The object pointed to by 'This' is assumed to be non-null.
82 llvm::Value *
83 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84                                                    const CXXRecordDecl *Derived,
85                                                    const CXXRecordDecl *Base,
86                                                    bool BaseIsVirtual) {
87   // 'this' must be a pointer (in some address space) to Derived.
88   assert(This->getType()->isPointerTy() &&
89          cast<llvm::PointerType>(This->getType())->getElementType()
90            == ConvertType(Derived));
91 
92   // Compute the offset of the virtual base.
93   CharUnits Offset;
94   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
95   if (BaseIsVirtual)
96     Offset = Layout.getVBaseClassOffset(Base);
97   else
98     Offset = Layout.getBaseClassOffset(Base);
99 
100   // Shift and cast down to the base type.
101   // TODO: for complete types, this should be possible with a GEP.
102   llvm::Value *V = This;
103   if (Offset.isPositive()) {
104     V = Builder.CreateBitCast(V, Int8PtrTy);
105     V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
106   }
107   V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
108 
109   return V;
110 }
111 
112 static llvm::Value *
113 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
114                                 CharUnits nonVirtualOffset,
115                                 llvm::Value *virtualOffset) {
116   // Assert that we have something to do.
117   assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
118 
119   // Compute the offset from the static and dynamic components.
120   llvm::Value *baseOffset;
121   if (!nonVirtualOffset.isZero()) {
122     baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
123                                         nonVirtualOffset.getQuantity());
124     if (virtualOffset) {
125       baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
126     }
127   } else {
128     baseOffset = virtualOffset;
129   }
130 
131   // Apply the base offset.
132   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
133   ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
134   return ptr;
135 }
136 
137 llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
138     llvm::Value *Value, const CXXRecordDecl *Derived,
139     CastExpr::path_const_iterator PathBegin,
140     CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
141     SourceLocation Loc) {
142   assert(PathBegin != PathEnd && "Base path should not be empty!");
143 
144   CastExpr::path_const_iterator Start = PathBegin;
145   const CXXRecordDecl *VBase = nullptr;
146 
147   // Sema has done some convenient canonicalization here: if the
148   // access path involved any virtual steps, the conversion path will
149   // *start* with a step down to the correct virtual base subobject,
150   // and hence will not require any further steps.
151   if ((*Start)->isVirtual()) {
152     VBase =
153       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
154     ++Start;
155   }
156 
157   // Compute the static offset of the ultimate destination within its
158   // allocating subobject (the virtual base, if there is one, or else
159   // the "complete" object that we see).
160   CharUnits NonVirtualOffset =
161     ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
162                                      Start, PathEnd);
163 
164   // If there's a virtual step, we can sometimes "devirtualize" it.
165   // For now, that's limited to when the derived type is final.
166   // TODO: "devirtualize" this for accesses to known-complete objects.
167   if (VBase && Derived->hasAttr<FinalAttr>()) {
168     const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
169     CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
170     NonVirtualOffset += vBaseOffset;
171     VBase = nullptr; // we no longer have a virtual step
172   }
173 
174   // Get the base pointer type.
175   llvm::Type *BasePtrTy =
176     ConvertType((PathEnd[-1])->getType())->getPointerTo();
177 
178   QualType DerivedTy = getContext().getRecordType(Derived);
179   CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
180 
181   // If the static offset is zero and we don't have a virtual step,
182   // just do a bitcast; null checks are unnecessary.
183   if (NonVirtualOffset.isZero() && !VBase) {
184     if (sanitizePerformTypeCheck()) {
185       EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
186                     !NullCheckValue);
187     }
188     return Builder.CreateBitCast(Value, BasePtrTy);
189   }
190 
191   llvm::BasicBlock *origBB = nullptr;
192   llvm::BasicBlock *endBB = nullptr;
193 
194   // Skip over the offset (and the vtable load) if we're supposed to
195   // null-check the pointer.
196   if (NullCheckValue) {
197     origBB = Builder.GetInsertBlock();
198     llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
199     endBB = createBasicBlock("cast.end");
200 
201     llvm::Value *isNull = Builder.CreateIsNull(Value);
202     Builder.CreateCondBr(isNull, endBB, notNullBB);
203     EmitBlock(notNullBB);
204   }
205 
206   if (sanitizePerformTypeCheck()) {
207     EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
208                   DerivedTy, DerivedAlign, true);
209   }
210 
211   // Compute the virtual offset.
212   llvm::Value *VirtualOffset = nullptr;
213   if (VBase) {
214     VirtualOffset =
215       CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
216   }
217 
218   // Apply both offsets.
219   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
220                                           NonVirtualOffset,
221                                           VirtualOffset);
222 
223   // Cast to the destination type.
224   Value = Builder.CreateBitCast(Value, BasePtrTy);
225 
226   // Build a phi if we needed a null check.
227   if (NullCheckValue) {
228     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
229     Builder.CreateBr(endBB);
230     EmitBlock(endBB);
231 
232     llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
233     PHI->addIncoming(Value, notNullBB);
234     PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
235     Value = PHI;
236   }
237 
238   return Value;
239 }
240 
241 llvm::Value *
242 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
243                                           const CXXRecordDecl *Derived,
244                                         CastExpr::path_const_iterator PathBegin,
245                                           CastExpr::path_const_iterator PathEnd,
246                                           bool NullCheckValue) {
247   assert(PathBegin != PathEnd && "Base path should not be empty!");
248 
249   QualType DerivedTy =
250     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
251   llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
252 
253   llvm::Value *NonVirtualOffset =
254     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
255 
256   if (!NonVirtualOffset) {
257     // No offset, we can just cast back.
258     return Builder.CreateBitCast(Value, DerivedPtrTy);
259   }
260 
261   llvm::BasicBlock *CastNull = nullptr;
262   llvm::BasicBlock *CastNotNull = nullptr;
263   llvm::BasicBlock *CastEnd = nullptr;
264 
265   if (NullCheckValue) {
266     CastNull = createBasicBlock("cast.null");
267     CastNotNull = createBasicBlock("cast.notnull");
268     CastEnd = createBasicBlock("cast.end");
269 
270     llvm::Value *IsNull = Builder.CreateIsNull(Value);
271     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
272     EmitBlock(CastNotNull);
273   }
274 
275   // Apply the offset.
276   Value = Builder.CreateBitCast(Value, Int8PtrTy);
277   Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
278                             "sub.ptr");
279 
280   // Just cast.
281   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
282 
283   if (NullCheckValue) {
284     Builder.CreateBr(CastEnd);
285     EmitBlock(CastNull);
286     Builder.CreateBr(CastEnd);
287     EmitBlock(CastEnd);
288 
289     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
290     PHI->addIncoming(Value, CastNotNull);
291     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
292                      CastNull);
293     Value = PHI;
294   }
295 
296   return Value;
297 }
298 
299 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
300                                               bool ForVirtualBase,
301                                               bool Delegating) {
302   if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
303     // This constructor/destructor does not need a VTT parameter.
304     return nullptr;
305   }
306 
307   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
308   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
309 
310   llvm::Value *VTT;
311 
312   uint64_t SubVTTIndex;
313 
314   if (Delegating) {
315     // If this is a delegating constructor call, just load the VTT.
316     return LoadCXXVTT();
317   } else if (RD == Base) {
318     // If the record matches the base, this is the complete ctor/dtor
319     // variant calling the base variant in a class with virtual bases.
320     assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
321            "doing no-op VTT offset in base dtor/ctor?");
322     assert(!ForVirtualBase && "Can't have same class as virtual base!");
323     SubVTTIndex = 0;
324   } else {
325     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
326     CharUnits BaseOffset = ForVirtualBase ?
327       Layout.getVBaseClassOffset(Base) :
328       Layout.getBaseClassOffset(Base);
329 
330     SubVTTIndex =
331       CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
332     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
333   }
334 
335   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
336     // A VTT parameter was passed to the constructor, use it.
337     VTT = LoadCXXVTT();
338     VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
339   } else {
340     // We're the complete constructor, so get the VTT by name.
341     VTT = CGM.getVTables().GetAddrOfVTT(RD);
342     VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
343   }
344 
345   return VTT;
346 }
347 
348 namespace {
349   /// Call the destructor for a direct base class.
350   struct CallBaseDtor : EHScopeStack::Cleanup {
351     const CXXRecordDecl *BaseClass;
352     bool BaseIsVirtual;
353     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
354       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
355 
356     void Emit(CodeGenFunction &CGF, Flags flags) override {
357       const CXXRecordDecl *DerivedClass =
358         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
359 
360       const CXXDestructorDecl *D = BaseClass->getDestructor();
361       llvm::Value *Addr =
362         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
363                                                   DerivedClass, BaseClass,
364                                                   BaseIsVirtual);
365       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
366                                 /*Delegating=*/false, Addr);
367     }
368   };
369 
370   /// A visitor which checks whether an initializer uses 'this' in a
371   /// way which requires the vtable to be properly set.
372   struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
373     typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
374 
375     bool UsesThis;
376 
377     DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
378 
379     // Black-list all explicit and implicit references to 'this'.
380     //
381     // Do we need to worry about external references to 'this' derived
382     // from arbitrary code?  If so, then anything which runs arbitrary
383     // external code might potentially access the vtable.
384     void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
385   };
386 }
387 
388 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
389   DynamicThisUseChecker Checker(C);
390   Checker.Visit(const_cast<Expr*>(Init));
391   return Checker.UsesThis;
392 }
393 
394 static void EmitBaseInitializer(CodeGenFunction &CGF,
395                                 const CXXRecordDecl *ClassDecl,
396                                 CXXCtorInitializer *BaseInit,
397                                 CXXCtorType CtorType) {
398   assert(BaseInit->isBaseInitializer() &&
399          "Must have base initializer!");
400 
401   llvm::Value *ThisPtr = CGF.LoadCXXThis();
402 
403   const Type *BaseType = BaseInit->getBaseClass();
404   CXXRecordDecl *BaseClassDecl =
405     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
406 
407   bool isBaseVirtual = BaseInit->isBaseVirtual();
408 
409   // The base constructor doesn't construct virtual bases.
410   if (CtorType == Ctor_Base && isBaseVirtual)
411     return;
412 
413   // If the initializer for the base (other than the constructor
414   // itself) accesses 'this' in any way, we need to initialize the
415   // vtables.
416   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
417     CGF.InitializeVTablePointers(ClassDecl);
418 
419   // We can pretend to be a complete class because it only matters for
420   // virtual bases, and we only do virtual bases for complete ctors.
421   llvm::Value *V =
422     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
423                                               BaseClassDecl,
424                                               isBaseVirtual);
425   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
426   AggValueSlot AggSlot =
427     AggValueSlot::forAddr(V, Alignment, Qualifiers(),
428                           AggValueSlot::IsDestructed,
429                           AggValueSlot::DoesNotNeedGCBarriers,
430                           AggValueSlot::IsNotAliased);
431 
432   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
433 
434   if (CGF.CGM.getLangOpts().Exceptions &&
435       !BaseClassDecl->hasTrivialDestructor())
436     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
437                                           isBaseVirtual);
438 }
439 
440 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
441                                      LValue LHS,
442                                      Expr *Init,
443                                      llvm::Value *ArrayIndexVar,
444                                      QualType T,
445                                      ArrayRef<VarDecl *> ArrayIndexes,
446                                      unsigned Index) {
447   if (Index == ArrayIndexes.size()) {
448     LValue LV = LHS;
449 
450     if (ArrayIndexVar) {
451       // If we have an array index variable, load it and use it as an offset.
452       // Then, increment the value.
453       llvm::Value *Dest = LHS.getAddress();
454       llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
455       Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
456       llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
457       Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
458       CGF.Builder.CreateStore(Next, ArrayIndexVar);
459 
460       // Update the LValue.
461       LV.setAddress(Dest);
462       CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
463       LV.setAlignment(std::min(Align, LV.getAlignment()));
464     }
465 
466     switch (CGF.getEvaluationKind(T)) {
467     case TEK_Scalar:
468       CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
469       break;
470     case TEK_Complex:
471       CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
472       break;
473     case TEK_Aggregate: {
474       AggValueSlot Slot =
475         AggValueSlot::forLValue(LV,
476                                 AggValueSlot::IsDestructed,
477                                 AggValueSlot::DoesNotNeedGCBarriers,
478                                 AggValueSlot::IsNotAliased);
479 
480       CGF.EmitAggExpr(Init, Slot);
481       break;
482     }
483     }
484 
485     return;
486   }
487 
488   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
489   assert(Array && "Array initialization without the array type?");
490   llvm::Value *IndexVar
491     = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
492   assert(IndexVar && "Array index variable not loaded");
493 
494   // Initialize this index variable to zero.
495   llvm::Value* Zero
496     = llvm::Constant::getNullValue(
497                               CGF.ConvertType(CGF.getContext().getSizeType()));
498   CGF.Builder.CreateStore(Zero, IndexVar);
499 
500   // Start the loop with a block that tests the condition.
501   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
502   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
503 
504   CGF.EmitBlock(CondBlock);
505 
506   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
507   // Generate: if (loop-index < number-of-elements) fall to the loop body,
508   // otherwise, go to the block after the for-loop.
509   uint64_t NumElements = Array->getSize().getZExtValue();
510   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
511   llvm::Value *NumElementsPtr =
512     llvm::ConstantInt::get(Counter->getType(), NumElements);
513   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
514                                                   "isless");
515 
516   // If the condition is true, execute the body.
517   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
518 
519   CGF.EmitBlock(ForBody);
520   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
521 
522   // Inside the loop body recurse to emit the inner loop or, eventually, the
523   // constructor call.
524   EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
525                            Array->getElementType(), ArrayIndexes, Index + 1);
526 
527   CGF.EmitBlock(ContinueBlock);
528 
529   // Emit the increment of the loop counter.
530   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
531   Counter = CGF.Builder.CreateLoad(IndexVar);
532   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
533   CGF.Builder.CreateStore(NextVal, IndexVar);
534 
535   // Finally, branch back up to the condition for the next iteration.
536   CGF.EmitBranch(CondBlock);
537 
538   // Emit the fall-through block.
539   CGF.EmitBlock(AfterFor, true);
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 = Field->getType();
554 
555   llvm::Value *ThisPtr = CGF.LoadCXXThis();
556   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
557   LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
558 
559   if (MemberInit->isIndirectMemberInitializer()) {
560     // If we are initializing an anonymous union field, drill down to
561     // the field.
562     IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
563     for (const auto *I : IndirectField->chain())
564       LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
565     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
566   } else {
567     LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
568   }
569 
570   // Special case: if we are in a copy or move constructor, and we are copying
571   // an array of PODs or classes with trivial copy constructors, ignore the
572   // AST and perform the copy we know is equivalent.
573   // FIXME: This is hacky at best... if we had a bit more explicit information
574   // in the AST, we could generalize it more easily.
575   const ConstantArrayType *Array
576     = CGF.getContext().getAsConstantArrayType(FieldType);
577   if (Array && Constructor->isDefaulted() &&
578       Constructor->isCopyOrMoveConstructor()) {
579     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
580     CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
581     if (BaseElementTy.isPODType(CGF.getContext()) ||
582         (CE && CE->getConstructor()->isTrivial())) {
583       unsigned SrcArgIndex =
584           CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
585       llvm::Value *SrcPtr
586         = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
587       LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
588       LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
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   switch (getEvaluationKind(FieldType)) {
608   case TEK_Scalar:
609     if (LHS.isSimple()) {
610       EmitExprAsInit(Init, Field, LHS, false);
611     } else {
612       RValue RHS = RValue::get(EmitScalarExpr(Init));
613       EmitStoreThroughLValue(RHS, LHS);
614     }
615     break;
616   case TEK_Complex:
617     EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
618     break;
619   case TEK_Aggregate: {
620     llvm::Value *ArrayIndexVar = nullptr;
621     if (ArrayIndexes.size()) {
622       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
623 
624       // The LHS is a pointer to the first object we'll be constructing, as
625       // a flat array.
626       QualType BaseElementTy = getContext().getBaseElementType(FieldType);
627       llvm::Type *BasePtr = ConvertType(BaseElementTy);
628       BasePtr = llvm::PointerType::getUnqual(BasePtr);
629       llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
630                                                        BasePtr);
631       LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
632 
633       // Create an array index that will be used to walk over all of the
634       // objects we're constructing.
635       ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
636       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
637       Builder.CreateStore(Zero, ArrayIndexVar);
638 
639 
640       // Emit the block variables for the array indices, if any.
641       for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
642         EmitAutoVarDecl(*ArrayIndexes[I]);
643     }
644 
645     EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
646                              ArrayIndexes, 0);
647   }
648   }
649 
650   // Ensure that we destroy this object if an exception is thrown
651   // later in the constructor.
652   QualType::DestructionKind dtorKind = FieldType.isDestructedType();
653   if (needsEHCleanup(dtorKind))
654     pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
655 }
656 
657 /// Checks whether the given constructor is a valid subject for the
658 /// complete-to-base constructor delegation optimization, i.e.
659 /// emitting the complete constructor as a simple call to the base
660 /// constructor.
661 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
662 
663   // Currently we disable the optimization for classes with virtual
664   // bases because (1) the addresses of parameter variables need to be
665   // consistent across all initializers but (2) the delegate function
666   // call necessarily creates a second copy of the parameter variable.
667   //
668   // The limiting example (purely theoretical AFAIK):
669   //   struct A { A(int &c) { c++; } };
670   //   struct B : virtual A {
671   //     B(int count) : A(count) { printf("%d\n", count); }
672   //   };
673   // ...although even this example could in principle be emitted as a
674   // delegation since the address of the parameter doesn't escape.
675   if (Ctor->getParent()->getNumVBases()) {
676     // TODO: white-list trivial vbase initializers.  This case wouldn't
677     // be subject to the restrictions below.
678 
679     // TODO: white-list cases where:
680     //  - there are no non-reference parameters to the constructor
681     //  - the initializers don't access any non-reference parameters
682     //  - the initializers don't take the address of non-reference
683     //    parameters
684     //  - etc.
685     // If we ever add any of the above cases, remember that:
686     //  - function-try-blocks will always blacklist this optimization
687     //  - we need to perform the constructor prologue and cleanup in
688     //    EmitConstructorBody.
689 
690     return false;
691   }
692 
693   // We also disable the optimization for variadic functions because
694   // it's impossible to "re-pass" varargs.
695   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
696     return false;
697 
698   // FIXME: Decide if we can do a delegation of a delegating constructor.
699   if (Ctor->isDelegatingConstructor())
700     return false;
701 
702   return true;
703 }
704 
705 /// EmitConstructorBody - Emits the body of the current constructor.
706 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
707   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
708   CXXCtorType CtorType = CurGD.getCtorType();
709 
710   assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
711           CtorType == Ctor_Complete) &&
712          "can only generate complete ctor for this ABI");
713 
714   // Before we go any further, try the complete->base constructor
715   // delegation optimization.
716   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
717       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
718     if (CGDebugInfo *DI = getDebugInfo())
719       DI->EmitLocation(Builder, Ctor->getLocEnd());
720     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
721     return;
722   }
723 
724   const FunctionDecl *Definition = 0;
725   Stmt *Body = Ctor->getBody(Definition);
726   assert(Definition == Ctor && "emitting wrong constructor body");
727 
728   // Enter the function-try-block before the constructor prologue if
729   // applicable.
730   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
731   if (IsTryBody)
732     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
733 
734   RegionCounter Cnt = getPGORegionCounter(Body);
735   Cnt.beginRegion(Builder);
736 
737   RunCleanupsScope RunCleanups(*this);
738 
739   // TODO: in restricted cases, we can emit the vbase initializers of
740   // a complete ctor and then delegate to the base ctor.
741 
742   // Emit the constructor prologue, i.e. the base and member
743   // initializers.
744   EmitCtorPrologue(Ctor, CtorType, Args);
745 
746   // Emit the body of the statement.
747   if (IsTryBody)
748     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
749   else if (Body)
750     EmitStmt(Body);
751 
752   // Emit any cleanup blocks associated with the member or base
753   // initializers, which includes (along the exceptional path) the
754   // destructors for those members and bases that were fully
755   // constructed.
756   RunCleanups.ForceCleanup();
757 
758   if (IsTryBody)
759     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
760 }
761 
762 namespace {
763   /// RAII object to indicate that codegen is copying the value representation
764   /// instead of the object representation. Useful when copying a struct or
765   /// class which has uninitialized members and we're only performing
766   /// lvalue-to-rvalue conversion on the object but not its members.
767   class CopyingValueRepresentation {
768   public:
769     explicit CopyingValueRepresentation(CodeGenFunction &CGF)
770         : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
771       SO.Bool = false;
772       SO.Enum = false;
773       CGF.SanOpts = &SO;
774     }
775     ~CopyingValueRepresentation() {
776       CGF.SanOpts = OldSanOpts;
777     }
778   private:
779     CodeGenFunction &CGF;
780     SanitizerOptions SO;
781     const SanitizerOptions *OldSanOpts;
782   };
783 }
784 
785 namespace {
786   class FieldMemcpyizer {
787   public:
788     FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
789                     const VarDecl *SrcRec)
790       : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
791         RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
792         FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
793         LastFieldOffset(0), LastAddedFieldIndex(0) {}
794 
795     static bool isMemcpyableField(FieldDecl *F) {
796       Qualifiers Qual = F->getType().getQualifiers();
797       if (Qual.hasVolatile() || Qual.hasObjCLifetime())
798         return false;
799       return true;
800     }
801 
802     void addMemcpyableField(FieldDecl *F) {
803       if (!FirstField)
804         addInitialField(F);
805       else
806         addNextField(F);
807     }
808 
809     CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
810       unsigned LastFieldSize =
811         LastField->isBitField() ?
812           LastField->getBitWidthValue(CGF.getContext()) :
813           CGF.getContext().getTypeSize(LastField->getType());
814       uint64_t MemcpySizeBits =
815         LastFieldOffset + LastFieldSize - FirstByteOffset +
816         CGF.getContext().getCharWidth() - 1;
817       CharUnits MemcpySize =
818         CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
819       return MemcpySize;
820     }
821 
822     void emitMemcpy() {
823       // Give the subclass a chance to bail out if it feels the memcpy isn't
824       // worth it (e.g. Hasn't aggregated enough data).
825       if (!FirstField) {
826         return;
827       }
828 
829       CharUnits Alignment;
830 
831       uint64_t FirstByteOffset;
832       if (FirstField->isBitField()) {
833         const CGRecordLayout &RL =
834           CGF.getTypes().getCGRecordLayout(FirstField->getParent());
835         const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
836         Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
837         // FirstFieldOffset is not appropriate for bitfields,
838         // it won't tell us what the storage offset should be and thus might not
839         // be properly aligned.
840         //
841         // Instead calculate the storage offset using the offset of the field in
842         // the struct type.
843         const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
844         FirstByteOffset =
845             DL.getStructLayout(RL.getLLVMType())
846                 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
847       } else {
848         Alignment = CGF.getContext().getDeclAlign(FirstField);
849         FirstByteOffset = FirstFieldOffset;
850       }
851 
852       assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
853               Alignment) == 0 && "Bad field alignment.");
854 
855       CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
856       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
857       llvm::Value *ThisPtr = CGF.LoadCXXThis();
858       LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
859       LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
860       llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
861       LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
862       LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
863 
864       emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
865                    Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
866                    MemcpySize, Alignment);
867       reset();
868     }
869 
870     void reset() {
871       FirstField = nullptr;
872     }
873 
874   protected:
875     CodeGenFunction &CGF;
876     const CXXRecordDecl *ClassDecl;
877 
878   private:
879 
880     void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
881                       CharUnits Size, CharUnits Alignment) {
882       llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
883       llvm::Type *DBP =
884         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
885       DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
886 
887       llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
888       llvm::Type *SBP =
889         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
890       SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
891 
892       CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
893                                Alignment.getQuantity());
894     }
895 
896     void addInitialField(FieldDecl *F) {
897         FirstField = F;
898         LastField = F;
899         FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
900         LastFieldOffset = FirstFieldOffset;
901         LastAddedFieldIndex = F->getFieldIndex();
902         return;
903       }
904 
905     void addNextField(FieldDecl *F) {
906       // For the most part, the following invariant will hold:
907       //   F->getFieldIndex() == LastAddedFieldIndex + 1
908       // The one exception is that Sema won't add a copy-initializer for an
909       // unnamed bitfield, which will show up here as a gap in the sequence.
910       assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
911              "Cannot aggregate fields out of order.");
912       LastAddedFieldIndex = F->getFieldIndex();
913 
914       // The 'first' and 'last' fields are chosen by offset, rather than field
915       // index. This allows the code to support bitfields, as well as regular
916       // fields.
917       uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
918       if (FOffset < FirstFieldOffset) {
919         FirstField = F;
920         FirstFieldOffset = FOffset;
921       } else if (FOffset > LastFieldOffset) {
922         LastField = F;
923         LastFieldOffset = FOffset;
924       }
925     }
926 
927     const VarDecl *SrcRec;
928     const ASTRecordLayout &RecLayout;
929     FieldDecl *FirstField;
930     FieldDecl *LastField;
931     uint64_t FirstFieldOffset, LastFieldOffset;
932     unsigned LastAddedFieldIndex;
933   };
934 
935   class ConstructorMemcpyizer : public FieldMemcpyizer {
936   private:
937 
938     /// Get source argument for copy constructor. Returns null if not a copy
939     /// constructor.
940     static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
941                                                const CXXConstructorDecl *CD,
942                                                FunctionArgList &Args) {
943       if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
944         return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
945       return nullptr;
946     }
947 
948     // Returns true if a CXXCtorInitializer represents a member initialization
949     // that can be rolled into a memcpy.
950     bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
951       if (!MemcpyableCtor)
952         return false;
953       FieldDecl *Field = MemberInit->getMember();
954       assert(Field && "No field for member init.");
955       QualType FieldType = Field->getType();
956       CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
957 
958       // Bail out on non-POD, not-trivially-constructable members.
959       if (!(CE && CE->getConstructor()->isTrivial()) &&
960           !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
961             FieldType->isReferenceType()))
962         return false;
963 
964       // Bail out on volatile fields.
965       if (!isMemcpyableField(Field))
966         return false;
967 
968       // Otherwise we're good.
969       return true;
970     }
971 
972   public:
973     ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
974                           FunctionArgList &Args)
975       : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
976         ConstructorDecl(CD),
977         MemcpyableCtor(CD->isDefaulted() &&
978                        CD->isCopyOrMoveConstructor() &&
979                        CGF.getLangOpts().getGC() == LangOptions::NonGC),
980         Args(Args) { }
981 
982     void addMemberInitializer(CXXCtorInitializer *MemberInit) {
983       if (isMemberInitMemcpyable(MemberInit)) {
984         AggregatedInits.push_back(MemberInit);
985         addMemcpyableField(MemberInit->getMember());
986       } else {
987         emitAggregatedInits();
988         EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
989                               ConstructorDecl, Args);
990       }
991     }
992 
993     void emitAggregatedInits() {
994       if (AggregatedInits.size() <= 1) {
995         // This memcpy is too small to be worthwhile. Fall back on default
996         // codegen.
997         if (!AggregatedInits.empty()) {
998           CopyingValueRepresentation CVR(CGF);
999           EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1000                                 AggregatedInits[0], ConstructorDecl, Args);
1001         }
1002         reset();
1003         return;
1004       }
1005 
1006       pushEHDestructors();
1007       emitMemcpy();
1008       AggregatedInits.clear();
1009     }
1010 
1011     void pushEHDestructors() {
1012       llvm::Value *ThisPtr = CGF.LoadCXXThis();
1013       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1014       LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1015 
1016       for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1017         QualType FieldType = AggregatedInits[i]->getMember()->getType();
1018         QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1019         if (CGF.needsEHCleanup(dtorKind))
1020           CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1021       }
1022     }
1023 
1024     void finish() {
1025       emitAggregatedInits();
1026     }
1027 
1028   private:
1029     const CXXConstructorDecl *ConstructorDecl;
1030     bool MemcpyableCtor;
1031     FunctionArgList &Args;
1032     SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1033   };
1034 
1035   class AssignmentMemcpyizer : public FieldMemcpyizer {
1036   private:
1037 
1038     // Returns the memcpyable field copied by the given statement, if one
1039     // exists. Otherwise returns null.
1040     FieldDecl *getMemcpyableField(Stmt *S) {
1041       if (!AssignmentsMemcpyable)
1042         return nullptr;
1043       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1044         // Recognise trivial assignments.
1045         if (BO->getOpcode() != BO_Assign)
1046           return nullptr;
1047         MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1048         if (!ME)
1049           return nullptr;
1050         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1051         if (!Field || !isMemcpyableField(Field))
1052           return nullptr;
1053         Stmt *RHS = BO->getRHS();
1054         if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1055           RHS = EC->getSubExpr();
1056         if (!RHS)
1057           return nullptr;
1058         MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1059         if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1060           return nullptr;
1061         return Field;
1062       } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1063         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1064         if (!(MD && (MD->isCopyAssignmentOperator() ||
1065                        MD->isMoveAssignmentOperator()) &&
1066               MD->isTrivial()))
1067           return nullptr;
1068         MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1069         if (!IOA)
1070           return nullptr;
1071         FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1072         if (!Field || !isMemcpyableField(Field))
1073           return nullptr;
1074         MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1075         if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1076           return nullptr;
1077         return Field;
1078       } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1079         FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1080         if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1081           return nullptr;
1082         Expr *DstPtr = CE->getArg(0);
1083         if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1084           DstPtr = DC->getSubExpr();
1085         UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1086         if (!DUO || DUO->getOpcode() != UO_AddrOf)
1087           return nullptr;
1088         MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1089         if (!ME)
1090           return nullptr;
1091         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1092         if (!Field || !isMemcpyableField(Field))
1093           return nullptr;
1094         Expr *SrcPtr = CE->getArg(1);
1095         if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1096           SrcPtr = SC->getSubExpr();
1097         UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1098         if (!SUO || SUO->getOpcode() != UO_AddrOf)
1099           return nullptr;
1100         MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1101         if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1102           return nullptr;
1103         return Field;
1104       }
1105 
1106       return nullptr;
1107     }
1108 
1109     bool AssignmentsMemcpyable;
1110     SmallVector<Stmt*, 16> AggregatedStmts;
1111 
1112   public:
1113 
1114     AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1115                          FunctionArgList &Args)
1116       : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1117         AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1118       assert(Args.size() == 2);
1119     }
1120 
1121     void emitAssignment(Stmt *S) {
1122       FieldDecl *F = getMemcpyableField(S);
1123       if (F) {
1124         addMemcpyableField(F);
1125         AggregatedStmts.push_back(S);
1126       } else {
1127         emitAggregatedStmts();
1128         CGF.EmitStmt(S);
1129       }
1130     }
1131 
1132     void emitAggregatedStmts() {
1133       if (AggregatedStmts.size() <= 1) {
1134         if (!AggregatedStmts.empty()) {
1135           CopyingValueRepresentation CVR(CGF);
1136           CGF.EmitStmt(AggregatedStmts[0]);
1137         }
1138         reset();
1139       }
1140 
1141       emitMemcpy();
1142       AggregatedStmts.clear();
1143     }
1144 
1145     void finish() {
1146       emitAggregatedStmts();
1147     }
1148   };
1149 
1150 }
1151 
1152 /// EmitCtorPrologue - This routine generates necessary code to initialize
1153 /// base classes and non-static data members belonging to this constructor.
1154 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1155                                        CXXCtorType CtorType,
1156                                        FunctionArgList &Args) {
1157   if (CD->isDelegatingConstructor())
1158     return EmitDelegatingCXXConstructorCall(CD, Args);
1159 
1160   const CXXRecordDecl *ClassDecl = CD->getParent();
1161 
1162   CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1163                                           E = CD->init_end();
1164 
1165   llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1166   if (ClassDecl->getNumVBases() &&
1167       !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1168     // The ABIs that don't have constructor variants need to put a branch
1169     // before the virtual base initialization code.
1170     BaseCtorContinueBB =
1171       CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1172     assert(BaseCtorContinueBB);
1173   }
1174 
1175   // Virtual base initializers first.
1176   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1177     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1178   }
1179 
1180   if (BaseCtorContinueBB) {
1181     // Complete object handler should continue to the remaining initializers.
1182     Builder.CreateBr(BaseCtorContinueBB);
1183     EmitBlock(BaseCtorContinueBB);
1184   }
1185 
1186   // Then, non-virtual base initializers.
1187   for (; B != E && (*B)->isBaseInitializer(); B++) {
1188     assert(!(*B)->isBaseVirtual());
1189     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1190   }
1191 
1192   InitializeVTablePointers(ClassDecl);
1193 
1194   // And finally, initialize class members.
1195   FieldConstructionScope FCS(*this, CXXThisValue);
1196   ConstructorMemcpyizer CM(*this, CD, Args);
1197   for (; B != E; B++) {
1198     CXXCtorInitializer *Member = (*B);
1199     assert(!Member->isBaseInitializer());
1200     assert(Member->isAnyMemberInitializer() &&
1201            "Delegating initializer on non-delegating constructor");
1202     CM.addMemberInitializer(Member);
1203   }
1204   CM.finish();
1205 }
1206 
1207 static bool
1208 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1209 
1210 static bool
1211 HasTrivialDestructorBody(ASTContext &Context,
1212                          const CXXRecordDecl *BaseClassDecl,
1213                          const CXXRecordDecl *MostDerivedClassDecl)
1214 {
1215   // If the destructor is trivial we don't have to check anything else.
1216   if (BaseClassDecl->hasTrivialDestructor())
1217     return true;
1218 
1219   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1220     return false;
1221 
1222   // Check fields.
1223   for (const auto *Field : BaseClassDecl->fields())
1224     if (!FieldHasTrivialDestructorBody(Context, Field))
1225       return false;
1226 
1227   // Check non-virtual bases.
1228   for (const auto &I : BaseClassDecl->bases()) {
1229     if (I.isVirtual())
1230       continue;
1231 
1232     const CXXRecordDecl *NonVirtualBase =
1233       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1234     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1235                                   MostDerivedClassDecl))
1236       return false;
1237   }
1238 
1239   if (BaseClassDecl == MostDerivedClassDecl) {
1240     // Check virtual bases.
1241     for (const auto &I : BaseClassDecl->vbases()) {
1242       const CXXRecordDecl *VirtualBase =
1243         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1244       if (!HasTrivialDestructorBody(Context, VirtualBase,
1245                                     MostDerivedClassDecl))
1246         return false;
1247     }
1248   }
1249 
1250   return true;
1251 }
1252 
1253 static bool
1254 FieldHasTrivialDestructorBody(ASTContext &Context,
1255                               const FieldDecl *Field)
1256 {
1257   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1258 
1259   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1260   if (!RT)
1261     return true;
1262 
1263   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1264   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1265 }
1266 
1267 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1268 /// any vtable pointers before calling this destructor.
1269 static bool CanSkipVTablePointerInitialization(ASTContext &Context,
1270                                                const CXXDestructorDecl *Dtor) {
1271   if (!Dtor->hasTrivialBody())
1272     return false;
1273 
1274   // Check the fields.
1275   const CXXRecordDecl *ClassDecl = Dtor->getParent();
1276   for (const auto *Field : ClassDecl->fields())
1277     if (!FieldHasTrivialDestructorBody(Context, Field))
1278       return false;
1279 
1280   return true;
1281 }
1282 
1283 /// EmitDestructorBody - Emits the body of the current destructor.
1284 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1285   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1286   CXXDtorType DtorType = CurGD.getDtorType();
1287 
1288   // The call to operator delete in a deleting destructor happens
1289   // outside of the function-try-block, which means it's always
1290   // possible to delegate the destructor body to the complete
1291   // destructor.  Do so.
1292   if (DtorType == Dtor_Deleting) {
1293     EnterDtorCleanups(Dtor, Dtor_Deleting);
1294     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1295                           /*Delegating=*/false, LoadCXXThis());
1296     PopCleanupBlock();
1297     return;
1298   }
1299 
1300   Stmt *Body = Dtor->getBody();
1301 
1302   // If the body is a function-try-block, enter the try before
1303   // anything else.
1304   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1305   if (isTryBody)
1306     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1307 
1308   // Enter the epilogue cleanups.
1309   RunCleanupsScope DtorEpilogue(*this);
1310 
1311   // If this is the complete variant, just invoke the base variant;
1312   // the epilogue will destruct the virtual bases.  But we can't do
1313   // this optimization if the body is a function-try-block, because
1314   // we'd introduce *two* handler blocks.  In the Microsoft ABI, we
1315   // always delegate because we might not have a definition in this TU.
1316   switch (DtorType) {
1317   case Dtor_Comdat:
1318     llvm_unreachable("not expecting a COMDAT");
1319 
1320   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1321 
1322   case Dtor_Complete:
1323     assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1324            "can't emit a dtor without a body for non-Microsoft ABIs");
1325 
1326     // Enter the cleanup scopes for virtual bases.
1327     EnterDtorCleanups(Dtor, Dtor_Complete);
1328 
1329     if (!isTryBody) {
1330       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1331                             /*Delegating=*/false, LoadCXXThis());
1332       break;
1333     }
1334     // Fallthrough: act like we're in the base variant.
1335 
1336   case Dtor_Base:
1337     assert(Body);
1338 
1339     RegionCounter Cnt = getPGORegionCounter(Body);
1340     Cnt.beginRegion(Builder);
1341 
1342     // Enter the cleanup scopes for fields and non-virtual bases.
1343     EnterDtorCleanups(Dtor, Dtor_Base);
1344 
1345     // Initialize the vtable pointers before entering the body.
1346     if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1347         InitializeVTablePointers(Dtor->getParent());
1348 
1349     if (isTryBody)
1350       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1351     else if (Body)
1352       EmitStmt(Body);
1353     else {
1354       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1355       // nothing to do besides what's in the epilogue
1356     }
1357     // -fapple-kext must inline any call to this dtor into
1358     // the caller's body.
1359     if (getLangOpts().AppleKext)
1360       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1361     break;
1362   }
1363 
1364   // Jump out through the epilogue cleanups.
1365   DtorEpilogue.ForceCleanup();
1366 
1367   // Exit the try if applicable.
1368   if (isTryBody)
1369     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1370 }
1371 
1372 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1373   const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1374   const Stmt *RootS = AssignOp->getBody();
1375   assert(isa<CompoundStmt>(RootS) &&
1376          "Body of an implicit assignment operator should be compound stmt.");
1377   const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1378 
1379   LexicalScope Scope(*this, RootCS->getSourceRange());
1380 
1381   AssignmentMemcpyizer AM(*this, AssignOp, Args);
1382   for (auto *I : RootCS->body())
1383     AM.emitAssignment(I);
1384   AM.finish();
1385 }
1386 
1387 namespace {
1388   /// Call the operator delete associated with the current destructor.
1389   struct CallDtorDelete : EHScopeStack::Cleanup {
1390     CallDtorDelete() {}
1391 
1392     void Emit(CodeGenFunction &CGF, Flags flags) override {
1393       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1394       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1395       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1396                          CGF.getContext().getTagDeclType(ClassDecl));
1397     }
1398   };
1399 
1400   struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1401     llvm::Value *ShouldDeleteCondition;
1402   public:
1403     CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1404       : ShouldDeleteCondition(ShouldDeleteCondition) {
1405       assert(ShouldDeleteCondition != nullptr);
1406     }
1407 
1408     void Emit(CodeGenFunction &CGF, Flags flags) override {
1409       llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1410       llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1411       llvm::Value *ShouldCallDelete
1412         = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1413       CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1414 
1415       CGF.EmitBlock(callDeleteBB);
1416       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1417       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1418       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1419                          CGF.getContext().getTagDeclType(ClassDecl));
1420       CGF.Builder.CreateBr(continueBB);
1421 
1422       CGF.EmitBlock(continueBB);
1423     }
1424   };
1425 
1426   class DestroyField  : public EHScopeStack::Cleanup {
1427     const FieldDecl *field;
1428     CodeGenFunction::Destroyer *destroyer;
1429     bool useEHCleanupForArray;
1430 
1431   public:
1432     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1433                  bool useEHCleanupForArray)
1434       : field(field), destroyer(destroyer),
1435         useEHCleanupForArray(useEHCleanupForArray) {}
1436 
1437     void Emit(CodeGenFunction &CGF, Flags flags) override {
1438       // Find the address of the field.
1439       llvm::Value *thisValue = CGF.LoadCXXThis();
1440       QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1441       LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1442       LValue LV = CGF.EmitLValueForField(ThisLV, field);
1443       assert(LV.isSimple());
1444 
1445       CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1446                       flags.isForNormalCleanup() && useEHCleanupForArray);
1447     }
1448   };
1449 }
1450 
1451 /// \brief Emit all code that comes at the end of class's
1452 /// destructor. This is to call destructors on members and base classes
1453 /// in reverse order of their construction.
1454 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1455                                         CXXDtorType DtorType) {
1456   assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1457          "Should not emit dtor epilogue for non-exported trivial dtor!");
1458 
1459   // The deleting-destructor phase just needs to call the appropriate
1460   // operator delete that Sema picked up.
1461   if (DtorType == Dtor_Deleting) {
1462     assert(DD->getOperatorDelete() &&
1463            "operator delete missing - EnterDtorCleanups");
1464     if (CXXStructorImplicitParamValue) {
1465       // If there is an implicit param to the deleting dtor, it's a boolean
1466       // telling whether we should call delete at the end of the dtor.
1467       EHStack.pushCleanup<CallDtorDeleteConditional>(
1468           NormalAndEHCleanup, CXXStructorImplicitParamValue);
1469     } else {
1470       EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1471     }
1472     return;
1473   }
1474 
1475   const CXXRecordDecl *ClassDecl = DD->getParent();
1476 
1477   // Unions have no bases and do not call field destructors.
1478   if (ClassDecl->isUnion())
1479     return;
1480 
1481   // The complete-destructor phase just destructs all the virtual bases.
1482   if (DtorType == Dtor_Complete) {
1483 
1484     // We push them in the forward order so that they'll be popped in
1485     // the reverse order.
1486     for (const auto &Base : ClassDecl->vbases()) {
1487       CXXRecordDecl *BaseClassDecl
1488         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1489 
1490       // Ignore trivial destructors.
1491       if (BaseClassDecl->hasTrivialDestructor())
1492         continue;
1493 
1494       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1495                                         BaseClassDecl,
1496                                         /*BaseIsVirtual*/ true);
1497     }
1498 
1499     return;
1500   }
1501 
1502   assert(DtorType == Dtor_Base);
1503 
1504   // Destroy non-virtual bases.
1505   for (const auto &Base : ClassDecl->bases()) {
1506     // Ignore virtual bases.
1507     if (Base.isVirtual())
1508       continue;
1509 
1510     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1511 
1512     // Ignore trivial destructors.
1513     if (BaseClassDecl->hasTrivialDestructor())
1514       continue;
1515 
1516     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1517                                       BaseClassDecl,
1518                                       /*BaseIsVirtual*/ false);
1519   }
1520 
1521   // Destroy direct fields.
1522   for (const auto *Field : ClassDecl->fields()) {
1523     QualType type = Field->getType();
1524     QualType::DestructionKind dtorKind = type.isDestructedType();
1525     if (!dtorKind) continue;
1526 
1527     // Anonymous union members do not have their destructors called.
1528     const RecordType *RT = type->getAsUnionType();
1529     if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1530 
1531     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1532     EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1533                                       getDestroyer(dtorKind),
1534                                       cleanupKind & EHCleanup);
1535   }
1536 }
1537 
1538 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1539 /// constructor for each of several members of an array.
1540 ///
1541 /// \param ctor the constructor to call for each element
1542 /// \param arrayType the type of the array to initialize
1543 /// \param arrayBegin an arrayType*
1544 /// \param zeroInitialize true if each element should be
1545 ///   zero-initialized before it is constructed
1546 void CodeGenFunction::EmitCXXAggrConstructorCall(
1547     const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1548     llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
1549   QualType elementType;
1550   llvm::Value *numElements =
1551     emitArrayLength(arrayType, elementType, arrayBegin);
1552 
1553   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
1554 }
1555 
1556 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1557 /// constructor for each of several members of an array.
1558 ///
1559 /// \param ctor the constructor to call for each element
1560 /// \param numElements the number of elements in the array;
1561 ///   may be zero
1562 /// \param arrayBegin a T*, where T is the type constructed by ctor
1563 /// \param zeroInitialize true if each element should be
1564 ///   zero-initialized before it is constructed
1565 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1566                                                  llvm::Value *numElements,
1567                                                  llvm::Value *arrayBegin,
1568                                                  const CXXConstructExpr *E,
1569                                                  bool zeroInitialize) {
1570 
1571   // It's legal for numElements to be zero.  This can happen both
1572   // dynamically, because x can be zero in 'new A[x]', and statically,
1573   // because of GCC extensions that permit zero-length arrays.  There
1574   // are probably legitimate places where we could assume that this
1575   // doesn't happen, but it's not clear that it's worth it.
1576   llvm::BranchInst *zeroCheckBranch = nullptr;
1577 
1578   // Optimize for a constant count.
1579   llvm::ConstantInt *constantCount
1580     = dyn_cast<llvm::ConstantInt>(numElements);
1581   if (constantCount) {
1582     // Just skip out if the constant count is zero.
1583     if (constantCount->isZero()) return;
1584 
1585   // Otherwise, emit the check.
1586   } else {
1587     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1588     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1589     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1590     EmitBlock(loopBB);
1591   }
1592 
1593   // Find the end of the array.
1594   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1595                                                     "arrayctor.end");
1596 
1597   // Enter the loop, setting up a phi for the current location to initialize.
1598   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1599   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1600   EmitBlock(loopBB);
1601   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1602                                          "arrayctor.cur");
1603   cur->addIncoming(arrayBegin, entryBB);
1604 
1605   // Inside the loop body, emit the constructor call on the array element.
1606 
1607   QualType type = getContext().getTypeDeclType(ctor->getParent());
1608 
1609   // Zero initialize the storage, if requested.
1610   if (zeroInitialize)
1611     EmitNullInitialization(cur, type);
1612 
1613   // C++ [class.temporary]p4:
1614   // There are two contexts in which temporaries are destroyed at a different
1615   // point than the end of the full-expression. The first context is when a
1616   // default constructor is called to initialize an element of an array.
1617   // If the constructor has one or more default arguments, the destruction of
1618   // every temporary created in a default argument expression is sequenced
1619   // before the construction of the next array element, if any.
1620 
1621   {
1622     RunCleanupsScope Scope(*this);
1623 
1624     // Evaluate the constructor and its arguments in a regular
1625     // partial-destroy cleanup.
1626     if (getLangOpts().Exceptions &&
1627         !ctor->getParent()->hasTrivialDestructor()) {
1628       Destroyer *destroyer = destroyCXXObject;
1629       pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1630     }
1631 
1632     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1633                            /*Delegating=*/false, cur, E);
1634   }
1635 
1636   // Go to the next element.
1637   llvm::Value *next =
1638     Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1639                               "arrayctor.next");
1640   cur->addIncoming(next, Builder.GetInsertBlock());
1641 
1642   // Check whether that's the end of the loop.
1643   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1644   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1645   Builder.CreateCondBr(done, contBB, loopBB);
1646 
1647   // Patch the earlier check to skip over the loop.
1648   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1649 
1650   EmitBlock(contBB);
1651 }
1652 
1653 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1654                                        llvm::Value *addr,
1655                                        QualType type) {
1656   const RecordType *rtype = type->castAs<RecordType>();
1657   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1658   const CXXDestructorDecl *dtor = record->getDestructor();
1659   assert(!dtor->isTrivial());
1660   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1661                             /*Delegating=*/false, addr);
1662 }
1663 
1664 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1665                                              CXXCtorType Type,
1666                                              bool ForVirtualBase,
1667                                              bool Delegating, llvm::Value *This,
1668                                              const CXXConstructExpr *E) {
1669   // If this is a trivial constructor, just emit what's needed.
1670   if (D->isTrivial()) {
1671     if (E->getNumArgs() == 0) {
1672       // Trivial default constructor, no codegen required.
1673       assert(D->isDefaultConstructor() &&
1674              "trivial 0-arg ctor not a default ctor");
1675       return;
1676     }
1677 
1678     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1679     assert(D->isCopyOrMoveConstructor() &&
1680            "trivial 1-arg ctor not a copy/move ctor");
1681 
1682     const Expr *Arg = E->getArg(0);
1683     QualType Ty = Arg->getType();
1684     llvm::Value *Src = EmitLValue(Arg).getAddress();
1685     EmitAggregateCopy(This, Src, Ty);
1686     return;
1687   }
1688 
1689   // C++11 [class.mfct.non-static]p2:
1690   //   If a non-static member function of a class X is called for an object that
1691   //   is not of type X, or of a type derived from X, the behavior is undefined.
1692   // FIXME: Provide a source location here.
1693   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1694                 getContext().getRecordType(D->getParent()));
1695 
1696   CallArgList Args;
1697 
1698   // Push the this ptr.
1699   Args.add(RValue::get(This), D->getThisType(getContext()));
1700 
1701   // Add the rest of the user-supplied arguments.
1702   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1703   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
1704 
1705   // Insert any ABI-specific implicit constructor arguments.
1706   unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1707       *this, D, Type, ForVirtualBase, Delegating, Args);
1708 
1709   // Emit the call.
1710   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
1711   const CGFunctionInfo &Info =
1712       CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
1713   EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
1714 }
1715 
1716 void
1717 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1718                                         llvm::Value *This, llvm::Value *Src,
1719                                         const CXXConstructExpr *E) {
1720   if (D->isTrivial()) {
1721     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1722     assert(D->isCopyOrMoveConstructor() &&
1723            "trivial 1-arg ctor not a copy/move ctor");
1724     EmitAggregateCopy(This, Src, E->arg_begin()->getType());
1725     return;
1726   }
1727   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
1728   assert(D->isInstance() &&
1729          "Trying to emit a member call expr on a static method!");
1730 
1731   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1732 
1733   CallArgList Args;
1734 
1735   // Push the this ptr.
1736   Args.add(RValue::get(This), D->getThisType(getContext()));
1737 
1738   // Push the src ptr.
1739   QualType QT = *(FPT->param_type_begin());
1740   llvm::Type *t = CGM.getTypes().ConvertType(QT);
1741   Src = Builder.CreateBitCast(Src, t);
1742   Args.add(RValue::get(Src), QT);
1743 
1744   // Skip over first argument (Src).
1745   EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1746                /*ParamsToSkip*/ 1);
1747 
1748   EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1749            Callee, ReturnValueSlot(), Args, D);
1750 }
1751 
1752 void
1753 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1754                                                 CXXCtorType CtorType,
1755                                                 const FunctionArgList &Args,
1756                                                 SourceLocation Loc) {
1757   CallArgList DelegateArgs;
1758 
1759   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1760   assert(I != E && "no parameters to constructor");
1761 
1762   // this
1763   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1764   ++I;
1765 
1766   // vtt
1767   if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
1768                                          /*ForVirtualBase=*/false,
1769                                          /*Delegating=*/true)) {
1770     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1771     DelegateArgs.add(RValue::get(VTT), VoidPP);
1772 
1773     if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
1774       assert(I != E && "cannot skip vtt parameter, already done with args");
1775       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1776       ++I;
1777     }
1778   }
1779 
1780   // Explicit arguments.
1781   for (; I != E; ++I) {
1782     const VarDecl *param = *I;
1783     // FIXME: per-argument source location
1784     EmitDelegateCallArg(DelegateArgs, param, Loc);
1785   }
1786 
1787   llvm::Value *Callee =
1788       CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
1789   EmitCall(CGM.getTypes()
1790                .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
1791            Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1792 }
1793 
1794 namespace {
1795   struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1796     const CXXDestructorDecl *Dtor;
1797     llvm::Value *Addr;
1798     CXXDtorType Type;
1799 
1800     CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1801                            CXXDtorType Type)
1802       : Dtor(D), Addr(Addr), Type(Type) {}
1803 
1804     void Emit(CodeGenFunction &CGF, Flags flags) override {
1805       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1806                                 /*Delegating=*/true, Addr);
1807     }
1808   };
1809 }
1810 
1811 void
1812 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1813                                                   const FunctionArgList &Args) {
1814   assert(Ctor->isDelegatingConstructor());
1815 
1816   llvm::Value *ThisPtr = LoadCXXThis();
1817 
1818   QualType Ty = getContext().getTagDeclType(Ctor->getParent());
1819   CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1820   AggValueSlot AggSlot =
1821     AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
1822                           AggValueSlot::IsDestructed,
1823                           AggValueSlot::DoesNotNeedGCBarriers,
1824                           AggValueSlot::IsNotAliased);
1825 
1826   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1827 
1828   const CXXRecordDecl *ClassDecl = Ctor->getParent();
1829   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1830     CXXDtorType Type =
1831       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1832 
1833     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1834                                                 ClassDecl->getDestructor(),
1835                                                 ThisPtr, Type);
1836   }
1837 }
1838 
1839 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1840                                             CXXDtorType Type,
1841                                             bool ForVirtualBase,
1842                                             bool Delegating,
1843                                             llvm::Value *This) {
1844   CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1845                                      Delegating, This);
1846 }
1847 
1848 namespace {
1849   struct CallLocalDtor : EHScopeStack::Cleanup {
1850     const CXXDestructorDecl *Dtor;
1851     llvm::Value *Addr;
1852 
1853     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1854       : Dtor(D), Addr(Addr) {}
1855 
1856     void Emit(CodeGenFunction &CGF, Flags flags) override {
1857       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1858                                 /*ForVirtualBase=*/false,
1859                                 /*Delegating=*/false, Addr);
1860     }
1861   };
1862 }
1863 
1864 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1865                                             llvm::Value *Addr) {
1866   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1867 }
1868 
1869 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1870   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1871   if (!ClassDecl) return;
1872   if (ClassDecl->hasTrivialDestructor()) return;
1873 
1874   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1875   assert(D && D->isUsed() && "destructor not marked as used!");
1876   PushDestructorCleanup(D, Addr);
1877 }
1878 
1879 void
1880 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1881                                          const CXXRecordDecl *NearestVBase,
1882                                          CharUnits OffsetFromNearestVBase,
1883                                          const CXXRecordDecl *VTableClass) {
1884   // Compute the address point.
1885   bool NeedsVirtualOffset;
1886   llvm::Value *VTableAddressPoint =
1887       CGM.getCXXABI().getVTableAddressPointInStructor(
1888           *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1889   if (!VTableAddressPoint)
1890     return;
1891 
1892   // Compute where to store the address point.
1893   llvm::Value *VirtualOffset = nullptr;
1894   CharUnits NonVirtualOffset = CharUnits::Zero();
1895 
1896   if (NeedsVirtualOffset) {
1897     // We need to use the virtual base offset offset because the virtual base
1898     // might have a different offset in the most derived class.
1899     VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1900                                                               LoadCXXThis(),
1901                                                               VTableClass,
1902                                                               NearestVBase);
1903     NonVirtualOffset = OffsetFromNearestVBase;
1904   } else {
1905     // We can just use the base offset in the complete class.
1906     NonVirtualOffset = Base.getBaseOffset();
1907   }
1908 
1909   // Apply the offsets.
1910   llvm::Value *VTableField = LoadCXXThis();
1911 
1912   if (!NonVirtualOffset.isZero() || VirtualOffset)
1913     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1914                                                   NonVirtualOffset,
1915                                                   VirtualOffset);
1916 
1917   // Finally, store the address point.
1918   llvm::Type *AddressPointPtrTy =
1919     VTableAddressPoint->getType()->getPointerTo();
1920   VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1921   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1922   CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
1923 }
1924 
1925 void
1926 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
1927                                           const CXXRecordDecl *NearestVBase,
1928                                           CharUnits OffsetFromNearestVBase,
1929                                           bool BaseIsNonVirtualPrimaryBase,
1930                                           const CXXRecordDecl *VTableClass,
1931                                           VisitedVirtualBasesSetTy& VBases) {
1932   // If this base is a non-virtual primary base the address point has already
1933   // been set.
1934   if (!BaseIsNonVirtualPrimaryBase) {
1935     // Initialize the vtable pointer for this base.
1936     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1937                             VTableClass);
1938   }
1939 
1940   const CXXRecordDecl *RD = Base.getBase();
1941 
1942   // Traverse bases.
1943   for (const auto &I : RD->bases()) {
1944     CXXRecordDecl *BaseDecl
1945       = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
1946 
1947     // Ignore classes without a vtable.
1948     if (!BaseDecl->isDynamicClass())
1949       continue;
1950 
1951     CharUnits BaseOffset;
1952     CharUnits BaseOffsetFromNearestVBase;
1953     bool BaseDeclIsNonVirtualPrimaryBase;
1954 
1955     if (I.isVirtual()) {
1956       // Check if we've visited this virtual base before.
1957       if (!VBases.insert(BaseDecl))
1958         continue;
1959 
1960       const ASTRecordLayout &Layout =
1961         getContext().getASTRecordLayout(VTableClass);
1962 
1963       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1964       BaseOffsetFromNearestVBase = CharUnits::Zero();
1965       BaseDeclIsNonVirtualPrimaryBase = false;
1966     } else {
1967       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1968 
1969       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
1970       BaseOffsetFromNearestVBase =
1971         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
1972       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
1973     }
1974 
1975     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
1976                              I.isVirtual() ? BaseDecl : NearestVBase,
1977                              BaseOffsetFromNearestVBase,
1978                              BaseDeclIsNonVirtualPrimaryBase,
1979                              VTableClass, VBases);
1980   }
1981 }
1982 
1983 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1984   // Ignore classes without a vtable.
1985   if (!RD->isDynamicClass())
1986     return;
1987 
1988   // Initialize the vtable pointers for this class and all of its bases.
1989   VisitedVirtualBasesSetTy VBases;
1990   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1991                            /*NearestVBase=*/nullptr,
1992                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
1993                            /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
1994 
1995   if (RD->getNumVBases())
1996     CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
1997 }
1998 
1999 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
2000                                            llvm::Type *Ty) {
2001   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
2002   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2003   CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2004   return VTable;
2005 }
2006 
2007 
2008 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2009 // quite what we want.
2010 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2011   while (true) {
2012     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2013       E = PE->getSubExpr();
2014       continue;
2015     }
2016 
2017     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2018       if (CE->getCastKind() == CK_NoOp) {
2019         E = CE->getSubExpr();
2020         continue;
2021       }
2022     }
2023     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2024       if (UO->getOpcode() == UO_Extension) {
2025         E = UO->getSubExpr();
2026         continue;
2027       }
2028     }
2029     return E;
2030   }
2031 }
2032 
2033 bool
2034 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2035                                                    const CXXMethodDecl *MD) {
2036   // When building with -fapple-kext, all calls must go through the vtable since
2037   // the kernel linker can do runtime patching of vtables.
2038   if (getLangOpts().AppleKext)
2039     return false;
2040 
2041   // If the most derived class is marked final, we know that no subclass can
2042   // override this member function and so we can devirtualize it. For example:
2043   //
2044   // struct A { virtual void f(); }
2045   // struct B final : A { };
2046   //
2047   // void f(B *b) {
2048   //   b->f();
2049   // }
2050   //
2051   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
2052   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2053     return true;
2054 
2055   // If the member function is marked 'final', we know that it can't be
2056   // overridden and can therefore devirtualize it.
2057   if (MD->hasAttr<FinalAttr>())
2058     return true;
2059 
2060   // Similarly, if the class itself is marked 'final' it can't be overridden
2061   // and we can therefore devirtualize the member function call.
2062   if (MD->getParent()->hasAttr<FinalAttr>())
2063     return true;
2064 
2065   Base = skipNoOpCastsAndParens(Base);
2066   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2067     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2068       // This is a record decl. We know the type and can devirtualize it.
2069       return VD->getType()->isRecordType();
2070     }
2071 
2072     return false;
2073   }
2074 
2075   // We can devirtualize calls on an object accessed by a class member access
2076   // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2077   // a derived class object constructed in the same location.
2078   if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2079     if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2080       return VD->getType()->isRecordType();
2081 
2082   // We can always devirtualize calls on temporary object expressions.
2083   if (isa<CXXConstructExpr>(Base))
2084     return true;
2085 
2086   // And calls on bound temporaries.
2087   if (isa<CXXBindTemporaryExpr>(Base))
2088     return true;
2089 
2090   // Check if this is a call expr that returns a record type.
2091   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2092     return CE->getCallReturnType()->isRecordType();
2093 
2094   // We can't devirtualize the call.
2095   return false;
2096 }
2097 
2098 llvm::Value *
2099 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2100                                              const CXXMethodDecl *MD,
2101                                              llvm::Value *This) {
2102   llvm::FunctionType *fnType =
2103     CGM.getTypes().GetFunctionType(
2104                              CGM.getTypes().arrangeCXXMethodDeclaration(MD));
2105 
2106   if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
2107     return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
2108 
2109   return CGM.GetAddrOfFunction(MD, fnType);
2110 }
2111 
2112 void CodeGenFunction::EmitForwardingCallToLambda(
2113                                       const CXXMethodDecl *callOperator,
2114                                       CallArgList &callArgs) {
2115   // Get the address of the call operator.
2116   const CGFunctionInfo &calleeFnInfo =
2117     CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2118   llvm::Value *callee =
2119     CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2120                           CGM.getTypes().GetFunctionType(calleeFnInfo));
2121 
2122   // Prepare the return slot.
2123   const FunctionProtoType *FPT =
2124     callOperator->getType()->castAs<FunctionProtoType>();
2125   QualType resultType = FPT->getReturnType();
2126   ReturnValueSlot returnSlot;
2127   if (!resultType->isVoidType() &&
2128       calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2129       !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2130     returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2131 
2132   // We don't need to separately arrange the call arguments because
2133   // the call can't be variadic anyway --- it's impossible to forward
2134   // variadic arguments.
2135 
2136   // Now emit our call.
2137   RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2138                        callArgs, callOperator);
2139 
2140   // If necessary, copy the returned value into the slot.
2141   if (!resultType->isVoidType() && returnSlot.isNull())
2142     EmitReturnOfRValue(RV, resultType);
2143   else
2144     EmitBranchThroughCleanup(ReturnBlock);
2145 }
2146 
2147 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2148   const BlockDecl *BD = BlockInfo->getBlockDecl();
2149   const VarDecl *variable = BD->capture_begin()->getVariable();
2150   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2151 
2152   // Start building arguments for forwarding call
2153   CallArgList CallArgs;
2154 
2155   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2156   llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2157   CallArgs.add(RValue::get(ThisPtr), ThisType);
2158 
2159   // Add the rest of the parameters.
2160   for (auto param : BD->params())
2161     EmitDelegateCallArg(CallArgs, param, param->getLocStart());
2162 
2163   assert(!Lambda->isGenericLambda() &&
2164             "generic lambda interconversion to block not implemented");
2165   EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
2166 }
2167 
2168 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2169   if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2170     // FIXME: Making this work correctly is nasty because it requires either
2171     // cloning the body of the call operator or making the call operator forward.
2172     CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2173     return;
2174   }
2175 
2176   EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
2177 }
2178 
2179 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2180   const CXXRecordDecl *Lambda = MD->getParent();
2181 
2182   // Start building arguments for forwarding call
2183   CallArgList CallArgs;
2184 
2185   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2186   llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2187   CallArgs.add(RValue::get(ThisPtr), ThisType);
2188 
2189   // Add the rest of the parameters.
2190   for (auto Param : MD->params())
2191     EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2192 
2193   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2194   // For a generic lambda, find the corresponding call operator specialization
2195   // to which the call to the static-invoker shall be forwarded.
2196   if (Lambda->isGenericLambda()) {
2197     assert(MD->isFunctionTemplateSpecialization());
2198     const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2199     FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2200     void *InsertPos = nullptr;
2201     FunctionDecl *CorrespondingCallOpSpecialization =
2202         CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2203     assert(CorrespondingCallOpSpecialization);
2204     CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2205   }
2206   EmitForwardingCallToLambda(CallOp, CallArgs);
2207 }
2208 
2209 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2210   if (MD->isVariadic()) {
2211     // FIXME: Making this work correctly is nasty because it requires either
2212     // cloning the body of the call operator or making the call operator forward.
2213     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2214     return;
2215   }
2216 
2217   EmitLambdaDelegatingInvokeBody(MD);
2218 }
2219