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