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