1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
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 code generation of C++ expressions
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "clang/CodeGen/CGFunctionInfo.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Intrinsics.h"
23 
24 using namespace clang;
25 using namespace CodeGen;
26 
27 static RequiredArgs
28 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
29                                   llvm::Value *This, llvm::Value *ImplicitParam,
30                                   QualType ImplicitParamTy, const CallExpr *CE,
31                                   CallArgList &Args, CallArgList *RtlArgs) {
32   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
33          isa<CXXOperatorCallExpr>(CE));
34   assert(MD->isInstance() &&
35          "Trying to emit a member or operator call expr on a static method!");
36   ASTContext &C = CGF.getContext();
37 
38   // Push the this ptr.
39   const CXXRecordDecl *RD =
40       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
41   Args.add(RValue::get(This),
42            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
43 
44   // If there is an implicit parameter (e.g. VTT), emit it.
45   if (ImplicitParam) {
46     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
47   }
48 
49   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
50   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
51 
52   // And the rest of the call args.
53   if (RtlArgs) {
54     // Special case: if the caller emitted the arguments right-to-left already
55     // (prior to emitting the *this argument), we're done. This happens for
56     // assignment operators.
57     Args.addFrom(*RtlArgs);
58   } else if (CE) {
59     // Special case: skip first argument of CXXOperatorCall (it is "this").
60     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
61     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
62                      CE->getDirectCallee());
63   } else {
64     assert(
65         FPT->getNumParams() == 0 &&
66         "No CallExpr specified for function with non-zero number of arguments");
67   }
68   return required;
69 }
70 
71 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
72     const CXXMethodDecl *MD, const CGCallee &Callee,
73     ReturnValueSlot ReturnValue,
74     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
75     const CallExpr *CE, CallArgList *RtlArgs) {
76   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77   CallArgList Args;
78   RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
80   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required);
81   return EmitCall(FnInfo, Callee, ReturnValue, Args);
82 }
83 
84 RValue CodeGenFunction::EmitCXXDestructorCall(
85     const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
86     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
87     StructorType Type) {
88   CallArgList Args;
89   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
90                                     ImplicitParamTy, CE, Args, nullptr);
91   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
92                   Callee, ReturnValueSlot(), Args);
93 }
94 
95 RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
96                                             const CXXPseudoDestructorExpr *E) {
97   QualType DestroyedType = E->getDestroyedType();
98   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
99     // Automatic Reference Counting:
100     //   If the pseudo-expression names a retainable object with weak or
101     //   strong lifetime, the object shall be released.
102     Expr *BaseExpr = E->getBase();
103     Address BaseValue = Address::invalid();
104     Qualifiers BaseQuals;
105 
106     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
107     if (E->isArrow()) {
108       BaseValue = EmitPointerWithAlignment(BaseExpr);
109       const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
110       BaseQuals = PTy->getPointeeType().getQualifiers();
111     } else {
112       LValue BaseLV = EmitLValue(BaseExpr);
113       BaseValue = BaseLV.getAddress();
114       QualType BaseTy = BaseExpr->getType();
115       BaseQuals = BaseTy.getQualifiers();
116     }
117 
118     switch (DestroyedType.getObjCLifetime()) {
119     case Qualifiers::OCL_None:
120     case Qualifiers::OCL_ExplicitNone:
121     case Qualifiers::OCL_Autoreleasing:
122       break;
123 
124     case Qualifiers::OCL_Strong:
125       EmitARCRelease(Builder.CreateLoad(BaseValue,
126                         DestroyedType.isVolatileQualified()),
127                      ARCPreciseLifetime);
128       break;
129 
130     case Qualifiers::OCL_Weak:
131       EmitARCDestroyWeak(BaseValue);
132       break;
133     }
134   } else {
135     // C++ [expr.pseudo]p1:
136     //   The result shall only be used as the operand for the function call
137     //   operator (), and the result of such a call has type void. The only
138     //   effect is the evaluation of the postfix-expression before the dot or
139     //   arrow.
140     EmitIgnoredExpr(E->getBase());
141   }
142 
143   return RValue::get(nullptr);
144 }
145 
146 static CXXRecordDecl *getCXXRecord(const Expr *E) {
147   QualType T = E->getType();
148   if (const PointerType *PTy = T->getAs<PointerType>())
149     T = PTy->getPointeeType();
150   const RecordType *Ty = T->castAs<RecordType>();
151   return cast<CXXRecordDecl>(Ty->getDecl());
152 }
153 
154 // Note: This function also emit constructor calls to support a MSVC
155 // extensions allowing explicit constructor function call.
156 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
157                                               ReturnValueSlot ReturnValue) {
158   const Expr *callee = CE->getCallee()->IgnoreParens();
159 
160   if (isa<BinaryOperator>(callee))
161     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
162 
163   const MemberExpr *ME = cast<MemberExpr>(callee);
164   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
165 
166   if (MD->isStatic()) {
167     // The method is static, emit it as we would a regular call.
168     CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
169     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
170                     ReturnValue);
171   }
172 
173   bool HasQualifier = ME->hasQualifier();
174   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
175   bool IsArrow = ME->isArrow();
176   const Expr *Base = ME->getBase();
177 
178   return EmitCXXMemberOrOperatorMemberCallExpr(
179       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
180 }
181 
182 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
183     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
184     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
185     const Expr *Base) {
186   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
187 
188   // Compute the object pointer.
189   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
190 
191   const CXXMethodDecl *DevirtualizedMethod = nullptr;
192   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
193     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
194     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
195     assert(DevirtualizedMethod);
196     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
197     const Expr *Inner = Base->ignoreParenBaseCasts();
198     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
199         MD->getReturnType().getCanonicalType())
200       // If the return types are not the same, this might be a case where more
201       // code needs to run to compensate for it. For example, the derived
202       // method might return a type that inherits form from the return
203       // type of MD and has a prefix.
204       // For now we just avoid devirtualizing these covariant cases.
205       DevirtualizedMethod = nullptr;
206     else if (getCXXRecord(Inner) == DevirtualizedClass)
207       // If the class of the Inner expression is where the dynamic method
208       // is defined, build the this pointer from it.
209       Base = Inner;
210     else if (getCXXRecord(Base) != DevirtualizedClass) {
211       // If the method is defined in a class that is not the best dynamic
212       // one or the one of the full expression, we would have to build
213       // a derived-to-base cast to compute the correct this pointer, but
214       // we don't have support for that yet, so do a virtual call.
215       DevirtualizedMethod = nullptr;
216     }
217   }
218 
219   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
220   // operator before the LHS.
221   CallArgList RtlArgStorage;
222   CallArgList *RtlArgs = nullptr;
223   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
224     if (OCE->isAssignmentOp()) {
225       RtlArgs = &RtlArgStorage;
226       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
227                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
228                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
229     }
230   }
231 
232   Address This = Address::invalid();
233   if (IsArrow)
234     This = EmitPointerWithAlignment(Base);
235   else
236     This = EmitLValue(Base).getAddress();
237 
238 
239   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
240     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
241     if (isa<CXXConstructorDecl>(MD) &&
242         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
243       return RValue::get(nullptr);
244 
245     if (!MD->getParent()->mayInsertExtraPadding()) {
246       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
247         // We don't like to generate the trivial copy/move assignment operator
248         // when it isn't necessary; just produce the proper effect here.
249         LValue RHS = isa<CXXOperatorCallExpr>(CE)
250                          ? MakeNaturalAlignAddrLValue(
251                                (*RtlArgs)[0].RV.getScalarVal(),
252                                (*(CE->arg_begin() + 1))->getType())
253                          : EmitLValue(*CE->arg_begin());
254         EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
255         return RValue::get(This.getPointer());
256       }
257 
258       if (isa<CXXConstructorDecl>(MD) &&
259           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
260         // Trivial move and copy ctor are the same.
261         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
262         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
263         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
264         return RValue::get(This.getPointer());
265       }
266       llvm_unreachable("unknown trivial member function");
267     }
268   }
269 
270   // Compute the function type we're calling.
271   const CXXMethodDecl *CalleeDecl =
272       DevirtualizedMethod ? DevirtualizedMethod : MD;
273   const CGFunctionInfo *FInfo = nullptr;
274   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
275     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
276         Dtor, StructorType::Complete);
277   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
278     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
279         Ctor, StructorType::Complete);
280   else
281     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
282 
283   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
284 
285   // C++11 [class.mfct.non-static]p2:
286   //   If a non-static member function of a class X is called for an object that
287   //   is not of type X, or of a type derived from X, the behavior is undefined.
288   SourceLocation CallLoc;
289   ASTContext &C = getContext();
290   if (CE)
291     CallLoc = CE->getExprLoc();
292 
293   SanitizerSet SkippedChecks;
294   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE))
295     if (CanElideObjectPointerNullCheck(CMCE->getImplicitObjectArgument()))
296       SkippedChecks.set(SanitizerKind::Null, true);
297   EmitTypeCheck(
298       isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
299                                           : CodeGenFunction::TCK_MemberCall,
300       CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
301       /*Alignment=*/CharUnits::Zero(), SkippedChecks);
302 
303   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
304   // 'CalleeDecl' instead.
305 
306   // C++ [class.virtual]p12:
307   //   Explicit qualification with the scope operator (5.1) suppresses the
308   //   virtual call mechanism.
309   //
310   // We also don't emit a virtual call if the base expression has a record type
311   // because then we know what the type is.
312   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
313 
314   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
315     assert(CE->arg_begin() == CE->arg_end() &&
316            "Destructor shouldn't have explicit parameters");
317     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
318     if (UseVirtualCall) {
319       CGM.getCXXABI().EmitVirtualDestructorCall(
320           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
321     } else {
322       CGCallee Callee;
323       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
324         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
325       else if (!DevirtualizedMethod)
326         Callee = CGCallee::forDirect(
327             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
328                                      Dtor);
329       else {
330         const CXXDestructorDecl *DDtor =
331           cast<CXXDestructorDecl>(DevirtualizedMethod);
332         Callee = CGCallee::forDirect(
333                   CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
334                                      DDtor);
335       }
336       EmitCXXMemberOrOperatorCall(
337           CalleeDecl, Callee, ReturnValue, This.getPointer(),
338           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
339     }
340     return RValue::get(nullptr);
341   }
342 
343   CGCallee Callee;
344   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
345     Callee = CGCallee::forDirect(
346                   CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
347                                  Ctor);
348   } else if (UseVirtualCall) {
349     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
350                                                        CE->getLocStart());
351   } else {
352     if (SanOpts.has(SanitizerKind::CFINVCall) &&
353         MD->getParent()->isDynamicClass()) {
354       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
355       EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
356                                 CE->getLocStart());
357     }
358 
359     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
360       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
361     else if (!DevirtualizedMethod)
362       Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
363     else {
364       Callee = CGCallee::forDirect(
365                                 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
366                                    DevirtualizedMethod);
367     }
368   }
369 
370   if (MD->isVirtual()) {
371     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
372         *this, CalleeDecl, This, UseVirtualCall);
373   }
374 
375   return EmitCXXMemberOrOperatorCall(
376       CalleeDecl, Callee, ReturnValue, This.getPointer(),
377       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
378 }
379 
380 RValue
381 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
382                                               ReturnValueSlot ReturnValue) {
383   const BinaryOperator *BO =
384       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
385   const Expr *BaseExpr = BO->getLHS();
386   const Expr *MemFnExpr = BO->getRHS();
387 
388   const MemberPointerType *MPT =
389     MemFnExpr->getType()->castAs<MemberPointerType>();
390 
391   const FunctionProtoType *FPT =
392     MPT->getPointeeType()->castAs<FunctionProtoType>();
393   const CXXRecordDecl *RD =
394     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
395 
396   // Emit the 'this' pointer.
397   Address This = Address::invalid();
398   if (BO->getOpcode() == BO_PtrMemI)
399     This = EmitPointerWithAlignment(BaseExpr);
400   else
401     This = EmitLValue(BaseExpr).getAddress();
402 
403   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
404                 QualType(MPT->getClass(), 0));
405 
406   // Get the member function pointer.
407   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
408 
409   // Ask the ABI to load the callee.  Note that This is modified.
410   llvm::Value *ThisPtrForCall = nullptr;
411   CGCallee Callee =
412     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
413                                              ThisPtrForCall, MemFnPtr, MPT);
414 
415   CallArgList Args;
416 
417   QualType ThisType =
418     getContext().getPointerType(getContext().getTagDeclType(RD));
419 
420   // Push the this ptr.
421   Args.add(RValue::get(ThisPtrForCall), ThisType);
422 
423   RequiredArgs required =
424       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
425 
426   // And the rest of the call args
427   EmitCallArgs(Args, FPT, E->arguments());
428   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
429                   Callee, ReturnValue, Args);
430 }
431 
432 RValue
433 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
434                                                const CXXMethodDecl *MD,
435                                                ReturnValueSlot ReturnValue) {
436   assert(MD->isInstance() &&
437          "Trying to emit a member call expr on a static method!");
438   return EmitCXXMemberOrOperatorMemberCallExpr(
439       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
440       /*IsArrow=*/false, E->getArg(0));
441 }
442 
443 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
444                                                ReturnValueSlot ReturnValue) {
445   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
446 }
447 
448 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
449                                             Address DestPtr,
450                                             const CXXRecordDecl *Base) {
451   if (Base->isEmpty())
452     return;
453 
454   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
455 
456   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
457   CharUnits NVSize = Layout.getNonVirtualSize();
458 
459   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
460   // present, they are initialized by the most derived class before calling the
461   // constructor.
462   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
463   Stores.emplace_back(CharUnits::Zero(), NVSize);
464 
465   // Each store is split by the existence of a vbptr.
466   CharUnits VBPtrWidth = CGF.getPointerSize();
467   std::vector<CharUnits> VBPtrOffsets =
468       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
469   for (CharUnits VBPtrOffset : VBPtrOffsets) {
470     // Stop before we hit any virtual base pointers located in virtual bases.
471     if (VBPtrOffset >= NVSize)
472       break;
473     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
474     CharUnits LastStoreOffset = LastStore.first;
475     CharUnits LastStoreSize = LastStore.second;
476 
477     CharUnits SplitBeforeOffset = LastStoreOffset;
478     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
479     assert(!SplitBeforeSize.isNegative() && "negative store size!");
480     if (!SplitBeforeSize.isZero())
481       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
482 
483     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
484     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
485     assert(!SplitAfterSize.isNegative() && "negative store size!");
486     if (!SplitAfterSize.isZero())
487       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
488   }
489 
490   // If the type contains a pointer to data member we can't memset it to zero.
491   // Instead, create a null constant and copy it to the destination.
492   // TODO: there are other patterns besides zero that we can usefully memset,
493   // like -1, which happens to be the pattern used by member-pointers.
494   // TODO: isZeroInitializable can be over-conservative in the case where a
495   // virtual base contains a member pointer.
496   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
497   if (!NullConstantForBase->isNullValue()) {
498     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
499         CGF.CGM.getModule(), NullConstantForBase->getType(),
500         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
501         NullConstantForBase, Twine());
502 
503     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
504                                DestPtr.getAlignment());
505     NullVariable->setAlignment(Align.getQuantity());
506 
507     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
508 
509     // Get and call the appropriate llvm.memcpy overload.
510     for (std::pair<CharUnits, CharUnits> Store : Stores) {
511       CharUnits StoreOffset = Store.first;
512       CharUnits StoreSize = Store.second;
513       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
514       CGF.Builder.CreateMemCpy(
515           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
516           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
517           StoreSizeVal);
518     }
519 
520   // Otherwise, just memset the whole thing to zero.  This is legal
521   // because in LLVM, all default initializers (other than the ones we just
522   // handled above) are guaranteed to have a bit pattern of all zeros.
523   } else {
524     for (std::pair<CharUnits, CharUnits> Store : Stores) {
525       CharUnits StoreOffset = Store.first;
526       CharUnits StoreSize = Store.second;
527       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
528       CGF.Builder.CreateMemSet(
529           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
530           CGF.Builder.getInt8(0), StoreSizeVal);
531     }
532   }
533 }
534 
535 void
536 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
537                                       AggValueSlot Dest) {
538   assert(!Dest.isIgnored() && "Must have a destination!");
539   const CXXConstructorDecl *CD = E->getConstructor();
540 
541   // If we require zero initialization before (or instead of) calling the
542   // constructor, as can be the case with a non-user-provided default
543   // constructor, emit the zero initialization now, unless destination is
544   // already zeroed.
545   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
546     switch (E->getConstructionKind()) {
547     case CXXConstructExpr::CK_Delegating:
548     case CXXConstructExpr::CK_Complete:
549       EmitNullInitialization(Dest.getAddress(), E->getType());
550       break;
551     case CXXConstructExpr::CK_VirtualBase:
552     case CXXConstructExpr::CK_NonVirtualBase:
553       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
554                                       CD->getParent());
555       break;
556     }
557   }
558 
559   // If this is a call to a trivial default constructor, do nothing.
560   if (CD->isTrivial() && CD->isDefaultConstructor())
561     return;
562 
563   // Elide the constructor if we're constructing from a temporary.
564   // The temporary check is required because Sema sets this on NRVO
565   // returns.
566   if (getLangOpts().ElideConstructors && E->isElidable()) {
567     assert(getContext().hasSameUnqualifiedType(E->getType(),
568                                                E->getArg(0)->getType()));
569     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
570       EmitAggExpr(E->getArg(0), Dest);
571       return;
572     }
573   }
574 
575   if (const ArrayType *arrayType
576         = getContext().getAsArrayType(E->getType())) {
577     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
578   } else {
579     CXXCtorType Type = Ctor_Complete;
580     bool ForVirtualBase = false;
581     bool Delegating = false;
582 
583     switch (E->getConstructionKind()) {
584      case CXXConstructExpr::CK_Delegating:
585       // We should be emitting a constructor; GlobalDecl will assert this
586       Type = CurGD.getCtorType();
587       Delegating = true;
588       break;
589 
590      case CXXConstructExpr::CK_Complete:
591       Type = Ctor_Complete;
592       break;
593 
594      case CXXConstructExpr::CK_VirtualBase:
595       ForVirtualBase = true;
596       // fall-through
597 
598      case CXXConstructExpr::CK_NonVirtualBase:
599       Type = Ctor_Base;
600     }
601 
602     // Call the constructor.
603     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
604                            Dest.getAddress(), E);
605   }
606 }
607 
608 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
609                                                  const Expr *Exp) {
610   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
611     Exp = E->getSubExpr();
612   assert(isa<CXXConstructExpr>(Exp) &&
613          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
614   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
615   const CXXConstructorDecl *CD = E->getConstructor();
616   RunCleanupsScope Scope(*this);
617 
618   // If we require zero initialization before (or instead of) calling the
619   // constructor, as can be the case with a non-user-provided default
620   // constructor, emit the zero initialization now.
621   // FIXME. Do I still need this for a copy ctor synthesis?
622   if (E->requiresZeroInitialization())
623     EmitNullInitialization(Dest, E->getType());
624 
625   assert(!getContext().getAsConstantArrayType(E->getType())
626          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
627   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
628 }
629 
630 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
631                                         const CXXNewExpr *E) {
632   if (!E->isArray())
633     return CharUnits::Zero();
634 
635   // No cookie is required if the operator new[] being used is the
636   // reserved placement operator new[].
637   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
638     return CharUnits::Zero();
639 
640   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
641 }
642 
643 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
644                                         const CXXNewExpr *e,
645                                         unsigned minElements,
646                                         llvm::Value *&numElements,
647                                         llvm::Value *&sizeWithoutCookie) {
648   QualType type = e->getAllocatedType();
649 
650   if (!e->isArray()) {
651     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
652     sizeWithoutCookie
653       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
654     return sizeWithoutCookie;
655   }
656 
657   // The width of size_t.
658   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
659 
660   // Figure out the cookie size.
661   llvm::APInt cookieSize(sizeWidth,
662                          CalculateCookiePadding(CGF, e).getQuantity());
663 
664   // Emit the array size expression.
665   // We multiply the size of all dimensions for NumElements.
666   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
667   numElements = CGF.CGM.EmitConstantExpr(e->getArraySize(),
668                                          CGF.getContext().getSizeType(), &CGF);
669   if (!numElements)
670     numElements = CGF.EmitScalarExpr(e->getArraySize());
671   assert(isa<llvm::IntegerType>(numElements->getType()));
672 
673   // The number of elements can be have an arbitrary integer type;
674   // essentially, we need to multiply it by a constant factor, add a
675   // cookie size, and verify that the result is representable as a
676   // size_t.  That's just a gloss, though, and it's wrong in one
677   // important way: if the count is negative, it's an error even if
678   // the cookie size would bring the total size >= 0.
679   bool isSigned
680     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
681   llvm::IntegerType *numElementsType
682     = cast<llvm::IntegerType>(numElements->getType());
683   unsigned numElementsWidth = numElementsType->getBitWidth();
684 
685   // Compute the constant factor.
686   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
687   while (const ConstantArrayType *CAT
688              = CGF.getContext().getAsConstantArrayType(type)) {
689     type = CAT->getElementType();
690     arraySizeMultiplier *= CAT->getSize();
691   }
692 
693   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
694   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
695   typeSizeMultiplier *= arraySizeMultiplier;
696 
697   // This will be a size_t.
698   llvm::Value *size;
699 
700   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
701   // Don't bloat the -O0 code.
702   if (llvm::ConstantInt *numElementsC =
703         dyn_cast<llvm::ConstantInt>(numElements)) {
704     const llvm::APInt &count = numElementsC->getValue();
705 
706     bool hasAnyOverflow = false;
707 
708     // If 'count' was a negative number, it's an overflow.
709     if (isSigned && count.isNegative())
710       hasAnyOverflow = true;
711 
712     // We want to do all this arithmetic in size_t.  If numElements is
713     // wider than that, check whether it's already too big, and if so,
714     // overflow.
715     else if (numElementsWidth > sizeWidth &&
716              numElementsWidth - sizeWidth > count.countLeadingZeros())
717       hasAnyOverflow = true;
718 
719     // Okay, compute a count at the right width.
720     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
721 
722     // If there is a brace-initializer, we cannot allocate fewer elements than
723     // there are initializers. If we do, that's treated like an overflow.
724     if (adjustedCount.ult(minElements))
725       hasAnyOverflow = true;
726 
727     // Scale numElements by that.  This might overflow, but we don't
728     // care because it only overflows if allocationSize does, too, and
729     // if that overflows then we shouldn't use this.
730     numElements = llvm::ConstantInt::get(CGF.SizeTy,
731                                          adjustedCount * arraySizeMultiplier);
732 
733     // Compute the size before cookie, and track whether it overflowed.
734     bool overflow;
735     llvm::APInt allocationSize
736       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
737     hasAnyOverflow |= overflow;
738 
739     // Add in the cookie, and check whether it's overflowed.
740     if (cookieSize != 0) {
741       // Save the current size without a cookie.  This shouldn't be
742       // used if there was overflow.
743       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
744 
745       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
746       hasAnyOverflow |= overflow;
747     }
748 
749     // On overflow, produce a -1 so operator new will fail.
750     if (hasAnyOverflow) {
751       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
752     } else {
753       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
754     }
755 
756   // Otherwise, we might need to use the overflow intrinsics.
757   } else {
758     // There are up to five conditions we need to test for:
759     // 1) if isSigned, we need to check whether numElements is negative;
760     // 2) if numElementsWidth > sizeWidth, we need to check whether
761     //   numElements is larger than something representable in size_t;
762     // 3) if minElements > 0, we need to check whether numElements is smaller
763     //    than that.
764     // 4) we need to compute
765     //      sizeWithoutCookie := numElements * typeSizeMultiplier
766     //    and check whether it overflows; and
767     // 5) if we need a cookie, we need to compute
768     //      size := sizeWithoutCookie + cookieSize
769     //    and check whether it overflows.
770 
771     llvm::Value *hasOverflow = nullptr;
772 
773     // If numElementsWidth > sizeWidth, then one way or another, we're
774     // going to have to do a comparison for (2), and this happens to
775     // take care of (1), too.
776     if (numElementsWidth > sizeWidth) {
777       llvm::APInt threshold(numElementsWidth, 1);
778       threshold <<= sizeWidth;
779 
780       llvm::Value *thresholdV
781         = llvm::ConstantInt::get(numElementsType, threshold);
782 
783       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
784       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
785 
786     // Otherwise, if we're signed, we want to sext up to size_t.
787     } else if (isSigned) {
788       if (numElementsWidth < sizeWidth)
789         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
790 
791       // If there's a non-1 type size multiplier, then we can do the
792       // signedness check at the same time as we do the multiply
793       // because a negative number times anything will cause an
794       // unsigned overflow.  Otherwise, we have to do it here. But at least
795       // in this case, we can subsume the >= minElements check.
796       if (typeSizeMultiplier == 1)
797         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
798                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
799 
800     // Otherwise, zext up to size_t if necessary.
801     } else if (numElementsWidth < sizeWidth) {
802       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
803     }
804 
805     assert(numElements->getType() == CGF.SizeTy);
806 
807     if (minElements) {
808       // Don't allow allocation of fewer elements than we have initializers.
809       if (!hasOverflow) {
810         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
811                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
812       } else if (numElementsWidth > sizeWidth) {
813         // The other existing overflow subsumes this check.
814         // We do an unsigned comparison, since any signed value < -1 is
815         // taken care of either above or below.
816         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
817                           CGF.Builder.CreateICmpULT(numElements,
818                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
819       }
820     }
821 
822     size = numElements;
823 
824     // Multiply by the type size if necessary.  This multiplier
825     // includes all the factors for nested arrays.
826     //
827     // This step also causes numElements to be scaled up by the
828     // nested-array factor if necessary.  Overflow on this computation
829     // can be ignored because the result shouldn't be used if
830     // allocation fails.
831     if (typeSizeMultiplier != 1) {
832       llvm::Value *umul_with_overflow
833         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
834 
835       llvm::Value *tsmV =
836         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
837       llvm::Value *result =
838           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
839 
840       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
841       if (hasOverflow)
842         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
843       else
844         hasOverflow = overflowed;
845 
846       size = CGF.Builder.CreateExtractValue(result, 0);
847 
848       // Also scale up numElements by the array size multiplier.
849       if (arraySizeMultiplier != 1) {
850         // If the base element type size is 1, then we can re-use the
851         // multiply we just did.
852         if (typeSize.isOne()) {
853           assert(arraySizeMultiplier == typeSizeMultiplier);
854           numElements = size;
855 
856         // Otherwise we need a separate multiply.
857         } else {
858           llvm::Value *asmV =
859             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
860           numElements = CGF.Builder.CreateMul(numElements, asmV);
861         }
862       }
863     } else {
864       // numElements doesn't need to be scaled.
865       assert(arraySizeMultiplier == 1);
866     }
867 
868     // Add in the cookie size if necessary.
869     if (cookieSize != 0) {
870       sizeWithoutCookie = size;
871 
872       llvm::Value *uadd_with_overflow
873         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
874 
875       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
876       llvm::Value *result =
877           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
878 
879       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
880       if (hasOverflow)
881         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
882       else
883         hasOverflow = overflowed;
884 
885       size = CGF.Builder.CreateExtractValue(result, 0);
886     }
887 
888     // If we had any possibility of dynamic overflow, make a select to
889     // overwrite 'size' with an all-ones value, which should cause
890     // operator new to throw.
891     if (hasOverflow)
892       size = CGF.Builder.CreateSelect(hasOverflow,
893                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
894                                       size);
895   }
896 
897   if (cookieSize == 0)
898     sizeWithoutCookie = size;
899   else
900     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
901 
902   return size;
903 }
904 
905 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
906                                     QualType AllocType, Address NewPtr) {
907   // FIXME: Refactor with EmitExprAsInit.
908   switch (CGF.getEvaluationKind(AllocType)) {
909   case TEK_Scalar:
910     CGF.EmitScalarInit(Init, nullptr,
911                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
912     return;
913   case TEK_Complex:
914     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
915                                   /*isInit*/ true);
916     return;
917   case TEK_Aggregate: {
918     AggValueSlot Slot
919       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
920                               AggValueSlot::IsDestructed,
921                               AggValueSlot::DoesNotNeedGCBarriers,
922                               AggValueSlot::IsNotAliased);
923     CGF.EmitAggExpr(Init, Slot);
924     return;
925   }
926   }
927   llvm_unreachable("bad evaluation kind");
928 }
929 
930 void CodeGenFunction::EmitNewArrayInitializer(
931     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
932     Address BeginPtr, llvm::Value *NumElements,
933     llvm::Value *AllocSizeWithoutCookie) {
934   // If we have a type with trivial initialization and no initializer,
935   // there's nothing to do.
936   if (!E->hasInitializer())
937     return;
938 
939   Address CurPtr = BeginPtr;
940 
941   unsigned InitListElements = 0;
942 
943   const Expr *Init = E->getInitializer();
944   Address EndOfInit = Address::invalid();
945   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
946   EHScopeStack::stable_iterator Cleanup;
947   llvm::Instruction *CleanupDominator = nullptr;
948 
949   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
950   CharUnits ElementAlign =
951     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
952 
953   // Attempt to perform zero-initialization using memset.
954   auto TryMemsetInitialization = [&]() -> bool {
955     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
956     // we can initialize with a memset to -1.
957     if (!CGM.getTypes().isZeroInitializable(ElementType))
958       return false;
959 
960     // Optimization: since zero initialization will just set the memory
961     // to all zeroes, generate a single memset to do it in one shot.
962 
963     // Subtract out the size of any elements we've already initialized.
964     auto *RemainingSize = AllocSizeWithoutCookie;
965     if (InitListElements) {
966       // We know this can't overflow; we check this when doing the allocation.
967       auto *InitializedSize = llvm::ConstantInt::get(
968           RemainingSize->getType(),
969           getContext().getTypeSizeInChars(ElementType).getQuantity() *
970               InitListElements);
971       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
972     }
973 
974     // Create the memset.
975     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
976     return true;
977   };
978 
979   // If the initializer is an initializer list, first do the explicit elements.
980   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
981     // Initializing from a (braced) string literal is a special case; the init
982     // list element does not initialize a (single) array element.
983     if (ILE->isStringLiteralInit()) {
984       // Initialize the initial portion of length equal to that of the string
985       // literal. The allocation must be for at least this much; we emitted a
986       // check for that earlier.
987       AggValueSlot Slot =
988           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
989                                 AggValueSlot::IsDestructed,
990                                 AggValueSlot::DoesNotNeedGCBarriers,
991                                 AggValueSlot::IsNotAliased);
992       EmitAggExpr(ILE->getInit(0), Slot);
993 
994       // Move past these elements.
995       InitListElements =
996           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
997               ->getSize().getZExtValue();
998       CurPtr =
999           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1000                                             Builder.getSize(InitListElements),
1001                                             "string.init.end"),
1002                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1003                                                           ElementSize));
1004 
1005       // Zero out the rest, if any remain.
1006       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1007       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1008         bool OK = TryMemsetInitialization();
1009         (void)OK;
1010         assert(OK && "couldn't memset character type?");
1011       }
1012       return;
1013     }
1014 
1015     InitListElements = ILE->getNumInits();
1016 
1017     // If this is a multi-dimensional array new, we will initialize multiple
1018     // elements with each init list element.
1019     QualType AllocType = E->getAllocatedType();
1020     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1021             AllocType->getAsArrayTypeUnsafe())) {
1022       ElementTy = ConvertTypeForMem(AllocType);
1023       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1024       InitListElements *= getContext().getConstantArrayElementCount(CAT);
1025     }
1026 
1027     // Enter a partial-destruction Cleanup if necessary.
1028     if (needsEHCleanup(DtorKind)) {
1029       // In principle we could tell the Cleanup where we are more
1030       // directly, but the control flow can get so varied here that it
1031       // would actually be quite complex.  Therefore we go through an
1032       // alloca.
1033       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1034                                    "array.init.end");
1035       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1036       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1037                                        ElementType, ElementAlign,
1038                                        getDestroyer(DtorKind));
1039       Cleanup = EHStack.stable_begin();
1040     }
1041 
1042     CharUnits StartAlign = CurPtr.getAlignment();
1043     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1044       // Tell the cleanup that it needs to destroy up to this
1045       // element.  TODO: some of these stores can be trivially
1046       // observed to be unnecessary.
1047       if (EndOfInit.isValid()) {
1048         auto FinishedPtr =
1049           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1050         Builder.CreateStore(FinishedPtr, EndOfInit);
1051       }
1052       // FIXME: If the last initializer is an incomplete initializer list for
1053       // an array, and we have an array filler, we can fold together the two
1054       // initialization loops.
1055       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1056                               ILE->getInit(i)->getType(), CurPtr);
1057       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1058                                                  Builder.getSize(1),
1059                                                  "array.exp.next"),
1060                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1061     }
1062 
1063     // The remaining elements are filled with the array filler expression.
1064     Init = ILE->getArrayFiller();
1065 
1066     // Extract the initializer for the individual array elements by pulling
1067     // out the array filler from all the nested initializer lists. This avoids
1068     // generating a nested loop for the initialization.
1069     while (Init && Init->getType()->isConstantArrayType()) {
1070       auto *SubILE = dyn_cast<InitListExpr>(Init);
1071       if (!SubILE)
1072         break;
1073       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1074       Init = SubILE->getArrayFiller();
1075     }
1076 
1077     // Switch back to initializing one base element at a time.
1078     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1079   }
1080 
1081   // If all elements have already been initialized, skip any further
1082   // initialization.
1083   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1084   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1085     // If there was a Cleanup, deactivate it.
1086     if (CleanupDominator)
1087       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1088     return;
1089   }
1090 
1091   assert(Init && "have trailing elements to initialize but no initializer");
1092 
1093   // If this is a constructor call, try to optimize it out, and failing that
1094   // emit a single loop to initialize all remaining elements.
1095   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1096     CXXConstructorDecl *Ctor = CCE->getConstructor();
1097     if (Ctor->isTrivial()) {
1098       // If new expression did not specify value-initialization, then there
1099       // is no initialization.
1100       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1101         return;
1102 
1103       if (TryMemsetInitialization())
1104         return;
1105     }
1106 
1107     // Store the new Cleanup position for irregular Cleanups.
1108     //
1109     // FIXME: Share this cleanup with the constructor call emission rather than
1110     // having it create a cleanup of its own.
1111     if (EndOfInit.isValid())
1112       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1113 
1114     // Emit a constructor call loop to initialize the remaining elements.
1115     if (InitListElements)
1116       NumElements = Builder.CreateSub(
1117           NumElements,
1118           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1119     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1120                                CCE->requiresZeroInitialization());
1121     return;
1122   }
1123 
1124   // If this is value-initialization, we can usually use memset.
1125   ImplicitValueInitExpr IVIE(ElementType);
1126   if (isa<ImplicitValueInitExpr>(Init)) {
1127     if (TryMemsetInitialization())
1128       return;
1129 
1130     // Switch to an ImplicitValueInitExpr for the element type. This handles
1131     // only one case: multidimensional array new of pointers to members. In
1132     // all other cases, we already have an initializer for the array element.
1133     Init = &IVIE;
1134   }
1135 
1136   // At this point we should have found an initializer for the individual
1137   // elements of the array.
1138   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1139          "got wrong type of element to initialize");
1140 
1141   // If we have an empty initializer list, we can usually use memset.
1142   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1143     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1144       return;
1145 
1146   // If we have a struct whose every field is value-initialized, we can
1147   // usually use memset.
1148   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1149     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1150       if (RType->getDecl()->isStruct()) {
1151         unsigned NumElements = 0;
1152         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1153           NumElements = CXXRD->getNumBases();
1154         for (auto *Field : RType->getDecl()->fields())
1155           if (!Field->isUnnamedBitfield())
1156             ++NumElements;
1157         // FIXME: Recurse into nested InitListExprs.
1158         if (ILE->getNumInits() == NumElements)
1159           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1160             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1161               --NumElements;
1162         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1163           return;
1164       }
1165     }
1166   }
1167 
1168   // Create the loop blocks.
1169   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1170   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1171   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1172 
1173   // Find the end of the array, hoisted out of the loop.
1174   llvm::Value *EndPtr =
1175     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1176 
1177   // If the number of elements isn't constant, we have to now check if there is
1178   // anything left to initialize.
1179   if (!ConstNum) {
1180     llvm::Value *IsEmpty =
1181       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1182     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1183   }
1184 
1185   // Enter the loop.
1186   EmitBlock(LoopBB);
1187 
1188   // Set up the current-element phi.
1189   llvm::PHINode *CurPtrPhi =
1190     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1191   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1192 
1193   CurPtr = Address(CurPtrPhi, ElementAlign);
1194 
1195   // Store the new Cleanup position for irregular Cleanups.
1196   if (EndOfInit.isValid())
1197     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1198 
1199   // Enter a partial-destruction Cleanup if necessary.
1200   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1201     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1202                                    ElementType, ElementAlign,
1203                                    getDestroyer(DtorKind));
1204     Cleanup = EHStack.stable_begin();
1205     CleanupDominator = Builder.CreateUnreachable();
1206   }
1207 
1208   // Emit the initializer into this element.
1209   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
1210 
1211   // Leave the Cleanup if we entered one.
1212   if (CleanupDominator) {
1213     DeactivateCleanupBlock(Cleanup, CleanupDominator);
1214     CleanupDominator->eraseFromParent();
1215   }
1216 
1217   // Advance to the next element by adjusting the pointer type as necessary.
1218   llvm::Value *NextPtr =
1219     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1220                                        "array.next");
1221 
1222   // Check whether we've gotten to the end of the array and, if so,
1223   // exit the loop.
1224   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1225   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1226   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1227 
1228   EmitBlock(ContBB);
1229 }
1230 
1231 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1232                                QualType ElementType, llvm::Type *ElementTy,
1233                                Address NewPtr, llvm::Value *NumElements,
1234                                llvm::Value *AllocSizeWithoutCookie) {
1235   ApplyDebugLocation DL(CGF, E);
1236   if (E->isArray())
1237     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1238                                 AllocSizeWithoutCookie);
1239   else if (const Expr *Init = E->getInitializer())
1240     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
1241 }
1242 
1243 /// Emit a call to an operator new or operator delete function, as implicitly
1244 /// created by new-expressions and delete-expressions.
1245 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1246                                 const FunctionDecl *CalleeDecl,
1247                                 const FunctionProtoType *CalleeType,
1248                                 const CallArgList &Args) {
1249   llvm::Instruction *CallOrInvoke;
1250   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1251   CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
1252   RValue RV =
1253       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1254                        Args, CalleeType, /*chainCall=*/false),
1255                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1256 
1257   /// C++1y [expr.new]p10:
1258   ///   [In a new-expression,] an implementation is allowed to omit a call
1259   ///   to a replaceable global allocation function.
1260   ///
1261   /// We model such elidable calls with the 'builtin' attribute.
1262   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1263   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1264       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1265     // FIXME: Add addAttribute to CallSite.
1266     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1267       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1268                        llvm::Attribute::Builtin);
1269     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1270       II->addAttribute(llvm::AttributeSet::FunctionIndex,
1271                        llvm::Attribute::Builtin);
1272     else
1273       llvm_unreachable("unexpected kind of call instruction");
1274   }
1275 
1276   return RV;
1277 }
1278 
1279 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1280                                                  const Expr *Arg,
1281                                                  bool IsDelete) {
1282   CallArgList Args;
1283   const Stmt *ArgS = Arg;
1284   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1285   // Find the allocation or deallocation function that we're calling.
1286   ASTContext &Ctx = getContext();
1287   DeclarationName Name = Ctx.DeclarationNames
1288       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1289   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1290     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1291       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1292         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1293   llvm_unreachable("predeclared global operator new/delete is missing");
1294 }
1295 
1296 static std::pair<bool, bool>
1297 shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) {
1298   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1299 
1300   // The first argument is always a void*.
1301   ++AI;
1302 
1303   // Figure out what other parameters we should be implicitly passing.
1304   bool PassSize = false;
1305   bool PassAlignment = false;
1306 
1307   if (AI != AE && (*AI)->isIntegerType()) {
1308     PassSize = true;
1309     ++AI;
1310   }
1311 
1312   if (AI != AE && (*AI)->isAlignValT()) {
1313     PassAlignment = true;
1314     ++AI;
1315   }
1316 
1317   assert(AI == AE && "unexpected usual deallocation function parameter");
1318   return {PassSize, PassAlignment};
1319 }
1320 
1321 namespace {
1322   /// A cleanup to call the given 'operator delete' function upon abnormal
1323   /// exit from a new expression. Templated on a traits type that deals with
1324   /// ensuring that the arguments dominate the cleanup if necessary.
1325   template<typename Traits>
1326   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1327     /// Type used to hold llvm::Value*s.
1328     typedef typename Traits::ValueTy ValueTy;
1329     /// Type used to hold RValues.
1330     typedef typename Traits::RValueTy RValueTy;
1331     struct PlacementArg {
1332       RValueTy ArgValue;
1333       QualType ArgType;
1334     };
1335 
1336     unsigned NumPlacementArgs : 31;
1337     unsigned PassAlignmentToPlacementDelete : 1;
1338     const FunctionDecl *OperatorDelete;
1339     ValueTy Ptr;
1340     ValueTy AllocSize;
1341     CharUnits AllocAlign;
1342 
1343     PlacementArg *getPlacementArgs() {
1344       return reinterpret_cast<PlacementArg *>(this + 1);
1345     }
1346 
1347   public:
1348     static size_t getExtraSize(size_t NumPlacementArgs) {
1349       return NumPlacementArgs * sizeof(PlacementArg);
1350     }
1351 
1352     CallDeleteDuringNew(size_t NumPlacementArgs,
1353                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1354                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1355                         CharUnits AllocAlign)
1356       : NumPlacementArgs(NumPlacementArgs),
1357         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1358         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1359         AllocAlign(AllocAlign) {}
1360 
1361     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1362       assert(I < NumPlacementArgs && "index out of range");
1363       getPlacementArgs()[I] = {Arg, Type};
1364     }
1365 
1366     void Emit(CodeGenFunction &CGF, Flags flags) override {
1367       const FunctionProtoType *FPT =
1368           OperatorDelete->getType()->getAs<FunctionProtoType>();
1369       CallArgList DeleteArgs;
1370 
1371       // The first argument is always a void*.
1372       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1373 
1374       // Figure out what other parameters we should be implicitly passing.
1375       bool PassSize = false;
1376       bool PassAlignment = false;
1377       if (NumPlacementArgs) {
1378         // A placement deallocation function is implicitly passed an alignment
1379         // if the placement allocation function was, but is never passed a size.
1380         PassAlignment = PassAlignmentToPlacementDelete;
1381       } else {
1382         // For a non-placement new-expression, 'operator delete' can take a
1383         // size and/or an alignment if it has the right parameters.
1384         std::tie(PassSize, PassAlignment) =
1385             shouldPassSizeAndAlignToUsualDelete(FPT);
1386       }
1387 
1388       // The second argument can be a std::size_t (for non-placement delete).
1389       if (PassSize)
1390         DeleteArgs.add(Traits::get(CGF, AllocSize),
1391                        CGF.getContext().getSizeType());
1392 
1393       // The next (second or third) argument can be a std::align_val_t, which
1394       // is an enum whose underlying type is std::size_t.
1395       // FIXME: Use the right type as the parameter type. Note that in a call
1396       // to operator delete(size_t, ...), we may not have it available.
1397       if (PassAlignment)
1398         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1399                            CGF.SizeTy, AllocAlign.getQuantity())),
1400                        CGF.getContext().getSizeType());
1401 
1402       // Pass the rest of the arguments, which must match exactly.
1403       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1404         auto Arg = getPlacementArgs()[I];
1405         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1406       }
1407 
1408       // Call 'operator delete'.
1409       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1410     }
1411   };
1412 }
1413 
1414 /// Enter a cleanup to call 'operator delete' if the initializer in a
1415 /// new-expression throws.
1416 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1417                                   const CXXNewExpr *E,
1418                                   Address NewPtr,
1419                                   llvm::Value *AllocSize,
1420                                   CharUnits AllocAlign,
1421                                   const CallArgList &NewArgs) {
1422   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1423 
1424   // If we're not inside a conditional branch, then the cleanup will
1425   // dominate and we can do the easier (and more efficient) thing.
1426   if (!CGF.isInConditionalBranch()) {
1427     struct DirectCleanupTraits {
1428       typedef llvm::Value *ValueTy;
1429       typedef RValue RValueTy;
1430       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1431       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1432     };
1433 
1434     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1435 
1436     DirectCleanup *Cleanup = CGF.EHStack
1437       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1438                                            E->getNumPlacementArgs(),
1439                                            E->getOperatorDelete(),
1440                                            NewPtr.getPointer(),
1441                                            AllocSize,
1442                                            E->passAlignment(),
1443                                            AllocAlign);
1444     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1445       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1446       Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1447     }
1448 
1449     return;
1450   }
1451 
1452   // Otherwise, we need to save all this stuff.
1453   DominatingValue<RValue>::saved_type SavedNewPtr =
1454     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1455   DominatingValue<RValue>::saved_type SavedAllocSize =
1456     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1457 
1458   struct ConditionalCleanupTraits {
1459     typedef DominatingValue<RValue>::saved_type ValueTy;
1460     typedef DominatingValue<RValue>::saved_type RValueTy;
1461     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1462       return V.restore(CGF);
1463     }
1464   };
1465   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1466 
1467   ConditionalCleanup *Cleanup = CGF.EHStack
1468     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1469                                               E->getNumPlacementArgs(),
1470                                               E->getOperatorDelete(),
1471                                               SavedNewPtr,
1472                                               SavedAllocSize,
1473                                               E->passAlignment(),
1474                                               AllocAlign);
1475   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1476     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1477     Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1478                              Arg.Ty);
1479   }
1480 
1481   CGF.initFullExprCleanup();
1482 }
1483 
1484 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1485   // The element type being allocated.
1486   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1487 
1488   // 1. Build a call to the allocation function.
1489   FunctionDecl *allocator = E->getOperatorNew();
1490 
1491   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1492   unsigned minElements = 0;
1493   if (E->isArray() && E->hasInitializer()) {
1494     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1495     if (ILE && ILE->isStringLiteralInit())
1496       minElements =
1497           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1498               ->getSize().getZExtValue();
1499     else if (ILE)
1500       minElements = ILE->getNumInits();
1501   }
1502 
1503   llvm::Value *numElements = nullptr;
1504   llvm::Value *allocSizeWithoutCookie = nullptr;
1505   llvm::Value *allocSize =
1506     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1507                         allocSizeWithoutCookie);
1508   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
1509 
1510   // Emit the allocation call.  If the allocator is a global placement
1511   // operator, just "inline" it directly.
1512   Address allocation = Address::invalid();
1513   CallArgList allocatorArgs;
1514   if (allocator->isReservedGlobalPlacementOperator()) {
1515     assert(E->getNumPlacementArgs() == 1);
1516     const Expr *arg = *E->placement_arguments().begin();
1517 
1518     AlignmentSource alignSource;
1519     allocation = EmitPointerWithAlignment(arg, &alignSource);
1520 
1521     // The pointer expression will, in many cases, be an opaque void*.
1522     // In these cases, discard the computed alignment and use the
1523     // formal alignment of the allocated type.
1524     if (alignSource != AlignmentSource::Decl)
1525       allocation = Address(allocation.getPointer(), allocAlign);
1526 
1527     // Set up allocatorArgs for the call to operator delete if it's not
1528     // the reserved global operator.
1529     if (E->getOperatorDelete() &&
1530         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1531       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1532       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1533     }
1534 
1535   } else {
1536     const FunctionProtoType *allocatorType =
1537       allocator->getType()->castAs<FunctionProtoType>();
1538     unsigned ParamsToSkip = 0;
1539 
1540     // The allocation size is the first argument.
1541     QualType sizeType = getContext().getSizeType();
1542     allocatorArgs.add(RValue::get(allocSize), sizeType);
1543     ++ParamsToSkip;
1544 
1545     if (allocSize != allocSizeWithoutCookie) {
1546       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1547       allocAlign = std::max(allocAlign, cookieAlign);
1548     }
1549 
1550     // The allocation alignment may be passed as the second argument.
1551     if (E->passAlignment()) {
1552       QualType AlignValT = sizeType;
1553       if (allocatorType->getNumParams() > 1) {
1554         AlignValT = allocatorType->getParamType(1);
1555         assert(getContext().hasSameUnqualifiedType(
1556                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1557                    sizeType) &&
1558                "wrong type for alignment parameter");
1559         ++ParamsToSkip;
1560       } else {
1561         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1562         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1563       }
1564       allocatorArgs.add(
1565           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1566           AlignValT);
1567     }
1568 
1569     // FIXME: Why do we not pass a CalleeDecl here?
1570     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1571                  /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip);
1572 
1573     RValue RV =
1574       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1575 
1576     // If this was a call to a global replaceable allocation function that does
1577     // not take an alignment argument, the allocator is known to produce
1578     // storage that's suitably aligned for any object that fits, up to a known
1579     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1580     CharUnits allocationAlign = allocAlign;
1581     if (!E->passAlignment() &&
1582         allocator->isReplaceableGlobalAllocationFunction()) {
1583       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1584           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1585       allocationAlign = std::max(
1586           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1587     }
1588 
1589     allocation = Address(RV.getScalarVal(), allocationAlign);
1590   }
1591 
1592   // Emit a null check on the allocation result if the allocation
1593   // function is allowed to return null (because it has a non-throwing
1594   // exception spec or is the reserved placement new) and we have an
1595   // interesting initializer.
1596   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
1597     (!allocType.isPODType(getContext()) || E->hasInitializer());
1598 
1599   llvm::BasicBlock *nullCheckBB = nullptr;
1600   llvm::BasicBlock *contBB = nullptr;
1601 
1602   // The null-check means that the initializer is conditionally
1603   // evaluated.
1604   ConditionalEvaluation conditional(*this);
1605 
1606   if (nullCheck) {
1607     conditional.begin(*this);
1608 
1609     nullCheckBB = Builder.GetInsertBlock();
1610     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1611     contBB = createBasicBlock("new.cont");
1612 
1613     llvm::Value *isNull =
1614       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1615     Builder.CreateCondBr(isNull, contBB, notNullBB);
1616     EmitBlock(notNullBB);
1617   }
1618 
1619   // If there's an operator delete, enter a cleanup to call it if an
1620   // exception is thrown.
1621   EHScopeStack::stable_iterator operatorDeleteCleanup;
1622   llvm::Instruction *cleanupDominator = nullptr;
1623   if (E->getOperatorDelete() &&
1624       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1625     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1626                           allocatorArgs);
1627     operatorDeleteCleanup = EHStack.stable_begin();
1628     cleanupDominator = Builder.CreateUnreachable();
1629   }
1630 
1631   assert((allocSize == allocSizeWithoutCookie) ==
1632          CalculateCookiePadding(*this, E).isZero());
1633   if (allocSize != allocSizeWithoutCookie) {
1634     assert(E->isArray());
1635     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1636                                                        numElements,
1637                                                        E, allocType);
1638   }
1639 
1640   llvm::Type *elementTy = ConvertTypeForMem(allocType);
1641   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1642 
1643   // Passing pointer through invariant.group.barrier to avoid propagation of
1644   // vptrs information which may be included in previous type.
1645   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1646       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1647       allocator->isReservedGlobalPlacementOperator())
1648     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1649                      result.getAlignment());
1650 
1651   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1652                      allocSizeWithoutCookie);
1653   if (E->isArray()) {
1654     // NewPtr is a pointer to the base element type.  If we're
1655     // allocating an array of arrays, we'll need to cast back to the
1656     // array pointer type.
1657     llvm::Type *resultType = ConvertTypeForMem(E->getType());
1658     if (result.getType() != resultType)
1659       result = Builder.CreateBitCast(result, resultType);
1660   }
1661 
1662   // Deactivate the 'operator delete' cleanup if we finished
1663   // initialization.
1664   if (operatorDeleteCleanup.isValid()) {
1665     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1666     cleanupDominator->eraseFromParent();
1667   }
1668 
1669   llvm::Value *resultPtr = result.getPointer();
1670   if (nullCheck) {
1671     conditional.end(*this);
1672 
1673     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1674     EmitBlock(contBB);
1675 
1676     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1677     PHI->addIncoming(resultPtr, notNullBB);
1678     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1679                      nullCheckBB);
1680 
1681     resultPtr = PHI;
1682   }
1683 
1684   return resultPtr;
1685 }
1686 
1687 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1688                                      llvm::Value *Ptr, QualType DeleteTy,
1689                                      llvm::Value *NumElements,
1690                                      CharUnits CookieSize) {
1691   assert((!NumElements && CookieSize.isZero()) ||
1692          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1693 
1694   const FunctionProtoType *DeleteFTy =
1695     DeleteFD->getType()->getAs<FunctionProtoType>();
1696 
1697   CallArgList DeleteArgs;
1698 
1699   std::pair<bool, bool> PassSizeAndAlign =
1700       shouldPassSizeAndAlignToUsualDelete(DeleteFTy);
1701 
1702   auto ParamTypeIt = DeleteFTy->param_type_begin();
1703 
1704   // Pass the pointer itself.
1705   QualType ArgTy = *ParamTypeIt++;
1706   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1707   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1708 
1709   // Pass the size if the delete function has a size_t parameter.
1710   if (PassSizeAndAlign.first) {
1711     QualType SizeType = *ParamTypeIt++;
1712     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1713     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1714                                                DeleteTypeSize.getQuantity());
1715 
1716     // For array new, multiply by the number of elements.
1717     if (NumElements)
1718       Size = Builder.CreateMul(Size, NumElements);
1719 
1720     // If there is a cookie, add the cookie size.
1721     if (!CookieSize.isZero())
1722       Size = Builder.CreateAdd(
1723           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1724 
1725     DeleteArgs.add(RValue::get(Size), SizeType);
1726   }
1727 
1728   // Pass the alignment if the delete function has an align_val_t parameter.
1729   if (PassSizeAndAlign.second) {
1730     QualType AlignValType = *ParamTypeIt++;
1731     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1732         getContext().getTypeAlignIfKnown(DeleteTy));
1733     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1734                                                 DeleteTypeAlign.getQuantity());
1735     DeleteArgs.add(RValue::get(Align), AlignValType);
1736   }
1737 
1738   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1739          "unknown parameter to usual delete function");
1740 
1741   // Emit the call to delete.
1742   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1743 }
1744 
1745 namespace {
1746   /// Calls the given 'operator delete' on a single object.
1747   struct CallObjectDelete final : EHScopeStack::Cleanup {
1748     llvm::Value *Ptr;
1749     const FunctionDecl *OperatorDelete;
1750     QualType ElementType;
1751 
1752     CallObjectDelete(llvm::Value *Ptr,
1753                      const FunctionDecl *OperatorDelete,
1754                      QualType ElementType)
1755       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1756 
1757     void Emit(CodeGenFunction &CGF, Flags flags) override {
1758       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1759     }
1760   };
1761 }
1762 
1763 void
1764 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1765                                              llvm::Value *CompletePtr,
1766                                              QualType ElementType) {
1767   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1768                                         OperatorDelete, ElementType);
1769 }
1770 
1771 /// Emit the code for deleting a single object.
1772 static void EmitObjectDelete(CodeGenFunction &CGF,
1773                              const CXXDeleteExpr *DE,
1774                              Address Ptr,
1775                              QualType ElementType) {
1776   // C++11 [expr.delete]p3:
1777   //   If the static type of the object to be deleted is different from its
1778   //   dynamic type, the static type shall be a base class of the dynamic type
1779   //   of the object to be deleted and the static type shall have a virtual
1780   //   destructor or the behavior is undefined.
1781   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1782                     DE->getExprLoc(), Ptr.getPointer(),
1783                     ElementType);
1784 
1785   // Find the destructor for the type, if applicable.  If the
1786   // destructor is virtual, we'll just emit the vcall and return.
1787   const CXXDestructorDecl *Dtor = nullptr;
1788   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1789     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1790     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1791       Dtor = RD->getDestructor();
1792 
1793       if (Dtor->isVirtual()) {
1794         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1795                                                     Dtor);
1796         return;
1797       }
1798     }
1799   }
1800 
1801   // Make sure that we call delete even if the dtor throws.
1802   // This doesn't have to a conditional cleanup because we're going
1803   // to pop it off in a second.
1804   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1805   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1806                                             Ptr.getPointer(),
1807                                             OperatorDelete, ElementType);
1808 
1809   if (Dtor)
1810     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1811                               /*ForVirtualBase=*/false,
1812                               /*Delegating=*/false,
1813                               Ptr);
1814   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1815     switch (Lifetime) {
1816     case Qualifiers::OCL_None:
1817     case Qualifiers::OCL_ExplicitNone:
1818     case Qualifiers::OCL_Autoreleasing:
1819       break;
1820 
1821     case Qualifiers::OCL_Strong:
1822       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1823       break;
1824 
1825     case Qualifiers::OCL_Weak:
1826       CGF.EmitARCDestroyWeak(Ptr);
1827       break;
1828     }
1829   }
1830 
1831   CGF.PopCleanupBlock();
1832 }
1833 
1834 namespace {
1835   /// Calls the given 'operator delete' on an array of objects.
1836   struct CallArrayDelete final : EHScopeStack::Cleanup {
1837     llvm::Value *Ptr;
1838     const FunctionDecl *OperatorDelete;
1839     llvm::Value *NumElements;
1840     QualType ElementType;
1841     CharUnits CookieSize;
1842 
1843     CallArrayDelete(llvm::Value *Ptr,
1844                     const FunctionDecl *OperatorDelete,
1845                     llvm::Value *NumElements,
1846                     QualType ElementType,
1847                     CharUnits CookieSize)
1848       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1849         ElementType(ElementType), CookieSize(CookieSize) {}
1850 
1851     void Emit(CodeGenFunction &CGF, Flags flags) override {
1852       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1853                          CookieSize);
1854     }
1855   };
1856 }
1857 
1858 /// Emit the code for deleting an array of objects.
1859 static void EmitArrayDelete(CodeGenFunction &CGF,
1860                             const CXXDeleteExpr *E,
1861                             Address deletedPtr,
1862                             QualType elementType) {
1863   llvm::Value *numElements = nullptr;
1864   llvm::Value *allocatedPtr = nullptr;
1865   CharUnits cookieSize;
1866   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1867                                       numElements, allocatedPtr, cookieSize);
1868 
1869   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1870 
1871   // Make sure that we call delete even if one of the dtors throws.
1872   const FunctionDecl *operatorDelete = E->getOperatorDelete();
1873   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1874                                            allocatedPtr, operatorDelete,
1875                                            numElements, elementType,
1876                                            cookieSize);
1877 
1878   // Destroy the elements.
1879   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1880     assert(numElements && "no element count for a type with a destructor!");
1881 
1882     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1883     CharUnits elementAlign =
1884       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1885 
1886     llvm::Value *arrayBegin = deletedPtr.getPointer();
1887     llvm::Value *arrayEnd =
1888       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1889 
1890     // Note that it is legal to allocate a zero-length array, and we
1891     // can never fold the check away because the length should always
1892     // come from a cookie.
1893     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1894                          CGF.getDestroyer(dtorKind),
1895                          /*checkZeroLength*/ true,
1896                          CGF.needsEHCleanup(dtorKind));
1897   }
1898 
1899   // Pop the cleanup block.
1900   CGF.PopCleanupBlock();
1901 }
1902 
1903 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1904   const Expr *Arg = E->getArgument();
1905   Address Ptr = EmitPointerWithAlignment(Arg);
1906 
1907   // Null check the pointer.
1908   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1909   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1910 
1911   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
1912 
1913   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1914   EmitBlock(DeleteNotNull);
1915 
1916   // We might be deleting a pointer to array.  If so, GEP down to the
1917   // first non-array element.
1918   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1919   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1920   if (DeleteTy->isConstantArrayType()) {
1921     llvm::Value *Zero = Builder.getInt32(0);
1922     SmallVector<llvm::Value*,8> GEP;
1923 
1924     GEP.push_back(Zero); // point at the outermost array
1925 
1926     // For each layer of array type we're pointing at:
1927     while (const ConstantArrayType *Arr
1928              = getContext().getAsConstantArrayType(DeleteTy)) {
1929       // 1. Unpeel the array type.
1930       DeleteTy = Arr->getElementType();
1931 
1932       // 2. GEP to the first element of the array.
1933       GEP.push_back(Zero);
1934     }
1935 
1936     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
1937                   Ptr.getAlignment());
1938   }
1939 
1940   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
1941 
1942   if (E->isArrayForm()) {
1943     EmitArrayDelete(*this, E, Ptr, DeleteTy);
1944   } else {
1945     EmitObjectDelete(*this, E, Ptr, DeleteTy);
1946   }
1947 
1948   EmitBlock(DeleteEnd);
1949 }
1950 
1951 static bool isGLValueFromPointerDeref(const Expr *E) {
1952   E = E->IgnoreParens();
1953 
1954   if (const auto *CE = dyn_cast<CastExpr>(E)) {
1955     if (!CE->getSubExpr()->isGLValue())
1956       return false;
1957     return isGLValueFromPointerDeref(CE->getSubExpr());
1958   }
1959 
1960   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1961     return isGLValueFromPointerDeref(OVE->getSourceExpr());
1962 
1963   if (const auto *BO = dyn_cast<BinaryOperator>(E))
1964     if (BO->getOpcode() == BO_Comma)
1965       return isGLValueFromPointerDeref(BO->getRHS());
1966 
1967   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1968     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1969            isGLValueFromPointerDeref(ACO->getFalseExpr());
1970 
1971   // C++11 [expr.sub]p1:
1972   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1973   if (isa<ArraySubscriptExpr>(E))
1974     return true;
1975 
1976   if (const auto *UO = dyn_cast<UnaryOperator>(E))
1977     if (UO->getOpcode() == UO_Deref)
1978       return true;
1979 
1980   return false;
1981 }
1982 
1983 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
1984                                          llvm::Type *StdTypeInfoPtrTy) {
1985   // Get the vtable pointer.
1986   Address ThisPtr = CGF.EmitLValue(E).getAddress();
1987 
1988   // C++ [expr.typeid]p2:
1989   //   If the glvalue expression is obtained by applying the unary * operator to
1990   //   a pointer and the pointer is a null pointer value, the typeid expression
1991   //   throws the std::bad_typeid exception.
1992   //
1993   // However, this paragraph's intent is not clear.  We choose a very generous
1994   // interpretation which implores us to consider comma operators, conditional
1995   // operators, parentheses and other such constructs.
1996   QualType SrcRecordTy = E->getType();
1997   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1998           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1999     llvm::BasicBlock *BadTypeidBlock =
2000         CGF.createBasicBlock("typeid.bad_typeid");
2001     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2002 
2003     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2004     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2005 
2006     CGF.EmitBlock(BadTypeidBlock);
2007     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2008     CGF.EmitBlock(EndBlock);
2009   }
2010 
2011   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2012                                         StdTypeInfoPtrTy);
2013 }
2014 
2015 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2016   llvm::Type *StdTypeInfoPtrTy =
2017     ConvertType(E->getType())->getPointerTo();
2018 
2019   if (E->isTypeOperand()) {
2020     llvm::Constant *TypeInfo =
2021         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2022     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2023   }
2024 
2025   // C++ [expr.typeid]p2:
2026   //   When typeid is applied to a glvalue expression whose type is a
2027   //   polymorphic class type, the result refers to a std::type_info object
2028   //   representing the type of the most derived object (that is, the dynamic
2029   //   type) to which the glvalue refers.
2030   if (E->isPotentiallyEvaluated())
2031     return EmitTypeidFromVTable(*this, E->getExprOperand(),
2032                                 StdTypeInfoPtrTy);
2033 
2034   QualType OperandTy = E->getExprOperand()->getType();
2035   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2036                                StdTypeInfoPtrTy);
2037 }
2038 
2039 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2040                                           QualType DestTy) {
2041   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2042   if (DestTy->isPointerType())
2043     return llvm::Constant::getNullValue(DestLTy);
2044 
2045   /// C++ [expr.dynamic.cast]p9:
2046   ///   A failed cast to reference type throws std::bad_cast
2047   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2048     return nullptr;
2049 
2050   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2051   return llvm::UndefValue::get(DestLTy);
2052 }
2053 
2054 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2055                                               const CXXDynamicCastExpr *DCE) {
2056   CGM.EmitExplicitCastExprType(DCE, this);
2057   QualType DestTy = DCE->getTypeAsWritten();
2058 
2059   if (DCE->isAlwaysNull())
2060     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2061       return T;
2062 
2063   QualType SrcTy = DCE->getSubExpr()->getType();
2064 
2065   // C++ [expr.dynamic.cast]p7:
2066   //   If T is "pointer to cv void," then the result is a pointer to the most
2067   //   derived object pointed to by v.
2068   const PointerType *DestPTy = DestTy->getAs<PointerType>();
2069 
2070   bool isDynamicCastToVoid;
2071   QualType SrcRecordTy;
2072   QualType DestRecordTy;
2073   if (DestPTy) {
2074     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2075     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2076     DestRecordTy = DestPTy->getPointeeType();
2077   } else {
2078     isDynamicCastToVoid = false;
2079     SrcRecordTy = SrcTy;
2080     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2081   }
2082 
2083   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2084 
2085   // C++ [expr.dynamic.cast]p4:
2086   //   If the value of v is a null pointer value in the pointer case, the result
2087   //   is the null pointer value of type T.
2088   bool ShouldNullCheckSrcValue =
2089       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2090                                                          SrcRecordTy);
2091 
2092   llvm::BasicBlock *CastNull = nullptr;
2093   llvm::BasicBlock *CastNotNull = nullptr;
2094   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2095 
2096   if (ShouldNullCheckSrcValue) {
2097     CastNull = createBasicBlock("dynamic_cast.null");
2098     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2099 
2100     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2101     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2102     EmitBlock(CastNotNull);
2103   }
2104 
2105   llvm::Value *Value;
2106   if (isDynamicCastToVoid) {
2107     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2108                                                   DestTy);
2109   } else {
2110     assert(DestRecordTy->isRecordType() &&
2111            "destination type must be a record type!");
2112     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2113                                                 DestTy, DestRecordTy, CastEnd);
2114     CastNotNull = Builder.GetInsertBlock();
2115   }
2116 
2117   if (ShouldNullCheckSrcValue) {
2118     EmitBranch(CastEnd);
2119 
2120     EmitBlock(CastNull);
2121     EmitBranch(CastEnd);
2122   }
2123 
2124   EmitBlock(CastEnd);
2125 
2126   if (ShouldNullCheckSrcValue) {
2127     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2128     PHI->addIncoming(Value, CastNotNull);
2129     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2130 
2131     Value = PHI;
2132   }
2133 
2134   return Value;
2135 }
2136 
2137 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
2138   RunCleanupsScope Scope(*this);
2139   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
2140 
2141   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
2142   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2143                                                e = E->capture_init_end();
2144        i != e; ++i, ++CurField) {
2145     // Emit initialization
2146     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2147     if (CurField->hasCapturedVLAType()) {
2148       auto VAT = CurField->getCapturedVLAType();
2149       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2150     } else {
2151       EmitInitializerForField(*CurField, LV, *i);
2152     }
2153   }
2154 }
2155