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