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 using namespace clang;
21 using namespace CodeGen;
22 
23 RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24                                           llvm::Value *Callee,
25                                           ReturnValueSlot ReturnValue,
26                                           llvm::Value *This,
27                                           llvm::Value *VTT,
28                                           CallExpr::const_arg_iterator ArgBeg,
29                                           CallExpr::const_arg_iterator ArgEnd) {
30   assert(MD->isInstance() &&
31          "Trying to emit a member call expr on a static method!");
32 
33   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
34 
35   CallArgList Args;
36 
37   // Push the this ptr.
38   Args.push_back(std::make_pair(RValue::get(This),
39                                 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.push_back(std::make_pair(RValue::get(VTT), T));
45   }
46 
47   // And the rest of the call args
48   EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49 
50   QualType ResultType = FPT->getResultType();
51   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
52                                                  FPT->getExtInfo()),
53                   Callee, ReturnValue, Args, MD);
54 }
55 
56 /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
57 /// expr can be devirtualized.
58 static bool canDevirtualizeMemberFunctionCalls(const Expr *Base,
59                                                const CXXMethodDecl *MD) {
60 
61   // If the member function has the "final" attribute, we know that it can't be
62   // overridden and can therefore devirtualize it.
63   if (MD->hasAttr<FinalAttr>())
64     return true;
65 
66   // Similarly, if the class itself has the "final" attribute it can't be
67   // overridden and we can therefore devirtualize the member function call.
68   if (MD->getParent()->hasAttr<FinalAttr>())
69     return true;
70 
71   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
72     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
73       // This is a record decl. We know the type and can devirtualize it.
74       return VD->getType()->isRecordType();
75     }
76 
77     return false;
78   }
79 
80   // We can always devirtualize calls on temporary object expressions.
81   if (isa<CXXConstructExpr>(Base))
82     return true;
83 
84   // And calls on bound temporaries.
85   if (isa<CXXBindTemporaryExpr>(Base))
86     return true;
87 
88   // Check if this is a call expr that returns a record type.
89   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
90     return CE->getCallReturnType()->isRecordType();
91 
92   // We can't devirtualize the call.
93   return false;
94 }
95 
96 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
97                                               ReturnValueSlot ReturnValue) {
98   if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
99     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
100 
101   const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
102   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
103 
104   CGDebugInfo *DI = getDebugInfo();
105   if (DI && CGM.getCodeGenOpts().LimitDebugInfo
106       && !isa<CallExpr>(ME->getBase())) {
107     QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
108     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
109       DI->getOrCreateRecordType(PTy->getPointeeType(),
110                                 MD->getParent()->getLocation());
111     }
112   }
113 
114   if (MD->isStatic()) {
115     // The method is static, emit it as we would a regular call.
116     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
117     return EmitCall(getContext().getPointerType(MD->getType()), Callee,
118                     ReturnValue, CE->arg_begin(), CE->arg_end());
119   }
120 
121   // Compute the object pointer.
122   llvm::Value *This;
123   if (ME->isArrow())
124     This = EmitScalarExpr(ME->getBase());
125   else
126     This = EmitLValue(ME->getBase()).getAddress();
127 
128   if (MD->isTrivial()) {
129     if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
130 
131     assert(MD->isCopyAssignmentOperator() && "unknown trivial member function");
132     // We don't like to generate the trivial copy assignment operator when
133     // it isn't necessary; just produce the proper effect here.
134     llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
135     EmitAggregateCopy(This, RHS, CE->getType());
136     return RValue::get(This);
137   }
138 
139   // Compute the function type we're calling.
140   const CGFunctionInfo &FInfo =
141     (isa<CXXDestructorDecl>(MD)
142      ? CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
143                                       Dtor_Complete)
144      : CGM.getTypes().getFunctionInfo(MD));
145 
146   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
147   const llvm::Type *Ty
148     = CGM.getTypes().GetFunctionType(FInfo, FPT->isVariadic());
149 
150   // C++ [class.virtual]p12:
151   //   Explicit qualification with the scope operator (5.1) suppresses the
152   //   virtual call mechanism.
153   //
154   // We also don't emit a virtual call if the base expression has a record type
155   // because then we know what the type is.
156   bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
157                      && !canDevirtualizeMemberFunctionCalls(ME->getBase(), MD);
158 
159   llvm::Value *Callee;
160   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
161     if (UseVirtualCall) {
162       Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
163     } else {
164       Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
165     }
166   } else if (UseVirtualCall) {
167     Callee = BuildVirtualCall(MD, This, Ty);
168   } else {
169     Callee = CGM.GetAddrOfFunction(MD, Ty);
170   }
171 
172   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
173                            CE->arg_begin(), CE->arg_end());
174 }
175 
176 RValue
177 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
178                                               ReturnValueSlot ReturnValue) {
179   const BinaryOperator *BO =
180       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
181   const Expr *BaseExpr = BO->getLHS();
182   const Expr *MemFnExpr = BO->getRHS();
183 
184   const MemberPointerType *MPT =
185     MemFnExpr->getType()->getAs<MemberPointerType>();
186 
187   const FunctionProtoType *FPT =
188     MPT->getPointeeType()->getAs<FunctionProtoType>();
189   const CXXRecordDecl *RD =
190     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
191 
192   // Get the member function pointer.
193   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
194 
195   // Emit the 'this' pointer.
196   llvm::Value *This;
197 
198   if (BO->getOpcode() == BO_PtrMemI)
199     This = EmitScalarExpr(BaseExpr);
200   else
201     This = EmitLValue(BaseExpr).getAddress();
202 
203   // Ask the ABI to load the callee.  Note that This is modified.
204   llvm::Value *Callee =
205     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
206 
207   CallArgList Args;
208 
209   QualType ThisType =
210     getContext().getPointerType(getContext().getTagDeclType(RD));
211 
212   // Push the this ptr.
213   Args.push_back(std::make_pair(RValue::get(This), ThisType));
214 
215   // And the rest of the call args
216   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
217   const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
218   return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
219                   ReturnValue, Args);
220 }
221 
222 RValue
223 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
224                                                const CXXMethodDecl *MD,
225                                                ReturnValueSlot ReturnValue) {
226   assert(MD->isInstance() &&
227          "Trying to emit a member call expr on a static method!");
228   LValue LV = EmitLValue(E->getArg(0));
229   llvm::Value *This = LV.getAddress();
230 
231   if (MD->isCopyAssignmentOperator()) {
232     const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233     if (ClassDecl->hasTrivialCopyAssignment()) {
234       assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235              "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
236       llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
237       QualType Ty = E->getType();
238       EmitAggregateCopy(This, Src, Ty);
239       return RValue::get(This);
240     }
241   }
242 
243   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
244   const llvm::Type *Ty =
245     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
246                                    FPT->isVariadic());
247   llvm::Value *Callee;
248   if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0), MD))
249     Callee = BuildVirtualCall(MD, This, Ty);
250   else
251     Callee = CGM.GetAddrOfFunction(MD, Ty);
252 
253   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
254                            E->arg_begin() + 1, E->arg_end());
255 }
256 
257 void
258 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
259                                       AggValueSlot Dest) {
260   assert(!Dest.isIgnored() && "Must have a destination!");
261   const CXXConstructorDecl *CD = E->getConstructor();
262 
263   // If we require zero initialization before (or instead of) calling the
264   // constructor, as can be the case with a non-user-provided default
265   // constructor, emit the zero initialization now.
266   if (E->requiresZeroInitialization())
267     EmitNullInitialization(Dest.getAddr(), E->getType());
268 
269   // If this is a call to a trivial default constructor, do nothing.
270   if (CD->isTrivial() && CD->isDefaultConstructor())
271     return;
272 
273   // Elide the constructor if we're constructing from a temporary.
274   // The temporary check is required because Sema sets this on NRVO
275   // returns.
276   if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
277     assert(getContext().hasSameUnqualifiedType(E->getType(),
278                                                E->getArg(0)->getType()));
279     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
280       EmitAggExpr(E->getArg(0), Dest);
281       return;
282     }
283   }
284 
285   const ConstantArrayType *Array
286     = getContext().getAsConstantArrayType(E->getType());
287   if (Array) {
288     QualType BaseElementTy = getContext().getBaseElementType(Array);
289     const llvm::Type *BasePtr = ConvertType(BaseElementTy);
290     BasePtr = llvm::PointerType::getUnqual(BasePtr);
291     llvm::Value *BaseAddrPtr =
292       Builder.CreateBitCast(Dest.getAddr(), BasePtr);
293 
294     EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
295                                E->arg_begin(), E->arg_end());
296   }
297   else {
298     CXXCtorType Type =
299       (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
300       ? Ctor_Complete : Ctor_Base;
301     bool ForVirtualBase =
302       E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
303 
304     // Call the constructor.
305     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
306                            E->arg_begin(), E->arg_end());
307   }
308 }
309 
310 void
311 CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
312                                             llvm::Value *Src,
313                                             const Expr *Exp) {
314   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
315     Exp = E->getSubExpr();
316   assert(isa<CXXConstructExpr>(Exp) &&
317          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
318   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
319   const CXXConstructorDecl *CD = E->getConstructor();
320   RunCleanupsScope Scope(*this);
321 
322   // If we require zero initialization before (or instead of) calling the
323   // constructor, as can be the case with a non-user-provided default
324   // constructor, emit the zero initialization now.
325   // FIXME. Do I still need this for a copy ctor synthesis?
326   if (E->requiresZeroInitialization())
327     EmitNullInitialization(Dest, E->getType());
328 
329   assert(!getContext().getAsConstantArrayType(E->getType())
330          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
331   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
332                                  E->arg_begin(), E->arg_end());
333 }
334 
335 /// Check whether the given operator new[] is the global placement
336 /// operator new[].
337 static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
338                                         const FunctionDecl *Fn) {
339   // Must be in global scope.  Note that allocation functions can't be
340   // declared in namespaces.
341   if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
342     return false;
343 
344   // Signature must be void *operator new[](size_t, void*).
345   // The size_t is common to all operator new[]s.
346   if (Fn->getNumParams() != 2)
347     return false;
348 
349   CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
350   return (ParamType == Ctx.VoidPtrTy);
351 }
352 
353 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
354                                         const CXXNewExpr *E) {
355   if (!E->isArray())
356     return CharUnits::Zero();
357 
358   // No cookie is required if the new operator being used is
359   // ::operator new[](size_t, void*).
360   const FunctionDecl *OperatorNew = E->getOperatorNew();
361   if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
362     return CharUnits::Zero();
363 
364   return CGF.CGM.getCXXABI().GetArrayCookieSize(E->getAllocatedType());
365 }
366 
367 static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
368                                         CodeGenFunction &CGF,
369                                         const CXXNewExpr *E,
370                                         llvm::Value *&NumElements,
371                                         llvm::Value *&SizeWithoutCookie) {
372   QualType ElemType = E->getAllocatedType();
373 
374   const llvm::IntegerType *SizeTy =
375     cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
376 
377   CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
378 
379   if (!E->isArray()) {
380     SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
381     return SizeWithoutCookie;
382   }
383 
384   // Figure out the cookie size.
385   CharUnits CookieSize = CalculateCookiePadding(CGF, E);
386 
387   // Emit the array size expression.
388   // We multiply the size of all dimensions for NumElements.
389   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
390   NumElements = CGF.EmitScalarExpr(E->getArraySize());
391   assert(NumElements->getType() == SizeTy && "element count not a size_t");
392 
393   uint64_t ArraySizeMultiplier = 1;
394   while (const ConstantArrayType *CAT
395              = CGF.getContext().getAsConstantArrayType(ElemType)) {
396     ElemType = CAT->getElementType();
397     ArraySizeMultiplier *= CAT->getSize().getZExtValue();
398   }
399 
400   llvm::Value *Size;
401 
402   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
403   // Don't bloat the -O0 code.
404   if (llvm::ConstantInt *NumElementsC =
405         dyn_cast<llvm::ConstantInt>(NumElements)) {
406     llvm::APInt NEC = NumElementsC->getValue();
407     unsigned SizeWidth = NEC.getBitWidth();
408 
409     // Determine if there is an overflow here by doing an extended multiply.
410     NEC = NEC.zext(SizeWidth*2);
411     llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
412     SC *= NEC;
413 
414     if (!CookieSize.isZero()) {
415       // Save the current size without a cookie.  We don't care if an
416       // overflow's already happened because SizeWithoutCookie isn't
417       // used if the allocator returns null or throws, as it should
418       // always do on an overflow.
419       llvm::APInt SWC = SC.trunc(SizeWidth);
420       SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
421 
422       // Add the cookie size.
423       SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
424     }
425 
426     if (SC.countLeadingZeros() >= SizeWidth) {
427       SC = SC.trunc(SizeWidth);
428       Size = llvm::ConstantInt::get(SizeTy, SC);
429     } else {
430       // On overflow, produce a -1 so operator new throws.
431       Size = llvm::Constant::getAllOnesValue(SizeTy);
432     }
433 
434     // Scale NumElements while we're at it.
435     uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
436     NumElements = llvm::ConstantInt::get(SizeTy, N);
437 
438   // Otherwise, we don't need to do an overflow-checked multiplication if
439   // we're multiplying by one.
440   } else if (TypeSize.isOne()) {
441     assert(ArraySizeMultiplier == 1);
442 
443     Size = NumElements;
444 
445     // If we need a cookie, add its size in with an overflow check.
446     // This is maybe a little paranoid.
447     if (!CookieSize.isZero()) {
448       SizeWithoutCookie = Size;
449 
450       llvm::Value *CookieSizeV
451         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
452 
453       const llvm::Type *Types[] = { SizeTy };
454       llvm::Value *UAddF
455         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
456       llvm::Value *AddRes
457         = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
458 
459       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
460       llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
461       Size = CGF.Builder.CreateSelect(DidOverflow,
462                                       llvm::ConstantInt::get(SizeTy, -1),
463                                       Size);
464     }
465 
466   // Otherwise use the int.umul.with.overflow intrinsic.
467   } else {
468     llvm::Value *OutermostElementSize
469       = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
470 
471     llvm::Value *NumOutermostElements = NumElements;
472 
473     // Scale NumElements by the array size multiplier.  This might
474     // overflow, but only if the multiplication below also overflows,
475     // in which case this multiplication isn't used.
476     if (ArraySizeMultiplier != 1)
477       NumElements = CGF.Builder.CreateMul(NumElements,
478                          llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
479 
480     // The requested size of the outermost array is non-constant.
481     // Multiply that by the static size of the elements of that array;
482     // on unsigned overflow, set the size to -1 to trigger an
483     // exception from the allocation routine.  This is sufficient to
484     // prevent buffer overruns from the allocator returning a
485     // seemingly valid pointer to insufficient space.  This idea comes
486     // originally from MSVC, and GCC has an open bug requesting
487     // similar behavior:
488     //   http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
489     //
490     // This will not be sufficient for C++0x, which requires a
491     // specific exception class (std::bad_array_new_length).
492     // That will require ABI support that has not yet been specified.
493     const llvm::Type *Types[] = { SizeTy };
494     llvm::Value *UMulF
495       = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
496     llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
497                                                   OutermostElementSize);
498 
499     // The overflow bit.
500     llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
501 
502     // The result of the multiplication.
503     Size = CGF.Builder.CreateExtractValue(MulRes, 0);
504 
505     // If we have a cookie, we need to add that size in, too.
506     if (!CookieSize.isZero()) {
507       SizeWithoutCookie = Size;
508 
509       llvm::Value *CookieSizeV
510         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
511       llvm::Value *UAddF
512         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
513       llvm::Value *AddRes
514         = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
515 
516       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
517 
518       llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
519       DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
520     }
521 
522     Size = CGF.Builder.CreateSelect(DidOverflow,
523                                     llvm::ConstantInt::get(SizeTy, -1),
524                                     Size);
525   }
526 
527   if (CookieSize.isZero())
528     SizeWithoutCookie = Size;
529   else
530     assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
531 
532   return Size;
533 }
534 
535 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
536                                     llvm::Value *NewPtr) {
537 
538   assert(E->getNumConstructorArgs() == 1 &&
539          "Can only have one argument to initializer of POD type.");
540 
541   const Expr *Init = E->getConstructorArg(0);
542   QualType AllocType = E->getAllocatedType();
543 
544   unsigned Alignment =
545     CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
546   if (!CGF.hasAggregateLLVMType(AllocType))
547     CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
548                           AllocType.isVolatileQualified(), Alignment,
549                           AllocType);
550   else if (AllocType->isAnyComplexType())
551     CGF.EmitComplexExprIntoAddr(Init, NewPtr,
552                                 AllocType.isVolatileQualified());
553   else {
554     AggValueSlot Slot
555       = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
556     CGF.EmitAggExpr(Init, Slot);
557   }
558 }
559 
560 void
561 CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
562                                          llvm::Value *NewPtr,
563                                          llvm::Value *NumElements) {
564   // We have a POD type.
565   if (E->getNumConstructorArgs() == 0)
566     return;
567 
568   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
569 
570   // Create a temporary for the loop index and initialize it with 0.
571   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
572   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
573   Builder.CreateStore(Zero, IndexPtr);
574 
575   // Start the loop with a block that tests the condition.
576   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
577   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
578 
579   EmitBlock(CondBlock);
580 
581   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
582 
583   // Generate: if (loop-index < number-of-elements fall to the loop body,
584   // otherwise, go to the block after the for-loop.
585   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
586   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
587   // If the condition is true, execute the body.
588   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
589 
590   EmitBlock(ForBody);
591 
592   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
593   // Inside the loop body, emit the constructor call on the array element.
594   Counter = Builder.CreateLoad(IndexPtr);
595   llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
596                                                    "arrayidx");
597   StoreAnyExprIntoOneUnit(*this, E, Address);
598 
599   EmitBlock(ContinueBlock);
600 
601   // Emit the increment of the loop counter.
602   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
603   Counter = Builder.CreateLoad(IndexPtr);
604   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
605   Builder.CreateStore(NextVal, IndexPtr);
606 
607   // Finally, branch back up to the condition for the next iteration.
608   EmitBranch(CondBlock);
609 
610   // Emit the fall-through block.
611   EmitBlock(AfterFor, true);
612 }
613 
614 static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
615                            llvm::Value *NewPtr, llvm::Value *Size) {
616   llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
617   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
618   if (NewPtr->getType() != BP)
619     NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
620 
621   CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
622                            CGF.getContext().getTypeAlign(T)/8, false);
623 }
624 
625 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
626                                llvm::Value *NewPtr,
627                                llvm::Value *NumElements,
628                                llvm::Value *AllocSizeWithoutCookie) {
629   if (E->isArray()) {
630     if (CXXConstructorDecl *Ctor = E->getConstructor()) {
631       bool RequiresZeroInitialization = false;
632       if (Ctor->getParent()->hasTrivialConstructor()) {
633         // If new expression did not specify value-initialization, then there
634         // is no initialization.
635         if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
636           return;
637 
638         if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
639           // Optimization: since zero initialization will just set the memory
640           // to all zeroes, generate a single memset to do it in one shot.
641           EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
642                          AllocSizeWithoutCookie);
643           return;
644         }
645 
646         RequiresZeroInitialization = true;
647       }
648 
649       CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
650                                      E->constructor_arg_begin(),
651                                      E->constructor_arg_end(),
652                                      RequiresZeroInitialization);
653       return;
654     } else if (E->getNumConstructorArgs() == 1 &&
655                isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
656       // Optimization: since zero initialization will just set the memory
657       // to all zeroes, generate a single memset to do it in one shot.
658       EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
659                      AllocSizeWithoutCookie);
660       return;
661     } else {
662       CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
663       return;
664     }
665   }
666 
667   if (CXXConstructorDecl *Ctor = E->getConstructor()) {
668     // Per C++ [expr.new]p15, if we have an initializer, then we're performing
669     // direct initialization. C++ [dcl.init]p5 requires that we
670     // zero-initialize storage if there are no user-declared constructors.
671     if (E->hasInitializer() &&
672         !Ctor->getParent()->hasUserDeclaredConstructor() &&
673         !Ctor->getParent()->isEmpty())
674       CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
675 
676     CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
677                                NewPtr, E->constructor_arg_begin(),
678                                E->constructor_arg_end());
679 
680     return;
681   }
682   // We have a POD type.
683   if (E->getNumConstructorArgs() == 0)
684     return;
685 
686   StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
687 }
688 
689 namespace {
690 /// A utility class for saving an rvalue.
691 class SavedRValue {
692 public:
693   enum Kind { ScalarLiteral, ScalarAddress,
694               AggregateLiteral, AggregateAddress,
695               Complex };
696 
697 private:
698   llvm::Value *Value;
699   Kind K;
700 
701   SavedRValue(llvm::Value *V, Kind K) : Value(V), K(K) {}
702 
703 public:
704   SavedRValue() {}
705 
706   static SavedRValue forScalarLiteral(llvm::Value *V) {
707     return SavedRValue(V, ScalarLiteral);
708   }
709 
710   static SavedRValue forScalarAddress(llvm::Value *Addr) {
711     return SavedRValue(Addr, ScalarAddress);
712   }
713 
714   static SavedRValue forAggregateLiteral(llvm::Value *V) {
715     return SavedRValue(V, AggregateLiteral);
716   }
717 
718   static SavedRValue forAggregateAddress(llvm::Value *Addr) {
719     return SavedRValue(Addr, AggregateAddress);
720   }
721 
722   static SavedRValue forComplexAddress(llvm::Value *Addr) {
723     return SavedRValue(Addr, Complex);
724   }
725 
726   Kind getKind() const { return K; }
727   llvm::Value *getValue() const { return Value; }
728 };
729 } // end anonymous namespace
730 
731 /// Given an r-value, perform the code necessary to make sure that a
732 /// future RestoreRValue will be able to load the value without
733 /// domination concerns.
734 static SavedRValue SaveRValue(CodeGenFunction &CGF, RValue RV) {
735   if (RV.isScalar()) {
736     llvm::Value *V = RV.getScalarVal();
737 
738     // These automatically dominate and don't need to be saved.
739     if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
740       return SavedRValue::forScalarLiteral(V);
741 
742     // Everything else needs an alloca.
743     llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
744     CGF.Builder.CreateStore(V, Addr);
745     return SavedRValue::forScalarAddress(Addr);
746   }
747 
748   if (RV.isComplex()) {
749     CodeGenFunction::ComplexPairTy V = RV.getComplexVal();
750     const llvm::Type *ComplexTy =
751       llvm::StructType::get(CGF.getLLVMContext(),
752                             V.first->getType(), V.second->getType(),
753                             (void*) 0);
754     llvm::Value *Addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
755     CGF.StoreComplexToAddr(V, Addr, /*volatile*/ false);
756     return SavedRValue::forComplexAddress(Addr);
757   }
758 
759   assert(RV.isAggregate());
760   llvm::Value *V = RV.getAggregateAddr(); // TODO: volatile?
761   if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
762     return SavedRValue::forAggregateLiteral(V);
763 
764   llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
765   CGF.Builder.CreateStore(V, Addr);
766   return SavedRValue::forAggregateAddress(Addr);
767 }
768 
769 /// Given a saved r-value produced by SaveRValue, perform the code
770 /// necessary to restore it to usability at the current insertion
771 /// point.
772 static RValue RestoreRValue(CodeGenFunction &CGF, SavedRValue RV) {
773   switch (RV.getKind()) {
774   case SavedRValue::ScalarLiteral:
775     return RValue::get(RV.getValue());
776   case SavedRValue::ScalarAddress:
777     return RValue::get(CGF.Builder.CreateLoad(RV.getValue()));
778   case SavedRValue::AggregateLiteral:
779     return RValue::getAggregate(RV.getValue());
780   case SavedRValue::AggregateAddress:
781     return RValue::getAggregate(CGF.Builder.CreateLoad(RV.getValue()));
782   case SavedRValue::Complex:
783     return RValue::getComplex(CGF.LoadComplexFromAddr(RV.getValue(), false));
784   }
785 
786   llvm_unreachable("bad saved r-value kind");
787   return RValue();
788 }
789 
790 namespace {
791   /// A cleanup to call the given 'operator delete' function upon
792   /// abnormal exit from a new expression.
793   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
794     size_t NumPlacementArgs;
795     const FunctionDecl *OperatorDelete;
796     llvm::Value *Ptr;
797     llvm::Value *AllocSize;
798 
799     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
800 
801   public:
802     static size_t getExtraSize(size_t NumPlacementArgs) {
803       return NumPlacementArgs * sizeof(RValue);
804     }
805 
806     CallDeleteDuringNew(size_t NumPlacementArgs,
807                         const FunctionDecl *OperatorDelete,
808                         llvm::Value *Ptr,
809                         llvm::Value *AllocSize)
810       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
811         Ptr(Ptr), AllocSize(AllocSize) {}
812 
813     void setPlacementArg(unsigned I, RValue Arg) {
814       assert(I < NumPlacementArgs && "index out of range");
815       getPlacementArgs()[I] = Arg;
816     }
817 
818     void Emit(CodeGenFunction &CGF, bool IsForEH) {
819       const FunctionProtoType *FPT
820         = OperatorDelete->getType()->getAs<FunctionProtoType>();
821       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
822              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
823 
824       CallArgList DeleteArgs;
825 
826       // The first argument is always a void*.
827       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
828       DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
829 
830       // A member 'operator delete' can take an extra 'size_t' argument.
831       if (FPT->getNumArgs() == NumPlacementArgs + 2)
832         DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
833 
834       // Pass the rest of the arguments, which must match exactly.
835       for (unsigned I = 0; I != NumPlacementArgs; ++I)
836         DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
837 
838       // Call 'operator delete'.
839       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
840                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
841                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
842     }
843   };
844 
845   /// A cleanup to call the given 'operator delete' function upon
846   /// abnormal exit from a new expression when the new expression is
847   /// conditional.
848   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
849     size_t NumPlacementArgs;
850     const FunctionDecl *OperatorDelete;
851     SavedRValue Ptr;
852     SavedRValue AllocSize;
853 
854     SavedRValue *getPlacementArgs() {
855       return reinterpret_cast<SavedRValue*>(this+1);
856     }
857 
858   public:
859     static size_t getExtraSize(size_t NumPlacementArgs) {
860       return NumPlacementArgs * sizeof(SavedRValue);
861     }
862 
863     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
864                                    const FunctionDecl *OperatorDelete,
865                                    SavedRValue Ptr,
866                                    SavedRValue AllocSize)
867       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
868         Ptr(Ptr), AllocSize(AllocSize) {}
869 
870     void setPlacementArg(unsigned I, SavedRValue Arg) {
871       assert(I < NumPlacementArgs && "index out of range");
872       getPlacementArgs()[I] = Arg;
873     }
874 
875     void Emit(CodeGenFunction &CGF, bool IsForEH) {
876       const FunctionProtoType *FPT
877         = OperatorDelete->getType()->getAs<FunctionProtoType>();
878       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
879              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
880 
881       CallArgList DeleteArgs;
882 
883       // The first argument is always a void*.
884       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
885       DeleteArgs.push_back(std::make_pair(RestoreRValue(CGF, Ptr), *AI++));
886 
887       // A member 'operator delete' can take an extra 'size_t' argument.
888       if (FPT->getNumArgs() == NumPlacementArgs + 2) {
889         RValue RV = RestoreRValue(CGF, AllocSize);
890         DeleteArgs.push_back(std::make_pair(RV, *AI++));
891       }
892 
893       // Pass the rest of the arguments, which must match exactly.
894       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
895         RValue RV = RestoreRValue(CGF, getPlacementArgs()[I]);
896         DeleteArgs.push_back(std::make_pair(RV, *AI++));
897       }
898 
899       // Call 'operator delete'.
900       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
901                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
902                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
903     }
904   };
905 }
906 
907 /// Enter a cleanup to call 'operator delete' if the initializer in a
908 /// new-expression throws.
909 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
910                                   const CXXNewExpr *E,
911                                   llvm::Value *NewPtr,
912                                   llvm::Value *AllocSize,
913                                   const CallArgList &NewArgs) {
914   // If we're not inside a conditional branch, then the cleanup will
915   // dominate and we can do the easier (and more efficient) thing.
916   if (!CGF.isInConditionalBranch()) {
917     CallDeleteDuringNew *Cleanup = CGF.EHStack
918       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
919                                                  E->getNumPlacementArgs(),
920                                                  E->getOperatorDelete(),
921                                                  NewPtr, AllocSize);
922     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
923       Cleanup->setPlacementArg(I, NewArgs[I+1].first);
924 
925     return;
926   }
927 
928   // Otherwise, we need to save all this stuff.
929   SavedRValue SavedNewPtr = SaveRValue(CGF, RValue::get(NewPtr));
930   SavedRValue SavedAllocSize = SaveRValue(CGF, RValue::get(AllocSize));
931 
932   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
933     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
934                                                  E->getNumPlacementArgs(),
935                                                  E->getOperatorDelete(),
936                                                  SavedNewPtr,
937                                                  SavedAllocSize);
938   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
939     Cleanup->setPlacementArg(I, SaveRValue(CGF, NewArgs[I+1].first));
940 
941   CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
942 }
943 
944 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
945   QualType AllocType = E->getAllocatedType();
946   if (AllocType->isArrayType())
947     while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
948       AllocType = AType->getElementType();
949 
950   FunctionDecl *NewFD = E->getOperatorNew();
951   const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
952 
953   CallArgList NewArgs;
954 
955   // The allocation size is the first argument.
956   QualType SizeTy = getContext().getSizeType();
957 
958   llvm::Value *NumElements = 0;
959   llvm::Value *AllocSizeWithoutCookie = 0;
960   llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
961                                                *this, E, NumElements,
962                                                AllocSizeWithoutCookie);
963 
964   NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
965 
966   // Emit the rest of the arguments.
967   // FIXME: Ideally, this should just use EmitCallArgs.
968   CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
969 
970   // First, use the types from the function type.
971   // We start at 1 here because the first argument (the allocation size)
972   // has already been emitted.
973   for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
974     QualType ArgType = NewFTy->getArgType(i);
975 
976     assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
977            getTypePtr() ==
978            getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
979            "type mismatch in call argument!");
980 
981     NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
982                                      ArgType));
983 
984   }
985 
986   // Either we've emitted all the call args, or we have a call to a
987   // variadic function.
988   assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
989          "Extra arguments in non-variadic function!");
990 
991   // If we still have any arguments, emit them using the type of the argument.
992   for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
993        NewArg != NewArgEnd; ++NewArg) {
994     QualType ArgType = NewArg->getType();
995     NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
996                                      ArgType));
997   }
998 
999   // Emit the call to new.
1000   RValue RV =
1001     EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
1002              CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
1003 
1004   // If an allocation function is declared with an empty exception specification
1005   // it returns null to indicate failure to allocate storage. [expr.new]p13.
1006   // (We don't need to check for null when there's no new initializer and
1007   // we're allocating a POD type).
1008   bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
1009     !(AllocType->isPODType() && !E->hasInitializer());
1010 
1011   llvm::BasicBlock *NullCheckSource = 0;
1012   llvm::BasicBlock *NewNotNull = 0;
1013   llvm::BasicBlock *NewEnd = 0;
1014 
1015   llvm::Value *NewPtr = RV.getScalarVal();
1016   unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
1017 
1018   if (NullCheckResult) {
1019     NullCheckSource = Builder.GetInsertBlock();
1020     NewNotNull = createBasicBlock("new.notnull");
1021     NewEnd = createBasicBlock("new.end");
1022 
1023     llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
1024     Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
1025     EmitBlock(NewNotNull);
1026   }
1027 
1028   assert((AllocSize == AllocSizeWithoutCookie) ==
1029          CalculateCookiePadding(*this, E).isZero());
1030   if (AllocSize != AllocSizeWithoutCookie) {
1031     assert(E->isArray());
1032     NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
1033                                                    AllocType);
1034   }
1035 
1036   // If there's an operator delete, enter a cleanup to call it if an
1037   // exception is thrown.
1038   EHScopeStack::stable_iterator CallOperatorDelete;
1039   if (E->getOperatorDelete()) {
1040     EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
1041     CallOperatorDelete = EHStack.stable_begin();
1042   }
1043 
1044   const llvm::Type *ElementPtrTy
1045     = ConvertTypeForMem(AllocType)->getPointerTo(AS);
1046   NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
1047 
1048   if (E->isArray()) {
1049     EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
1050 
1051     // NewPtr is a pointer to the base element type.  If we're
1052     // allocating an array of arrays, we'll need to cast back to the
1053     // array pointer type.
1054     const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
1055     if (NewPtr->getType() != ResultTy)
1056       NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
1057   } else {
1058     EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
1059   }
1060 
1061   // Deactivate the 'operator delete' cleanup if we finished
1062   // initialization.
1063   if (CallOperatorDelete.isValid())
1064     DeactivateCleanupBlock(CallOperatorDelete);
1065 
1066   if (NullCheckResult) {
1067     Builder.CreateBr(NewEnd);
1068     llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
1069     EmitBlock(NewEnd);
1070 
1071     llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1072     PHI->reserveOperandSpace(2);
1073     PHI->addIncoming(NewPtr, NotNullSource);
1074     PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1075                      NullCheckSource);
1076 
1077     NewPtr = PHI;
1078   }
1079 
1080   return NewPtr;
1081 }
1082 
1083 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1084                                      llvm::Value *Ptr,
1085                                      QualType DeleteTy) {
1086   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1087 
1088   const FunctionProtoType *DeleteFTy =
1089     DeleteFD->getType()->getAs<FunctionProtoType>();
1090 
1091   CallArgList DeleteArgs;
1092 
1093   // Check if we need to pass the size to the delete operator.
1094   llvm::Value *Size = 0;
1095   QualType SizeTy;
1096   if (DeleteFTy->getNumArgs() == 2) {
1097     SizeTy = DeleteFTy->getArgType(1);
1098     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1099     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1100                                   DeleteTypeSize.getQuantity());
1101   }
1102 
1103   QualType ArgTy = DeleteFTy->getArgType(0);
1104   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1105   DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1106 
1107   if (Size)
1108     DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
1109 
1110   // Emit the call to delete.
1111   EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
1112            CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
1113            DeleteArgs, DeleteFD);
1114 }
1115 
1116 namespace {
1117   /// Calls the given 'operator delete' on a single object.
1118   struct CallObjectDelete : EHScopeStack::Cleanup {
1119     llvm::Value *Ptr;
1120     const FunctionDecl *OperatorDelete;
1121     QualType ElementType;
1122 
1123     CallObjectDelete(llvm::Value *Ptr,
1124                      const FunctionDecl *OperatorDelete,
1125                      QualType ElementType)
1126       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1127 
1128     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1129       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1130     }
1131   };
1132 }
1133 
1134 /// Emit the code for deleting a single object.
1135 static void EmitObjectDelete(CodeGenFunction &CGF,
1136                              const FunctionDecl *OperatorDelete,
1137                              llvm::Value *Ptr,
1138                              QualType ElementType) {
1139   // Find the destructor for the type, if applicable.  If the
1140   // destructor is virtual, we'll just emit the vcall and return.
1141   const CXXDestructorDecl *Dtor = 0;
1142   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1143     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1144     if (!RD->hasTrivialDestructor()) {
1145       Dtor = RD->getDestructor();
1146 
1147       if (Dtor->isVirtual()) {
1148         const llvm::Type *Ty =
1149           CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1150                                                                Dtor_Complete),
1151                                          /*isVariadic=*/false);
1152 
1153         llvm::Value *Callee
1154           = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1155         CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1156                               0, 0);
1157 
1158         // The dtor took care of deleting the object.
1159         return;
1160       }
1161     }
1162   }
1163 
1164   // Make sure that we call delete even if the dtor throws.
1165   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1166                                             Ptr, OperatorDelete, ElementType);
1167 
1168   if (Dtor)
1169     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1170                               /*ForVirtualBase=*/false, Ptr);
1171 
1172   CGF.PopCleanupBlock();
1173 }
1174 
1175 namespace {
1176   /// Calls the given 'operator delete' on an array of objects.
1177   struct CallArrayDelete : EHScopeStack::Cleanup {
1178     llvm::Value *Ptr;
1179     const FunctionDecl *OperatorDelete;
1180     llvm::Value *NumElements;
1181     QualType ElementType;
1182     CharUnits CookieSize;
1183 
1184     CallArrayDelete(llvm::Value *Ptr,
1185                     const FunctionDecl *OperatorDelete,
1186                     llvm::Value *NumElements,
1187                     QualType ElementType,
1188                     CharUnits CookieSize)
1189       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1190         ElementType(ElementType), CookieSize(CookieSize) {}
1191 
1192     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1193       const FunctionProtoType *DeleteFTy =
1194         OperatorDelete->getType()->getAs<FunctionProtoType>();
1195       assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1196 
1197       CallArgList Args;
1198 
1199       // Pass the pointer as the first argument.
1200       QualType VoidPtrTy = DeleteFTy->getArgType(0);
1201       llvm::Value *DeletePtr
1202         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1203       Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1204 
1205       // Pass the original requested size as the second argument.
1206       if (DeleteFTy->getNumArgs() == 2) {
1207         QualType size_t = DeleteFTy->getArgType(1);
1208         const llvm::IntegerType *SizeTy
1209           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1210 
1211         CharUnits ElementTypeSize =
1212           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1213 
1214         // The size of an element, multiplied by the number of elements.
1215         llvm::Value *Size
1216           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1217         Size = CGF.Builder.CreateMul(Size, NumElements);
1218 
1219         // Plus the size of the cookie if applicable.
1220         if (!CookieSize.isZero()) {
1221           llvm::Value *CookieSizeV
1222             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1223           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1224         }
1225 
1226         Args.push_back(std::make_pair(RValue::get(Size), size_t));
1227       }
1228 
1229       // Emit the call to delete.
1230       CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1231                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
1232                    ReturnValueSlot(), Args, OperatorDelete);
1233     }
1234   };
1235 }
1236 
1237 /// Emit the code for deleting an array of objects.
1238 static void EmitArrayDelete(CodeGenFunction &CGF,
1239                             const FunctionDecl *OperatorDelete,
1240                             llvm::Value *Ptr,
1241                             QualType ElementType) {
1242   llvm::Value *NumElements = 0;
1243   llvm::Value *AllocatedPtr = 0;
1244   CharUnits CookieSize;
1245   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, ElementType,
1246                                       NumElements, AllocatedPtr, CookieSize);
1247 
1248   assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1249 
1250   // Make sure that we call delete even if one of the dtors throws.
1251   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1252                                            AllocatedPtr, OperatorDelete,
1253                                            NumElements, ElementType,
1254                                            CookieSize);
1255 
1256   if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1257     if (!RD->hasTrivialDestructor()) {
1258       assert(NumElements && "ReadArrayCookie didn't find element count"
1259                             " for a class with destructor");
1260       CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1261     }
1262   }
1263 
1264   CGF.PopCleanupBlock();
1265 }
1266 
1267 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1268 
1269   // Get at the argument before we performed the implicit conversion
1270   // to void*.
1271   const Expr *Arg = E->getArgument();
1272   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1273     if (ICE->getCastKind() != CK_UserDefinedConversion &&
1274         ICE->getType()->isVoidPointerType())
1275       Arg = ICE->getSubExpr();
1276     else
1277       break;
1278   }
1279 
1280   llvm::Value *Ptr = EmitScalarExpr(Arg);
1281 
1282   // Null check the pointer.
1283   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1284   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1285 
1286   llvm::Value *IsNull =
1287     Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1288                          "isnull");
1289 
1290   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1291   EmitBlock(DeleteNotNull);
1292 
1293   // We might be deleting a pointer to array.  If so, GEP down to the
1294   // first non-array element.
1295   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1296   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1297   if (DeleteTy->isConstantArrayType()) {
1298     llvm::Value *Zero = Builder.getInt32(0);
1299     llvm::SmallVector<llvm::Value*,8> GEP;
1300 
1301     GEP.push_back(Zero); // point at the outermost array
1302 
1303     // For each layer of array type we're pointing at:
1304     while (const ConstantArrayType *Arr
1305              = getContext().getAsConstantArrayType(DeleteTy)) {
1306       // 1. Unpeel the array type.
1307       DeleteTy = Arr->getElementType();
1308 
1309       // 2. GEP to the first element of the array.
1310       GEP.push_back(Zero);
1311     }
1312 
1313     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
1314   }
1315 
1316   assert(ConvertTypeForMem(DeleteTy) ==
1317          cast<llvm::PointerType>(Ptr->getType())->getElementType());
1318 
1319   if (E->isArrayForm()) {
1320     EmitArrayDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1321   } else {
1322     EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1323   }
1324 
1325   EmitBlock(DeleteEnd);
1326 }
1327 
1328 llvm::Value * CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1329   QualType Ty = E->getType();
1330   const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
1331 
1332   if (E->isTypeOperand()) {
1333     llvm::Constant *TypeInfo =
1334       CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1335     return Builder.CreateBitCast(TypeInfo, LTy);
1336   }
1337 
1338   Expr *subE = E->getExprOperand();
1339   Ty = subE->getType();
1340   CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1341   Ty = CanTy.getUnqualifiedType().getNonReferenceType();
1342   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1343     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1344     if (RD->isPolymorphic()) {
1345       // FIXME: if subE is an lvalue do
1346       LValue Obj = EmitLValue(subE);
1347       llvm::Value *This = Obj.getAddress();
1348       // We need to do a zero check for *p, unless it has NonNullAttr.
1349       // FIXME: PointerType->hasAttr<NonNullAttr>()
1350       bool CanBeZero = false;
1351       if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
1352         if (UO->getOpcode() == UO_Deref)
1353           CanBeZero = true;
1354       if (CanBeZero) {
1355         llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1356         llvm::BasicBlock *ZeroBlock = createBasicBlock();
1357 
1358         llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1359         Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
1360                              NonZeroBlock, ZeroBlock);
1361         EmitBlock(ZeroBlock);
1362         /// Call __cxa_bad_typeid
1363         const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1364         const llvm::FunctionType *FTy;
1365         FTy = llvm::FunctionType::get(ResultType, false);
1366         llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1367         Builder.CreateCall(F)->setDoesNotReturn();
1368         Builder.CreateUnreachable();
1369         EmitBlock(NonZeroBlock);
1370       }
1371       llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
1372       V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1373       V = Builder.CreateLoad(V);
1374       return V;
1375     }
1376   }
1377   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
1378 }
1379 
1380 llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1381                                               const CXXDynamicCastExpr *DCE) {
1382   QualType SrcTy = DCE->getSubExpr()->getType();
1383   QualType DestTy = DCE->getTypeAsWritten();
1384   QualType InnerType = DestTy->getPointeeType();
1385 
1386   const llvm::Type *LTy = ConvertType(DCE->getType());
1387 
1388   bool CanBeZero = false;
1389   bool ToVoid = false;
1390   bool ThrowOnBad = false;
1391   if (DestTy->isPointerType()) {
1392     // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1393     CanBeZero = true;
1394     if (InnerType->isVoidType())
1395       ToVoid = true;
1396   } else {
1397     LTy = LTy->getPointerTo();
1398 
1399     // FIXME: What if exceptions are disabled?
1400     ThrowOnBad = true;
1401   }
1402 
1403   if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1404     SrcTy = SrcTy->getPointeeType();
1405   SrcTy = SrcTy.getUnqualifiedType();
1406 
1407   if (DestTy->isPointerType() || DestTy->isReferenceType())
1408     DestTy = DestTy->getPointeeType();
1409   DestTy = DestTy.getUnqualifiedType();
1410 
1411   llvm::BasicBlock *ContBlock = createBasicBlock();
1412   llvm::BasicBlock *NullBlock = 0;
1413   llvm::BasicBlock *NonZeroBlock = 0;
1414   if (CanBeZero) {
1415     NonZeroBlock = createBasicBlock();
1416     NullBlock = createBasicBlock();
1417     Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
1418     EmitBlock(NonZeroBlock);
1419   }
1420 
1421   llvm::BasicBlock *BadCastBlock = 0;
1422 
1423   const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
1424 
1425   // See if this is a dynamic_cast(void*)
1426   if (ToVoid) {
1427     llvm::Value *This = V;
1428     V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
1429     V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1430     V = Builder.CreateLoad(V, "offset to top");
1431     This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1432     V = Builder.CreateInBoundsGEP(This, V);
1433     V = Builder.CreateBitCast(V, LTy);
1434   } else {
1435     /// Call __dynamic_cast
1436     const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1437     const llvm::FunctionType *FTy;
1438     std::vector<const llvm::Type*> ArgTys;
1439     const llvm::Type *PtrToInt8Ty
1440       = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1441     ArgTys.push_back(PtrToInt8Ty);
1442     ArgTys.push_back(PtrToInt8Ty);
1443     ArgTys.push_back(PtrToInt8Ty);
1444     ArgTys.push_back(PtrDiffTy);
1445     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1446 
1447     // FIXME: Calculate better hint.
1448     llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
1449 
1450     assert(SrcTy->isRecordType() && "Src type must be record type!");
1451     assert(DestTy->isRecordType() && "Dest type must be record type!");
1452 
1453     llvm::Value *SrcArg
1454       = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1455     llvm::Value *DestArg
1456       = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
1457 
1458     V = Builder.CreateBitCast(V, PtrToInt8Ty);
1459     V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
1460                             V, SrcArg, DestArg, hint);
1461     V = Builder.CreateBitCast(V, LTy);
1462 
1463     if (ThrowOnBad) {
1464       BadCastBlock = createBasicBlock();
1465       Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
1466       EmitBlock(BadCastBlock);
1467       /// Invoke __cxa_bad_cast
1468       ResultType = llvm::Type::getVoidTy(VMContext);
1469       const llvm::FunctionType *FBadTy;
1470       FBadTy = llvm::FunctionType::get(ResultType, false);
1471       llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
1472       if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1473         llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1474         Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1475         EmitBlock(Cont);
1476       } else {
1477         // FIXME: Does this ever make sense?
1478         Builder.CreateCall(F)->setDoesNotReturn();
1479       }
1480       Builder.CreateUnreachable();
1481     }
1482   }
1483 
1484   if (CanBeZero) {
1485     Builder.CreateBr(ContBlock);
1486     EmitBlock(NullBlock);
1487     Builder.CreateBr(ContBlock);
1488   }
1489   EmitBlock(ContBlock);
1490   if (CanBeZero) {
1491     llvm::PHINode *PHI = Builder.CreatePHI(LTy);
1492     PHI->reserveOperandSpace(2);
1493     PHI->addIncoming(V, NonZeroBlock);
1494     PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
1495     V = PHI;
1496   }
1497 
1498   return V;
1499 }
1500