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