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