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