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