1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code dealing with code generation of C++ expressions
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenFunction.h"
14 #include "CGCUDARuntime.h"
15 #include "CGCXXABI.h"
16 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "ConstantEmitter.h"
19 #include "clang/Basic/CodeGenOptions.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "llvm/IR/Intrinsics.h"
22 
23 using namespace clang;
24 using namespace CodeGen;
25 
26 namespace {
27 struct MemberCallInfo {
28   RequiredArgs ReqArgs;
29   // Number of prefix arguments for the call. Ignores the `this` pointer.
30   unsigned PrefixSize;
31 };
32 }
33 
34 static MemberCallInfo
35 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
36                                   llvm::Value *This, llvm::Value *ImplicitParam,
37                                   QualType ImplicitParamTy, const CallExpr *CE,
38                                   CallArgList &Args, CallArgList *RtlArgs) {
39   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
40          isa<CXXOperatorCallExpr>(CE));
41   assert(MD->isInstance() &&
42          "Trying to emit a member or operator call expr on a static method!");
43   ASTContext &C = CGF.getContext();
44 
45   // Push the this ptr.
46   const CXXRecordDecl *RD =
47       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
48   Args.add(RValue::get(This),
49            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
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(), MD);
58   unsigned PrefixSize = Args.size() - 1;
59 
60   // And the rest of the call args.
61   if (RtlArgs) {
62     // Special case: if the caller emitted the arguments right-to-left already
63     // (prior to emitting the *this argument), we're done. This happens for
64     // assignment operators.
65     Args.addFrom(*RtlArgs);
66   } else if (CE) {
67     // Special case: skip first argument of CXXOperatorCall (it is "this").
68     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
69     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
70                      CE->getDirectCallee());
71   } else {
72     assert(
73         FPT->getNumParams() == 0 &&
74         "No CallExpr specified for function with non-zero number of arguments");
75   }
76   return {required, PrefixSize};
77 }
78 
79 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
80     const CXXMethodDecl *MD, const CGCallee &Callee,
81     ReturnValueSlot ReturnValue,
82     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
83     const CallExpr *CE, CallArgList *RtlArgs) {
84   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
85   CallArgList Args;
86   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
87       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
88   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
89       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
90   return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
91                   CE ? CE->getExprLoc() : SourceLocation());
92 }
93 
94 RValue CodeGenFunction::EmitCXXDestructorCall(
95     const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
96     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
97     StructorType Type) {
98   CallArgList Args;
99   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
100                                     ImplicitParamTy, CE, Args, nullptr);
101   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
102                   Callee, ReturnValueSlot(), Args);
103 }
104 
105 RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
106                                             const CXXPseudoDestructorExpr *E) {
107   QualType DestroyedType = E->getDestroyedType();
108   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
109     // Automatic Reference Counting:
110     //   If the pseudo-expression names a retainable object with weak or
111     //   strong lifetime, the object shall be released.
112     Expr *BaseExpr = E->getBase();
113     Address BaseValue = Address::invalid();
114     Qualifiers BaseQuals;
115 
116     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
117     if (E->isArrow()) {
118       BaseValue = EmitPointerWithAlignment(BaseExpr);
119       const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
120       BaseQuals = PTy->getPointeeType().getQualifiers();
121     } else {
122       LValue BaseLV = EmitLValue(BaseExpr);
123       BaseValue = BaseLV.getAddress();
124       QualType BaseTy = BaseExpr->getType();
125       BaseQuals = BaseTy.getQualifiers();
126     }
127 
128     switch (DestroyedType.getObjCLifetime()) {
129     case Qualifiers::OCL_None:
130     case Qualifiers::OCL_ExplicitNone:
131     case Qualifiers::OCL_Autoreleasing:
132       break;
133 
134     case Qualifiers::OCL_Strong:
135       EmitARCRelease(Builder.CreateLoad(BaseValue,
136                         DestroyedType.isVolatileQualified()),
137                      ARCPreciseLifetime);
138       break;
139 
140     case Qualifiers::OCL_Weak:
141       EmitARCDestroyWeak(BaseValue);
142       break;
143     }
144   } else {
145     // C++ [expr.pseudo]p1:
146     //   The result shall only be used as the operand for the function call
147     //   operator (), and the result of such a call has type void. The only
148     //   effect is the evaluation of the postfix-expression before the dot or
149     //   arrow.
150     EmitIgnoredExpr(E->getBase());
151   }
152 
153   return RValue::get(nullptr);
154 }
155 
156 static CXXRecordDecl *getCXXRecord(const Expr *E) {
157   QualType T = E->getType();
158   if (const PointerType *PTy = T->getAs<PointerType>())
159     T = PTy->getPointeeType();
160   const RecordType *Ty = T->castAs<RecordType>();
161   return cast<CXXRecordDecl>(Ty->getDecl());
162 }
163 
164 // Note: This function also emit constructor calls to support a MSVC
165 // extensions allowing explicit constructor function call.
166 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
167                                               ReturnValueSlot ReturnValue) {
168   const Expr *callee = CE->getCallee()->IgnoreParens();
169 
170   if (isa<BinaryOperator>(callee))
171     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
172 
173   const MemberExpr *ME = cast<MemberExpr>(callee);
174   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
175 
176   if (MD->isStatic()) {
177     // The method is static, emit it as we would a regular call.
178     CGCallee callee =
179         CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
180     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
181                     ReturnValue);
182   }
183 
184   bool HasQualifier = ME->hasQualifier();
185   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
186   bool IsArrow = ME->isArrow();
187   const Expr *Base = ME->getBase();
188 
189   return EmitCXXMemberOrOperatorMemberCallExpr(
190       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
191 }
192 
193 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
194     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
195     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
196     const Expr *Base) {
197   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
198 
199   // Compute the object pointer.
200   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
201 
202   const CXXMethodDecl *DevirtualizedMethod = nullptr;
203   if (CanUseVirtualCall &&
204       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
205     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
206     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
207     assert(DevirtualizedMethod);
208     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
209     const Expr *Inner = Base->ignoreParenBaseCasts();
210     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
211         MD->getReturnType().getCanonicalType())
212       // If the return types are not the same, this might be a case where more
213       // code needs to run to compensate for it. For example, the derived
214       // method might return a type that inherits form from the return
215       // type of MD and has a prefix.
216       // For now we just avoid devirtualizing these covariant cases.
217       DevirtualizedMethod = nullptr;
218     else if (getCXXRecord(Inner) == DevirtualizedClass)
219       // If the class of the Inner expression is where the dynamic method
220       // is defined, build the this pointer from it.
221       Base = Inner;
222     else if (getCXXRecord(Base) != DevirtualizedClass) {
223       // If the method is defined in a class that is not the best dynamic
224       // one or the one of the full expression, we would have to build
225       // a derived-to-base cast to compute the correct this pointer, but
226       // we don't have support for that yet, so do a virtual call.
227       DevirtualizedMethod = nullptr;
228     }
229   }
230 
231   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
232   // operator before the LHS.
233   CallArgList RtlArgStorage;
234   CallArgList *RtlArgs = nullptr;
235   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
236     if (OCE->isAssignmentOp()) {
237       RtlArgs = &RtlArgStorage;
238       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
239                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
240                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
241     }
242   }
243 
244   LValue This;
245   if (IsArrow) {
246     LValueBaseInfo BaseInfo;
247     TBAAAccessInfo TBAAInfo;
248     Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
249     This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
250   } else {
251     This = EmitLValue(Base);
252   }
253 
254 
255   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
256     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
257     if (isa<CXXConstructorDecl>(MD) &&
258         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
259       return RValue::get(nullptr);
260 
261     if (!MD->getParent()->mayInsertExtraPadding()) {
262       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
263         // We don't like to generate the trivial copy/move assignment operator
264         // when it isn't necessary; just produce the proper effect here.
265         LValue RHS = isa<CXXOperatorCallExpr>(CE)
266                          ? MakeNaturalAlignAddrLValue(
267                                (*RtlArgs)[0].getRValue(*this).getScalarVal(),
268                                (*(CE->arg_begin() + 1))->getType())
269                          : EmitLValue(*CE->arg_begin());
270         EmitAggregateAssign(This, RHS, CE->getType());
271         return RValue::get(This.getPointer());
272       }
273 
274       if (isa<CXXConstructorDecl>(MD) &&
275           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
276         // Trivial move and copy ctor are the same.
277         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
278         const Expr *Arg = *CE->arg_begin();
279         LValue RHS = EmitLValue(Arg);
280         LValue Dest = MakeAddrLValue(This.getAddress(), Arg->getType());
281         // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
282         // constructing a new complete object of type Ctor.
283         EmitAggregateCopy(Dest, RHS, Arg->getType(),
284                           AggValueSlot::DoesNotOverlap);
285         return RValue::get(This.getPointer());
286       }
287       llvm_unreachable("unknown trivial member function");
288     }
289   }
290 
291   // Compute the function type we're calling.
292   const CXXMethodDecl *CalleeDecl =
293       DevirtualizedMethod ? DevirtualizedMethod : MD;
294   const CGFunctionInfo *FInfo = nullptr;
295   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
296     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
297         Dtor, StructorType::Complete);
298   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
299     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
300         Ctor, StructorType::Complete);
301   else
302     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
303 
304   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
305 
306   // C++11 [class.mfct.non-static]p2:
307   //   If a non-static member function of a class X is called for an object that
308   //   is not of type X, or of a type derived from X, the behavior is undefined.
309   SourceLocation CallLoc;
310   ASTContext &C = getContext();
311   if (CE)
312     CallLoc = CE->getExprLoc();
313 
314   SanitizerSet SkippedChecks;
315   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
316     auto *IOA = CMCE->getImplicitObjectArgument();
317     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
318     if (IsImplicitObjectCXXThis)
319       SkippedChecks.set(SanitizerKind::Alignment, true);
320     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
321       SkippedChecks.set(SanitizerKind::Null, true);
322   }
323   EmitTypeCheck(
324       isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
325                                           : CodeGenFunction::TCK_MemberCall,
326       CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
327       /*Alignment=*/CharUnits::Zero(), SkippedChecks);
328 
329   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
330   // 'CalleeDecl' instead.
331 
332   // C++ [class.virtual]p12:
333   //   Explicit qualification with the scope operator (5.1) suppresses the
334   //   virtual call mechanism.
335   //
336   // We also don't emit a virtual call if the base expression has a record type
337   // because then we know what the type is.
338   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
339 
340   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
341     assert(CE->arg_begin() == CE->arg_end() &&
342            "Destructor shouldn't have explicit parameters");
343     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
344     if (UseVirtualCall) {
345       CGM.getCXXABI().EmitVirtualDestructorCall(
346           *this, Dtor, Dtor_Complete, This.getAddress(),
347           cast<CXXMemberCallExpr>(CE));
348     } else {
349       CGCallee Callee;
350       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
351         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
352       else if (!DevirtualizedMethod)
353         Callee = CGCallee::forDirect(
354             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
355             GlobalDecl(Dtor, Dtor_Complete));
356       else {
357         const CXXDestructorDecl *DDtor =
358           cast<CXXDestructorDecl>(DevirtualizedMethod);
359         Callee = CGCallee::forDirect(
360             CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
361             GlobalDecl(DDtor, Dtor_Complete));
362       }
363       EmitCXXMemberOrOperatorCall(
364           CalleeDecl, Callee, ReturnValue, This.getPointer(),
365           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
366     }
367     return RValue::get(nullptr);
368   }
369 
370   CGCallee Callee;
371   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
372     Callee = CGCallee::forDirect(
373         CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
374         GlobalDecl(Ctor, Ctor_Complete));
375   } else if (UseVirtualCall) {
376     Callee = CGCallee::forVirtual(CE, MD, This.getAddress(), Ty);
377   } else {
378     if (SanOpts.has(SanitizerKind::CFINVCall) &&
379         MD->getParent()->isDynamicClass()) {
380       llvm::Value *VTable;
381       const CXXRecordDecl *RD;
382       std::tie(VTable, RD) =
383           CGM.getCXXABI().LoadVTablePtr(*this, This.getAddress(),
384                                         MD->getParent());
385       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
386     }
387 
388     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
389       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
390     else if (!DevirtualizedMethod)
391       Callee =
392           CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
393     else {
394       Callee =
395           CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
396                               GlobalDecl(DevirtualizedMethod));
397     }
398   }
399 
400   if (MD->isVirtual()) {
401     Address NewThisAddr =
402         CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
403             *this, CalleeDecl, This.getAddress(), UseVirtualCall);
404     This.setAddress(NewThisAddr);
405   }
406 
407   return EmitCXXMemberOrOperatorCall(
408       CalleeDecl, Callee, ReturnValue, This.getPointer(),
409       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
410 }
411 
412 RValue
413 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
414                                               ReturnValueSlot ReturnValue) {
415   const BinaryOperator *BO =
416       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
417   const Expr *BaseExpr = BO->getLHS();
418   const Expr *MemFnExpr = BO->getRHS();
419 
420   const MemberPointerType *MPT =
421     MemFnExpr->getType()->castAs<MemberPointerType>();
422 
423   const FunctionProtoType *FPT =
424     MPT->getPointeeType()->castAs<FunctionProtoType>();
425   const CXXRecordDecl *RD =
426     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
427 
428   // Emit the 'this' pointer.
429   Address This = Address::invalid();
430   if (BO->getOpcode() == BO_PtrMemI)
431     This = EmitPointerWithAlignment(BaseExpr);
432   else
433     This = EmitLValue(BaseExpr).getAddress();
434 
435   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
436                 QualType(MPT->getClass(), 0));
437 
438   // Get the member function pointer.
439   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
440 
441   // Ask the ABI to load the callee.  Note that This is modified.
442   llvm::Value *ThisPtrForCall = nullptr;
443   CGCallee Callee =
444     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
445                                              ThisPtrForCall, MemFnPtr, MPT);
446 
447   CallArgList Args;
448 
449   QualType ThisType =
450     getContext().getPointerType(getContext().getTagDeclType(RD));
451 
452   // Push the this ptr.
453   Args.add(RValue::get(ThisPtrForCall), ThisType);
454 
455   RequiredArgs required =
456       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
457 
458   // And the rest of the call args
459   EmitCallArgs(Args, FPT, E->arguments());
460   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
461                                                       /*PrefixSize=*/0),
462                   Callee, ReturnValue, Args, nullptr, E->getExprLoc());
463 }
464 
465 RValue
466 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
467                                                const CXXMethodDecl *MD,
468                                                ReturnValueSlot ReturnValue) {
469   assert(MD->isInstance() &&
470          "Trying to emit a member call expr on a static method!");
471   return EmitCXXMemberOrOperatorMemberCallExpr(
472       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
473       /*IsArrow=*/false, E->getArg(0));
474 }
475 
476 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
477                                                ReturnValueSlot ReturnValue) {
478   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
479 }
480 
481 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
482                                             Address DestPtr,
483                                             const CXXRecordDecl *Base) {
484   if (Base->isEmpty())
485     return;
486 
487   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
488 
489   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
490   CharUnits NVSize = Layout.getNonVirtualSize();
491 
492   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
493   // present, they are initialized by the most derived class before calling the
494   // constructor.
495   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
496   Stores.emplace_back(CharUnits::Zero(), NVSize);
497 
498   // Each store is split by the existence of a vbptr.
499   CharUnits VBPtrWidth = CGF.getPointerSize();
500   std::vector<CharUnits> VBPtrOffsets =
501       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
502   for (CharUnits VBPtrOffset : VBPtrOffsets) {
503     // Stop before we hit any virtual base pointers located in virtual bases.
504     if (VBPtrOffset >= NVSize)
505       break;
506     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
507     CharUnits LastStoreOffset = LastStore.first;
508     CharUnits LastStoreSize = LastStore.second;
509 
510     CharUnits SplitBeforeOffset = LastStoreOffset;
511     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
512     assert(!SplitBeforeSize.isNegative() && "negative store size!");
513     if (!SplitBeforeSize.isZero())
514       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
515 
516     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
517     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
518     assert(!SplitAfterSize.isNegative() && "negative store size!");
519     if (!SplitAfterSize.isZero())
520       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
521   }
522 
523   // If the type contains a pointer to data member we can't memset it to zero.
524   // Instead, create a null constant and copy it to the destination.
525   // TODO: there are other patterns besides zero that we can usefully memset,
526   // like -1, which happens to be the pattern used by member-pointers.
527   // TODO: isZeroInitializable can be over-conservative in the case where a
528   // virtual base contains a member pointer.
529   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
530   if (!NullConstantForBase->isNullValue()) {
531     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
532         CGF.CGM.getModule(), NullConstantForBase->getType(),
533         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
534         NullConstantForBase, Twine());
535 
536     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
537                                DestPtr.getAlignment());
538     NullVariable->setAlignment(Align.getQuantity());
539 
540     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
541 
542     // Get and call the appropriate llvm.memcpy overload.
543     for (std::pair<CharUnits, CharUnits> Store : Stores) {
544       CharUnits StoreOffset = Store.first;
545       CharUnits StoreSize = Store.second;
546       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
547       CGF.Builder.CreateMemCpy(
548           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
549           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
550           StoreSizeVal);
551     }
552 
553   // Otherwise, just memset the whole thing to zero.  This is legal
554   // because in LLVM, all default initializers (other than the ones we just
555   // handled above) are guaranteed to have a bit pattern of all zeros.
556   } else {
557     for (std::pair<CharUnits, CharUnits> Store : Stores) {
558       CharUnits StoreOffset = Store.first;
559       CharUnits StoreSize = Store.second;
560       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
561       CGF.Builder.CreateMemSet(
562           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
563           CGF.Builder.getInt8(0), StoreSizeVal);
564     }
565   }
566 }
567 
568 void
569 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
570                                       AggValueSlot Dest) {
571   assert(!Dest.isIgnored() && "Must have a destination!");
572   const CXXConstructorDecl *CD = E->getConstructor();
573 
574   // If we require zero initialization before (or instead of) calling the
575   // constructor, as can be the case with a non-user-provided default
576   // constructor, emit the zero initialization now, unless destination is
577   // already zeroed.
578   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
579     switch (E->getConstructionKind()) {
580     case CXXConstructExpr::CK_Delegating:
581     case CXXConstructExpr::CK_Complete:
582       EmitNullInitialization(Dest.getAddress(), E->getType());
583       break;
584     case CXXConstructExpr::CK_VirtualBase:
585     case CXXConstructExpr::CK_NonVirtualBase:
586       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
587                                       CD->getParent());
588       break;
589     }
590   }
591 
592   // If this is a call to a trivial default constructor, do nothing.
593   if (CD->isTrivial() && CD->isDefaultConstructor())
594     return;
595 
596   // Elide the constructor if we're constructing from a temporary.
597   // The temporary check is required because Sema sets this on NRVO
598   // returns.
599   if (getLangOpts().ElideConstructors && E->isElidable()) {
600     assert(getContext().hasSameUnqualifiedType(E->getType(),
601                                                E->getArg(0)->getType()));
602     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
603       EmitAggExpr(E->getArg(0), Dest);
604       return;
605     }
606   }
607 
608   if (const ArrayType *arrayType
609         = getContext().getAsArrayType(E->getType())) {
610     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
611                                Dest.isSanitizerChecked());
612   } else {
613     CXXCtorType Type = Ctor_Complete;
614     bool ForVirtualBase = false;
615     bool Delegating = false;
616 
617     switch (E->getConstructionKind()) {
618      case CXXConstructExpr::CK_Delegating:
619       // We should be emitting a constructor; GlobalDecl will assert this
620       Type = CurGD.getCtorType();
621       Delegating = true;
622       break;
623 
624      case CXXConstructExpr::CK_Complete:
625       Type = Ctor_Complete;
626       break;
627 
628      case CXXConstructExpr::CK_VirtualBase:
629       ForVirtualBase = true;
630       LLVM_FALLTHROUGH;
631 
632      case CXXConstructExpr::CK_NonVirtualBase:
633       Type = Ctor_Base;
634     }
635 
636     // Call the constructor.
637     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
638                            Dest.getAddress(), E, Dest.mayOverlap(),
639                            Dest.isSanitizerChecked());
640   }
641 }
642 
643 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
644                                                  const Expr *Exp) {
645   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
646     Exp = E->getSubExpr();
647   assert(isa<CXXConstructExpr>(Exp) &&
648          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
649   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
650   const CXXConstructorDecl *CD = E->getConstructor();
651   RunCleanupsScope Scope(*this);
652 
653   // If we require zero initialization before (or instead of) calling the
654   // constructor, as can be the case with a non-user-provided default
655   // constructor, emit the zero initialization now.
656   // FIXME. Do I still need this for a copy ctor synthesis?
657   if (E->requiresZeroInitialization())
658     EmitNullInitialization(Dest, E->getType());
659 
660   assert(!getContext().getAsConstantArrayType(E->getType())
661          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
662   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
663 }
664 
665 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
666                                         const CXXNewExpr *E) {
667   if (!E->isArray())
668     return CharUnits::Zero();
669 
670   // No cookie is required if the operator new[] being used is the
671   // reserved placement operator new[].
672   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
673     return CharUnits::Zero();
674 
675   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
676 }
677 
678 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
679                                         const CXXNewExpr *e,
680                                         unsigned minElements,
681                                         llvm::Value *&numElements,
682                                         llvm::Value *&sizeWithoutCookie) {
683   QualType type = e->getAllocatedType();
684 
685   if (!e->isArray()) {
686     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
687     sizeWithoutCookie
688       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
689     return sizeWithoutCookie;
690   }
691 
692   // The width of size_t.
693   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
694 
695   // Figure out the cookie size.
696   llvm::APInt cookieSize(sizeWidth,
697                          CalculateCookiePadding(CGF, e).getQuantity());
698 
699   // Emit the array size expression.
700   // We multiply the size of all dimensions for NumElements.
701   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
702   numElements =
703     ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
704   if (!numElements)
705     numElements = CGF.EmitScalarExpr(e->getArraySize());
706   assert(isa<llvm::IntegerType>(numElements->getType()));
707 
708   // The number of elements can be have an arbitrary integer type;
709   // essentially, we need to multiply it by a constant factor, add a
710   // cookie size, and verify that the result is representable as a
711   // size_t.  That's just a gloss, though, and it's wrong in one
712   // important way: if the count is negative, it's an error even if
713   // the cookie size would bring the total size >= 0.
714   bool isSigned
715     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
716   llvm::IntegerType *numElementsType
717     = cast<llvm::IntegerType>(numElements->getType());
718   unsigned numElementsWidth = numElementsType->getBitWidth();
719 
720   // Compute the constant factor.
721   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
722   while (const ConstantArrayType *CAT
723              = CGF.getContext().getAsConstantArrayType(type)) {
724     type = CAT->getElementType();
725     arraySizeMultiplier *= CAT->getSize();
726   }
727 
728   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
729   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
730   typeSizeMultiplier *= arraySizeMultiplier;
731 
732   // This will be a size_t.
733   llvm::Value *size;
734 
735   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
736   // Don't bloat the -O0 code.
737   if (llvm::ConstantInt *numElementsC =
738         dyn_cast<llvm::ConstantInt>(numElements)) {
739     const llvm::APInt &count = numElementsC->getValue();
740 
741     bool hasAnyOverflow = false;
742 
743     // If 'count' was a negative number, it's an overflow.
744     if (isSigned && count.isNegative())
745       hasAnyOverflow = true;
746 
747     // We want to do all this arithmetic in size_t.  If numElements is
748     // wider than that, check whether it's already too big, and if so,
749     // overflow.
750     else if (numElementsWidth > sizeWidth &&
751              numElementsWidth - sizeWidth > count.countLeadingZeros())
752       hasAnyOverflow = true;
753 
754     // Okay, compute a count at the right width.
755     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
756 
757     // If there is a brace-initializer, we cannot allocate fewer elements than
758     // there are initializers. If we do, that's treated like an overflow.
759     if (adjustedCount.ult(minElements))
760       hasAnyOverflow = true;
761 
762     // Scale numElements by that.  This might overflow, but we don't
763     // care because it only overflows if allocationSize does, too, and
764     // if that overflows then we shouldn't use this.
765     numElements = llvm::ConstantInt::get(CGF.SizeTy,
766                                          adjustedCount * arraySizeMultiplier);
767 
768     // Compute the size before cookie, and track whether it overflowed.
769     bool overflow;
770     llvm::APInt allocationSize
771       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
772     hasAnyOverflow |= overflow;
773 
774     // Add in the cookie, and check whether it's overflowed.
775     if (cookieSize != 0) {
776       // Save the current size without a cookie.  This shouldn't be
777       // used if there was overflow.
778       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
779 
780       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
781       hasAnyOverflow |= overflow;
782     }
783 
784     // On overflow, produce a -1 so operator new will fail.
785     if (hasAnyOverflow) {
786       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
787     } else {
788       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
789     }
790 
791   // Otherwise, we might need to use the overflow intrinsics.
792   } else {
793     // There are up to five conditions we need to test for:
794     // 1) if isSigned, we need to check whether numElements is negative;
795     // 2) if numElementsWidth > sizeWidth, we need to check whether
796     //   numElements is larger than something representable in size_t;
797     // 3) if minElements > 0, we need to check whether numElements is smaller
798     //    than that.
799     // 4) we need to compute
800     //      sizeWithoutCookie := numElements * typeSizeMultiplier
801     //    and check whether it overflows; and
802     // 5) if we need a cookie, we need to compute
803     //      size := sizeWithoutCookie + cookieSize
804     //    and check whether it overflows.
805 
806     llvm::Value *hasOverflow = nullptr;
807 
808     // If numElementsWidth > sizeWidth, then one way or another, we're
809     // going to have to do a comparison for (2), and this happens to
810     // take care of (1), too.
811     if (numElementsWidth > sizeWidth) {
812       llvm::APInt threshold(numElementsWidth, 1);
813       threshold <<= sizeWidth;
814 
815       llvm::Value *thresholdV
816         = llvm::ConstantInt::get(numElementsType, threshold);
817 
818       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
819       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
820 
821     // Otherwise, if we're signed, we want to sext up to size_t.
822     } else if (isSigned) {
823       if (numElementsWidth < sizeWidth)
824         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
825 
826       // If there's a non-1 type size multiplier, then we can do the
827       // signedness check at the same time as we do the multiply
828       // because a negative number times anything will cause an
829       // unsigned overflow.  Otherwise, we have to do it here. But at least
830       // in this case, we can subsume the >= minElements check.
831       if (typeSizeMultiplier == 1)
832         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
833                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
834 
835     // Otherwise, zext up to size_t if necessary.
836     } else if (numElementsWidth < sizeWidth) {
837       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
838     }
839 
840     assert(numElements->getType() == CGF.SizeTy);
841 
842     if (minElements) {
843       // Don't allow allocation of fewer elements than we have initializers.
844       if (!hasOverflow) {
845         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
846                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
847       } else if (numElementsWidth > sizeWidth) {
848         // The other existing overflow subsumes this check.
849         // We do an unsigned comparison, since any signed value < -1 is
850         // taken care of either above or below.
851         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
852                           CGF.Builder.CreateICmpULT(numElements,
853                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
854       }
855     }
856 
857     size = numElements;
858 
859     // Multiply by the type size if necessary.  This multiplier
860     // includes all the factors for nested arrays.
861     //
862     // This step also causes numElements to be scaled up by the
863     // nested-array factor if necessary.  Overflow on this computation
864     // can be ignored because the result shouldn't be used if
865     // allocation fails.
866     if (typeSizeMultiplier != 1) {
867       llvm::Value *umul_with_overflow
868         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
869 
870       llvm::Value *tsmV =
871         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
872       llvm::Value *result =
873           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
874 
875       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
876       if (hasOverflow)
877         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
878       else
879         hasOverflow = overflowed;
880 
881       size = CGF.Builder.CreateExtractValue(result, 0);
882 
883       // Also scale up numElements by the array size multiplier.
884       if (arraySizeMultiplier != 1) {
885         // If the base element type size is 1, then we can re-use the
886         // multiply we just did.
887         if (typeSize.isOne()) {
888           assert(arraySizeMultiplier == typeSizeMultiplier);
889           numElements = size;
890 
891         // Otherwise we need a separate multiply.
892         } else {
893           llvm::Value *asmV =
894             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
895           numElements = CGF.Builder.CreateMul(numElements, asmV);
896         }
897       }
898     } else {
899       // numElements doesn't need to be scaled.
900       assert(arraySizeMultiplier == 1);
901     }
902 
903     // Add in the cookie size if necessary.
904     if (cookieSize != 0) {
905       sizeWithoutCookie = size;
906 
907       llvm::Value *uadd_with_overflow
908         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
909 
910       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
911       llvm::Value *result =
912           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
913 
914       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
915       if (hasOverflow)
916         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
917       else
918         hasOverflow = overflowed;
919 
920       size = CGF.Builder.CreateExtractValue(result, 0);
921     }
922 
923     // If we had any possibility of dynamic overflow, make a select to
924     // overwrite 'size' with an all-ones value, which should cause
925     // operator new to throw.
926     if (hasOverflow)
927       size = CGF.Builder.CreateSelect(hasOverflow,
928                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
929                                       size);
930   }
931 
932   if (cookieSize == 0)
933     sizeWithoutCookie = size;
934   else
935     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
936 
937   return size;
938 }
939 
940 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
941                                     QualType AllocType, Address NewPtr,
942                                     AggValueSlot::Overlap_t MayOverlap) {
943   // FIXME: Refactor with EmitExprAsInit.
944   switch (CGF.getEvaluationKind(AllocType)) {
945   case TEK_Scalar:
946     CGF.EmitScalarInit(Init, nullptr,
947                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
948     return;
949   case TEK_Complex:
950     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
951                                   /*isInit*/ true);
952     return;
953   case TEK_Aggregate: {
954     AggValueSlot Slot
955       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
956                               AggValueSlot::IsDestructed,
957                               AggValueSlot::DoesNotNeedGCBarriers,
958                               AggValueSlot::IsNotAliased,
959                               MayOverlap, AggValueSlot::IsNotZeroed,
960                               AggValueSlot::IsSanitizerChecked);
961     CGF.EmitAggExpr(Init, Slot);
962     return;
963   }
964   }
965   llvm_unreachable("bad evaluation kind");
966 }
967 
968 void CodeGenFunction::EmitNewArrayInitializer(
969     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
970     Address BeginPtr, llvm::Value *NumElements,
971     llvm::Value *AllocSizeWithoutCookie) {
972   // If we have a type with trivial initialization and no initializer,
973   // there's nothing to do.
974   if (!E->hasInitializer())
975     return;
976 
977   Address CurPtr = BeginPtr;
978 
979   unsigned InitListElements = 0;
980 
981   const Expr *Init = E->getInitializer();
982   Address EndOfInit = Address::invalid();
983   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
984   EHScopeStack::stable_iterator Cleanup;
985   llvm::Instruction *CleanupDominator = nullptr;
986 
987   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
988   CharUnits ElementAlign =
989     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
990 
991   // Attempt to perform zero-initialization using memset.
992   auto TryMemsetInitialization = [&]() -> bool {
993     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
994     // we can initialize with a memset to -1.
995     if (!CGM.getTypes().isZeroInitializable(ElementType))
996       return false;
997 
998     // Optimization: since zero initialization will just set the memory
999     // to all zeroes, generate a single memset to do it in one shot.
1000 
1001     // Subtract out the size of any elements we've already initialized.
1002     auto *RemainingSize = AllocSizeWithoutCookie;
1003     if (InitListElements) {
1004       // We know this can't overflow; we check this when doing the allocation.
1005       auto *InitializedSize = llvm::ConstantInt::get(
1006           RemainingSize->getType(),
1007           getContext().getTypeSizeInChars(ElementType).getQuantity() *
1008               InitListElements);
1009       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1010     }
1011 
1012     // Create the memset.
1013     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1014     return true;
1015   };
1016 
1017   // If the initializer is an initializer list, first do the explicit elements.
1018   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
1019     // Initializing from a (braced) string literal is a special case; the init
1020     // list element does not initialize a (single) array element.
1021     if (ILE->isStringLiteralInit()) {
1022       // Initialize the initial portion of length equal to that of the string
1023       // literal. The allocation must be for at least this much; we emitted a
1024       // check for that earlier.
1025       AggValueSlot Slot =
1026           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1027                                 AggValueSlot::IsDestructed,
1028                                 AggValueSlot::DoesNotNeedGCBarriers,
1029                                 AggValueSlot::IsNotAliased,
1030                                 AggValueSlot::DoesNotOverlap,
1031                                 AggValueSlot::IsNotZeroed,
1032                                 AggValueSlot::IsSanitizerChecked);
1033       EmitAggExpr(ILE->getInit(0), Slot);
1034 
1035       // Move past these elements.
1036       InitListElements =
1037           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1038               ->getSize().getZExtValue();
1039       CurPtr =
1040           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1041                                             Builder.getSize(InitListElements),
1042                                             "string.init.end"),
1043                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1044                                                           ElementSize));
1045 
1046       // Zero out the rest, if any remain.
1047       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1048       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1049         bool OK = TryMemsetInitialization();
1050         (void)OK;
1051         assert(OK && "couldn't memset character type?");
1052       }
1053       return;
1054     }
1055 
1056     InitListElements = ILE->getNumInits();
1057 
1058     // If this is a multi-dimensional array new, we will initialize multiple
1059     // elements with each init list element.
1060     QualType AllocType = E->getAllocatedType();
1061     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1062             AllocType->getAsArrayTypeUnsafe())) {
1063       ElementTy = ConvertTypeForMem(AllocType);
1064       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1065       InitListElements *= getContext().getConstantArrayElementCount(CAT);
1066     }
1067 
1068     // Enter a partial-destruction Cleanup if necessary.
1069     if (needsEHCleanup(DtorKind)) {
1070       // In principle we could tell the Cleanup where we are more
1071       // directly, but the control flow can get so varied here that it
1072       // would actually be quite complex.  Therefore we go through an
1073       // alloca.
1074       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1075                                    "array.init.end");
1076       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1077       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1078                                        ElementType, ElementAlign,
1079                                        getDestroyer(DtorKind));
1080       Cleanup = EHStack.stable_begin();
1081     }
1082 
1083     CharUnits StartAlign = CurPtr.getAlignment();
1084     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1085       // Tell the cleanup that it needs to destroy up to this
1086       // element.  TODO: some of these stores can be trivially
1087       // observed to be unnecessary.
1088       if (EndOfInit.isValid()) {
1089         auto FinishedPtr =
1090           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1091         Builder.CreateStore(FinishedPtr, EndOfInit);
1092       }
1093       // FIXME: If the last initializer is an incomplete initializer list for
1094       // an array, and we have an array filler, we can fold together the two
1095       // initialization loops.
1096       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1097                               ILE->getInit(i)->getType(), CurPtr,
1098                               AggValueSlot::DoesNotOverlap);
1099       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1100                                                  Builder.getSize(1),
1101                                                  "array.exp.next"),
1102                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1103     }
1104 
1105     // The remaining elements are filled with the array filler expression.
1106     Init = ILE->getArrayFiller();
1107 
1108     // Extract the initializer for the individual array elements by pulling
1109     // out the array filler from all the nested initializer lists. This avoids
1110     // generating a nested loop for the initialization.
1111     while (Init && Init->getType()->isConstantArrayType()) {
1112       auto *SubILE = dyn_cast<InitListExpr>(Init);
1113       if (!SubILE)
1114         break;
1115       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1116       Init = SubILE->getArrayFiller();
1117     }
1118 
1119     // Switch back to initializing one base element at a time.
1120     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1121   }
1122 
1123   // If all elements have already been initialized, skip any further
1124   // initialization.
1125   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1126   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1127     // If there was a Cleanup, deactivate it.
1128     if (CleanupDominator)
1129       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1130     return;
1131   }
1132 
1133   assert(Init && "have trailing elements to initialize but no initializer");
1134 
1135   // If this is a constructor call, try to optimize it out, and failing that
1136   // emit a single loop to initialize all remaining elements.
1137   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1138     CXXConstructorDecl *Ctor = CCE->getConstructor();
1139     if (Ctor->isTrivial()) {
1140       // If new expression did not specify value-initialization, then there
1141       // is no initialization.
1142       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1143         return;
1144 
1145       if (TryMemsetInitialization())
1146         return;
1147     }
1148 
1149     // Store the new Cleanup position for irregular Cleanups.
1150     //
1151     // FIXME: Share this cleanup with the constructor call emission rather than
1152     // having it create a cleanup of its own.
1153     if (EndOfInit.isValid())
1154       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1155 
1156     // Emit a constructor call loop to initialize the remaining elements.
1157     if (InitListElements)
1158       NumElements = Builder.CreateSub(
1159           NumElements,
1160           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1161     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1162                                /*NewPointerIsChecked*/true,
1163                                CCE->requiresZeroInitialization());
1164     return;
1165   }
1166 
1167   // If this is value-initialization, we can usually use memset.
1168   ImplicitValueInitExpr IVIE(ElementType);
1169   if (isa<ImplicitValueInitExpr>(Init)) {
1170     if (TryMemsetInitialization())
1171       return;
1172 
1173     // Switch to an ImplicitValueInitExpr for the element type. This handles
1174     // only one case: multidimensional array new of pointers to members. In
1175     // all other cases, we already have an initializer for the array element.
1176     Init = &IVIE;
1177   }
1178 
1179   // At this point we should have found an initializer for the individual
1180   // elements of the array.
1181   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1182          "got wrong type of element to initialize");
1183 
1184   // If we have an empty initializer list, we can usually use memset.
1185   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1186     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1187       return;
1188 
1189   // If we have a struct whose every field is value-initialized, we can
1190   // usually use memset.
1191   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1192     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1193       if (RType->getDecl()->isStruct()) {
1194         unsigned NumElements = 0;
1195         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1196           NumElements = CXXRD->getNumBases();
1197         for (auto *Field : RType->getDecl()->fields())
1198           if (!Field->isUnnamedBitfield())
1199             ++NumElements;
1200         // FIXME: Recurse into nested InitListExprs.
1201         if (ILE->getNumInits() == NumElements)
1202           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1203             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1204               --NumElements;
1205         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1206           return;
1207       }
1208     }
1209   }
1210 
1211   // Create the loop blocks.
1212   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1213   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1214   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1215 
1216   // Find the end of the array, hoisted out of the loop.
1217   llvm::Value *EndPtr =
1218     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1219 
1220   // If the number of elements isn't constant, we have to now check if there is
1221   // anything left to initialize.
1222   if (!ConstNum) {
1223     llvm::Value *IsEmpty =
1224       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1225     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1226   }
1227 
1228   // Enter the loop.
1229   EmitBlock(LoopBB);
1230 
1231   // Set up the current-element phi.
1232   llvm::PHINode *CurPtrPhi =
1233     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1234   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1235 
1236   CurPtr = Address(CurPtrPhi, ElementAlign);
1237 
1238   // Store the new Cleanup position for irregular Cleanups.
1239   if (EndOfInit.isValid())
1240     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1241 
1242   // Enter a partial-destruction Cleanup if necessary.
1243   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1244     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1245                                    ElementType, ElementAlign,
1246                                    getDestroyer(DtorKind));
1247     Cleanup = EHStack.stable_begin();
1248     CleanupDominator = Builder.CreateUnreachable();
1249   }
1250 
1251   // Emit the initializer into this element.
1252   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1253                           AggValueSlot::DoesNotOverlap);
1254 
1255   // Leave the Cleanup if we entered one.
1256   if (CleanupDominator) {
1257     DeactivateCleanupBlock(Cleanup, CleanupDominator);
1258     CleanupDominator->eraseFromParent();
1259   }
1260 
1261   // Advance to the next element by adjusting the pointer type as necessary.
1262   llvm::Value *NextPtr =
1263     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1264                                        "array.next");
1265 
1266   // Check whether we've gotten to the end of the array and, if so,
1267   // exit the loop.
1268   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1269   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1270   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1271 
1272   EmitBlock(ContBB);
1273 }
1274 
1275 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1276                                QualType ElementType, llvm::Type *ElementTy,
1277                                Address NewPtr, llvm::Value *NumElements,
1278                                llvm::Value *AllocSizeWithoutCookie) {
1279   ApplyDebugLocation DL(CGF, E);
1280   if (E->isArray())
1281     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1282                                 AllocSizeWithoutCookie);
1283   else if (const Expr *Init = E->getInitializer())
1284     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1285                             AggValueSlot::DoesNotOverlap);
1286 }
1287 
1288 /// Emit a call to an operator new or operator delete function, as implicitly
1289 /// created by new-expressions and delete-expressions.
1290 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1291                                 const FunctionDecl *CalleeDecl,
1292                                 const FunctionProtoType *CalleeType,
1293                                 const CallArgList &Args) {
1294   llvm::CallBase *CallOrInvoke;
1295   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1296   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
1297   RValue RV =
1298       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1299                        Args, CalleeType, /*chainCall=*/false),
1300                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1301 
1302   /// C++1y [expr.new]p10:
1303   ///   [In a new-expression,] an implementation is allowed to omit a call
1304   ///   to a replaceable global allocation function.
1305   ///
1306   /// We model such elidable calls with the 'builtin' attribute.
1307   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1308   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1309       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1310     CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex,
1311                                llvm::Attribute::Builtin);
1312   }
1313 
1314   return RV;
1315 }
1316 
1317 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1318                                                  const CallExpr *TheCall,
1319                                                  bool IsDelete) {
1320   CallArgList Args;
1321   EmitCallArgs(Args, Type->getParamTypes(), TheCall->arguments());
1322   // Find the allocation or deallocation function that we're calling.
1323   ASTContext &Ctx = getContext();
1324   DeclarationName Name = Ctx.DeclarationNames
1325       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1326 
1327   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1328     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1329       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1330         return EmitNewDeleteCall(*this, FD, Type, Args);
1331   llvm_unreachable("predeclared global operator new/delete is missing");
1332 }
1333 
1334 namespace {
1335 /// The parameters to pass to a usual operator delete.
1336 struct UsualDeleteParams {
1337   bool DestroyingDelete = false;
1338   bool Size = false;
1339   bool Alignment = false;
1340 };
1341 }
1342 
1343 static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1344   UsualDeleteParams Params;
1345 
1346   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1347   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1348 
1349   // The first argument is always a void*.
1350   ++AI;
1351 
1352   // The next parameter may be a std::destroying_delete_t.
1353   if (FD->isDestroyingOperatorDelete()) {
1354     Params.DestroyingDelete = true;
1355     assert(AI != AE);
1356     ++AI;
1357   }
1358 
1359   // Figure out what other parameters we should be implicitly passing.
1360   if (AI != AE && (*AI)->isIntegerType()) {
1361     Params.Size = true;
1362     ++AI;
1363   }
1364 
1365   if (AI != AE && (*AI)->isAlignValT()) {
1366     Params.Alignment = true;
1367     ++AI;
1368   }
1369 
1370   assert(AI == AE && "unexpected usual deallocation function parameter");
1371   return Params;
1372 }
1373 
1374 namespace {
1375   /// A cleanup to call the given 'operator delete' function upon abnormal
1376   /// exit from a new expression. Templated on a traits type that deals with
1377   /// ensuring that the arguments dominate the cleanup if necessary.
1378   template<typename Traits>
1379   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1380     /// Type used to hold llvm::Value*s.
1381     typedef typename Traits::ValueTy ValueTy;
1382     /// Type used to hold RValues.
1383     typedef typename Traits::RValueTy RValueTy;
1384     struct PlacementArg {
1385       RValueTy ArgValue;
1386       QualType ArgType;
1387     };
1388 
1389     unsigned NumPlacementArgs : 31;
1390     unsigned PassAlignmentToPlacementDelete : 1;
1391     const FunctionDecl *OperatorDelete;
1392     ValueTy Ptr;
1393     ValueTy AllocSize;
1394     CharUnits AllocAlign;
1395 
1396     PlacementArg *getPlacementArgs() {
1397       return reinterpret_cast<PlacementArg *>(this + 1);
1398     }
1399 
1400   public:
1401     static size_t getExtraSize(size_t NumPlacementArgs) {
1402       return NumPlacementArgs * sizeof(PlacementArg);
1403     }
1404 
1405     CallDeleteDuringNew(size_t NumPlacementArgs,
1406                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1407                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1408                         CharUnits AllocAlign)
1409       : NumPlacementArgs(NumPlacementArgs),
1410         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1411         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1412         AllocAlign(AllocAlign) {}
1413 
1414     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1415       assert(I < NumPlacementArgs && "index out of range");
1416       getPlacementArgs()[I] = {Arg, Type};
1417     }
1418 
1419     void Emit(CodeGenFunction &CGF, Flags flags) override {
1420       const FunctionProtoType *FPT =
1421           OperatorDelete->getType()->getAs<FunctionProtoType>();
1422       CallArgList DeleteArgs;
1423 
1424       // The first argument is always a void* (or C* for a destroying operator
1425       // delete for class type C).
1426       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1427 
1428       // Figure out what other parameters we should be implicitly passing.
1429       UsualDeleteParams Params;
1430       if (NumPlacementArgs) {
1431         // A placement deallocation function is implicitly passed an alignment
1432         // if the placement allocation function was, but is never passed a size.
1433         Params.Alignment = PassAlignmentToPlacementDelete;
1434       } else {
1435         // For a non-placement new-expression, 'operator delete' can take a
1436         // size and/or an alignment if it has the right parameters.
1437         Params = getUsualDeleteParams(OperatorDelete);
1438       }
1439 
1440       assert(!Params.DestroyingDelete &&
1441              "should not call destroying delete in a new-expression");
1442 
1443       // The second argument can be a std::size_t (for non-placement delete).
1444       if (Params.Size)
1445         DeleteArgs.add(Traits::get(CGF, AllocSize),
1446                        CGF.getContext().getSizeType());
1447 
1448       // The next (second or third) argument can be a std::align_val_t, which
1449       // is an enum whose underlying type is std::size_t.
1450       // FIXME: Use the right type as the parameter type. Note that in a call
1451       // to operator delete(size_t, ...), we may not have it available.
1452       if (Params.Alignment)
1453         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1454                            CGF.SizeTy, AllocAlign.getQuantity())),
1455                        CGF.getContext().getSizeType());
1456 
1457       // Pass the rest of the arguments, which must match exactly.
1458       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1459         auto Arg = getPlacementArgs()[I];
1460         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1461       }
1462 
1463       // Call 'operator delete'.
1464       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1465     }
1466   };
1467 }
1468 
1469 /// Enter a cleanup to call 'operator delete' if the initializer in a
1470 /// new-expression throws.
1471 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1472                                   const CXXNewExpr *E,
1473                                   Address NewPtr,
1474                                   llvm::Value *AllocSize,
1475                                   CharUnits AllocAlign,
1476                                   const CallArgList &NewArgs) {
1477   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1478 
1479   // If we're not inside a conditional branch, then the cleanup will
1480   // dominate and we can do the easier (and more efficient) thing.
1481   if (!CGF.isInConditionalBranch()) {
1482     struct DirectCleanupTraits {
1483       typedef llvm::Value *ValueTy;
1484       typedef RValue RValueTy;
1485       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1486       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1487     };
1488 
1489     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1490 
1491     DirectCleanup *Cleanup = CGF.EHStack
1492       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1493                                            E->getNumPlacementArgs(),
1494                                            E->getOperatorDelete(),
1495                                            NewPtr.getPointer(),
1496                                            AllocSize,
1497                                            E->passAlignment(),
1498                                            AllocAlign);
1499     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1500       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1501       Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1502     }
1503 
1504     return;
1505   }
1506 
1507   // Otherwise, we need to save all this stuff.
1508   DominatingValue<RValue>::saved_type SavedNewPtr =
1509     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1510   DominatingValue<RValue>::saved_type SavedAllocSize =
1511     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1512 
1513   struct ConditionalCleanupTraits {
1514     typedef DominatingValue<RValue>::saved_type ValueTy;
1515     typedef DominatingValue<RValue>::saved_type RValueTy;
1516     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1517       return V.restore(CGF);
1518     }
1519   };
1520   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1521 
1522   ConditionalCleanup *Cleanup = CGF.EHStack
1523     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1524                                               E->getNumPlacementArgs(),
1525                                               E->getOperatorDelete(),
1526                                               SavedNewPtr,
1527                                               SavedAllocSize,
1528                                               E->passAlignment(),
1529                                               AllocAlign);
1530   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1531     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1532     Cleanup->setPlacementArg(
1533         I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1534   }
1535 
1536   CGF.initFullExprCleanup();
1537 }
1538 
1539 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1540   // The element type being allocated.
1541   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1542 
1543   // 1. Build a call to the allocation function.
1544   FunctionDecl *allocator = E->getOperatorNew();
1545 
1546   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1547   unsigned minElements = 0;
1548   if (E->isArray() && E->hasInitializer()) {
1549     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1550     if (ILE && ILE->isStringLiteralInit())
1551       minElements =
1552           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1553               ->getSize().getZExtValue();
1554     else if (ILE)
1555       minElements = ILE->getNumInits();
1556   }
1557 
1558   llvm::Value *numElements = nullptr;
1559   llvm::Value *allocSizeWithoutCookie = nullptr;
1560   llvm::Value *allocSize =
1561     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1562                         allocSizeWithoutCookie);
1563   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
1564 
1565   // Emit the allocation call.  If the allocator is a global placement
1566   // operator, just "inline" it directly.
1567   Address allocation = Address::invalid();
1568   CallArgList allocatorArgs;
1569   if (allocator->isReservedGlobalPlacementOperator()) {
1570     assert(E->getNumPlacementArgs() == 1);
1571     const Expr *arg = *E->placement_arguments().begin();
1572 
1573     LValueBaseInfo BaseInfo;
1574     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1575 
1576     // The pointer expression will, in many cases, be an opaque void*.
1577     // In these cases, discard the computed alignment and use the
1578     // formal alignment of the allocated type.
1579     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1580       allocation = Address(allocation.getPointer(), allocAlign);
1581 
1582     // Set up allocatorArgs for the call to operator delete if it's not
1583     // the reserved global operator.
1584     if (E->getOperatorDelete() &&
1585         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1586       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1587       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1588     }
1589 
1590   } else {
1591     const FunctionProtoType *allocatorType =
1592       allocator->getType()->castAs<FunctionProtoType>();
1593     unsigned ParamsToSkip = 0;
1594 
1595     // The allocation size is the first argument.
1596     QualType sizeType = getContext().getSizeType();
1597     allocatorArgs.add(RValue::get(allocSize), sizeType);
1598     ++ParamsToSkip;
1599 
1600     if (allocSize != allocSizeWithoutCookie) {
1601       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1602       allocAlign = std::max(allocAlign, cookieAlign);
1603     }
1604 
1605     // The allocation alignment may be passed as the second argument.
1606     if (E->passAlignment()) {
1607       QualType AlignValT = sizeType;
1608       if (allocatorType->getNumParams() > 1) {
1609         AlignValT = allocatorType->getParamType(1);
1610         assert(getContext().hasSameUnqualifiedType(
1611                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1612                    sizeType) &&
1613                "wrong type for alignment parameter");
1614         ++ParamsToSkip;
1615       } else {
1616         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1617         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1618       }
1619       allocatorArgs.add(
1620           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1621           AlignValT);
1622     }
1623 
1624     // FIXME: Why do we not pass a CalleeDecl here?
1625     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1626                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1627 
1628     RValue RV =
1629       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1630 
1631     // If this was a call to a global replaceable allocation function that does
1632     // not take an alignment argument, the allocator is known to produce
1633     // storage that's suitably aligned for any object that fits, up to a known
1634     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1635     CharUnits allocationAlign = allocAlign;
1636     if (!E->passAlignment() &&
1637         allocator->isReplaceableGlobalAllocationFunction()) {
1638       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1639           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1640       allocationAlign = std::max(
1641           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1642     }
1643 
1644     allocation = Address(RV.getScalarVal(), allocationAlign);
1645   }
1646 
1647   // Emit a null check on the allocation result if the allocation
1648   // function is allowed to return null (because it has a non-throwing
1649   // exception spec or is the reserved placement new) and we have an
1650   // interesting initializer will be running sanitizers on the initialization.
1651   bool nullCheck = E->shouldNullCheckAllocation() &&
1652                    (!allocType.isPODType(getContext()) || E->hasInitializer() ||
1653                     sanitizePerformTypeCheck());
1654 
1655   llvm::BasicBlock *nullCheckBB = nullptr;
1656   llvm::BasicBlock *contBB = nullptr;
1657 
1658   // The null-check means that the initializer is conditionally
1659   // evaluated.
1660   ConditionalEvaluation conditional(*this);
1661 
1662   if (nullCheck) {
1663     conditional.begin(*this);
1664 
1665     nullCheckBB = Builder.GetInsertBlock();
1666     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1667     contBB = createBasicBlock("new.cont");
1668 
1669     llvm::Value *isNull =
1670       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1671     Builder.CreateCondBr(isNull, contBB, notNullBB);
1672     EmitBlock(notNullBB);
1673   }
1674 
1675   // If there's an operator delete, enter a cleanup to call it if an
1676   // exception is thrown.
1677   EHScopeStack::stable_iterator operatorDeleteCleanup;
1678   llvm::Instruction *cleanupDominator = nullptr;
1679   if (E->getOperatorDelete() &&
1680       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1681     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1682                           allocatorArgs);
1683     operatorDeleteCleanup = EHStack.stable_begin();
1684     cleanupDominator = Builder.CreateUnreachable();
1685   }
1686 
1687   assert((allocSize == allocSizeWithoutCookie) ==
1688          CalculateCookiePadding(*this, E).isZero());
1689   if (allocSize != allocSizeWithoutCookie) {
1690     assert(E->isArray());
1691     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1692                                                        numElements,
1693                                                        E, allocType);
1694   }
1695 
1696   llvm::Type *elementTy = ConvertTypeForMem(allocType);
1697   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1698 
1699   // Passing pointer through launder.invariant.group to avoid propagation of
1700   // vptrs information which may be included in previous type.
1701   // To not break LTO with different optimizations levels, we do it regardless
1702   // of optimization level.
1703   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1704       allocator->isReservedGlobalPlacementOperator())
1705     result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
1706                      result.getAlignment());
1707 
1708   // Emit sanitizer checks for pointer value now, so that in the case of an
1709   // array it was checked only once and not at each constructor call. We may
1710   // have already checked that the pointer is non-null.
1711   // FIXME: If we have an array cookie and a potentially-throwing allocator,
1712   // we'll null check the wrong pointer here.
1713   SanitizerSet SkippedChecks;
1714   SkippedChecks.set(SanitizerKind::Null, nullCheck);
1715   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
1716                 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1717                 result.getPointer(), allocType, result.getAlignment(),
1718                 SkippedChecks, numElements);
1719 
1720   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1721                      allocSizeWithoutCookie);
1722   if (E->isArray()) {
1723     // NewPtr is a pointer to the base element type.  If we're
1724     // allocating an array of arrays, we'll need to cast back to the
1725     // array pointer type.
1726     llvm::Type *resultType = ConvertTypeForMem(E->getType());
1727     if (result.getType() != resultType)
1728       result = Builder.CreateBitCast(result, resultType);
1729   }
1730 
1731   // Deactivate the 'operator delete' cleanup if we finished
1732   // initialization.
1733   if (operatorDeleteCleanup.isValid()) {
1734     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1735     cleanupDominator->eraseFromParent();
1736   }
1737 
1738   llvm::Value *resultPtr = result.getPointer();
1739   if (nullCheck) {
1740     conditional.end(*this);
1741 
1742     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1743     EmitBlock(contBB);
1744 
1745     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1746     PHI->addIncoming(resultPtr, notNullBB);
1747     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1748                      nullCheckBB);
1749 
1750     resultPtr = PHI;
1751   }
1752 
1753   return resultPtr;
1754 }
1755 
1756 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1757                                      llvm::Value *Ptr, QualType DeleteTy,
1758                                      llvm::Value *NumElements,
1759                                      CharUnits CookieSize) {
1760   assert((!NumElements && CookieSize.isZero()) ||
1761          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1762 
1763   const FunctionProtoType *DeleteFTy =
1764     DeleteFD->getType()->getAs<FunctionProtoType>();
1765 
1766   CallArgList DeleteArgs;
1767 
1768   auto Params = getUsualDeleteParams(DeleteFD);
1769   auto ParamTypeIt = DeleteFTy->param_type_begin();
1770 
1771   // Pass the pointer itself.
1772   QualType ArgTy = *ParamTypeIt++;
1773   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1774   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1775 
1776   // Pass the std::destroying_delete tag if present.
1777   if (Params.DestroyingDelete) {
1778     QualType DDTag = *ParamTypeIt++;
1779     // Just pass an 'undef'. We expect the tag type to be an empty struct.
1780     auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1781     DeleteArgs.add(RValue::get(V), DDTag);
1782   }
1783 
1784   // Pass the size if the delete function has a size_t parameter.
1785   if (Params.Size) {
1786     QualType SizeType = *ParamTypeIt++;
1787     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1788     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1789                                                DeleteTypeSize.getQuantity());
1790 
1791     // For array new, multiply by the number of elements.
1792     if (NumElements)
1793       Size = Builder.CreateMul(Size, NumElements);
1794 
1795     // If there is a cookie, add the cookie size.
1796     if (!CookieSize.isZero())
1797       Size = Builder.CreateAdd(
1798           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1799 
1800     DeleteArgs.add(RValue::get(Size), SizeType);
1801   }
1802 
1803   // Pass the alignment if the delete function has an align_val_t parameter.
1804   if (Params.Alignment) {
1805     QualType AlignValType = *ParamTypeIt++;
1806     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1807         getContext().getTypeAlignIfKnown(DeleteTy));
1808     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1809                                                 DeleteTypeAlign.getQuantity());
1810     DeleteArgs.add(RValue::get(Align), AlignValType);
1811   }
1812 
1813   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1814          "unknown parameter to usual delete function");
1815 
1816   // Emit the call to delete.
1817   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1818 }
1819 
1820 namespace {
1821   /// Calls the given 'operator delete' on a single object.
1822   struct CallObjectDelete final : EHScopeStack::Cleanup {
1823     llvm::Value *Ptr;
1824     const FunctionDecl *OperatorDelete;
1825     QualType ElementType;
1826 
1827     CallObjectDelete(llvm::Value *Ptr,
1828                      const FunctionDecl *OperatorDelete,
1829                      QualType ElementType)
1830       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1831 
1832     void Emit(CodeGenFunction &CGF, Flags flags) override {
1833       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1834     }
1835   };
1836 }
1837 
1838 void
1839 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1840                                              llvm::Value *CompletePtr,
1841                                              QualType ElementType) {
1842   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1843                                         OperatorDelete, ElementType);
1844 }
1845 
1846 /// Emit the code for deleting a single object with a destroying operator
1847 /// delete. If the element type has a non-virtual destructor, Ptr has already
1848 /// been converted to the type of the parameter of 'operator delete'. Otherwise
1849 /// Ptr points to an object of the static type.
1850 static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1851                                        const CXXDeleteExpr *DE, Address Ptr,
1852                                        QualType ElementType) {
1853   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1854   if (Dtor && Dtor->isVirtual())
1855     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1856                                                 Dtor);
1857   else
1858     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1859 }
1860 
1861 /// Emit the code for deleting a single object.
1862 static void EmitObjectDelete(CodeGenFunction &CGF,
1863                              const CXXDeleteExpr *DE,
1864                              Address Ptr,
1865                              QualType ElementType) {
1866   // C++11 [expr.delete]p3:
1867   //   If the static type of the object to be deleted is different from its
1868   //   dynamic type, the static type shall be a base class of the dynamic type
1869   //   of the object to be deleted and the static type shall have a virtual
1870   //   destructor or the behavior is undefined.
1871   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1872                     DE->getExprLoc(), Ptr.getPointer(),
1873                     ElementType);
1874 
1875   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1876   assert(!OperatorDelete->isDestroyingOperatorDelete());
1877 
1878   // Find the destructor for the type, if applicable.  If the
1879   // destructor is virtual, we'll just emit the vcall and return.
1880   const CXXDestructorDecl *Dtor = nullptr;
1881   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1882     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1883     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1884       Dtor = RD->getDestructor();
1885 
1886       if (Dtor->isVirtual()) {
1887         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1888                                                     Dtor);
1889         return;
1890       }
1891     }
1892   }
1893 
1894   // Make sure that we call delete even if the dtor throws.
1895   // This doesn't have to a conditional cleanup because we're going
1896   // to pop it off in a second.
1897   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1898                                             Ptr.getPointer(),
1899                                             OperatorDelete, ElementType);
1900 
1901   if (Dtor)
1902     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1903                               /*ForVirtualBase=*/false,
1904                               /*Delegating=*/false,
1905                               Ptr);
1906   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1907     switch (Lifetime) {
1908     case Qualifiers::OCL_None:
1909     case Qualifiers::OCL_ExplicitNone:
1910     case Qualifiers::OCL_Autoreleasing:
1911       break;
1912 
1913     case Qualifiers::OCL_Strong:
1914       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1915       break;
1916 
1917     case Qualifiers::OCL_Weak:
1918       CGF.EmitARCDestroyWeak(Ptr);
1919       break;
1920     }
1921   }
1922 
1923   CGF.PopCleanupBlock();
1924 }
1925 
1926 namespace {
1927   /// Calls the given 'operator delete' on an array of objects.
1928   struct CallArrayDelete final : EHScopeStack::Cleanup {
1929     llvm::Value *Ptr;
1930     const FunctionDecl *OperatorDelete;
1931     llvm::Value *NumElements;
1932     QualType ElementType;
1933     CharUnits CookieSize;
1934 
1935     CallArrayDelete(llvm::Value *Ptr,
1936                     const FunctionDecl *OperatorDelete,
1937                     llvm::Value *NumElements,
1938                     QualType ElementType,
1939                     CharUnits CookieSize)
1940       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1941         ElementType(ElementType), CookieSize(CookieSize) {}
1942 
1943     void Emit(CodeGenFunction &CGF, Flags flags) override {
1944       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1945                          CookieSize);
1946     }
1947   };
1948 }
1949 
1950 /// Emit the code for deleting an array of objects.
1951 static void EmitArrayDelete(CodeGenFunction &CGF,
1952                             const CXXDeleteExpr *E,
1953                             Address deletedPtr,
1954                             QualType elementType) {
1955   llvm::Value *numElements = nullptr;
1956   llvm::Value *allocatedPtr = nullptr;
1957   CharUnits cookieSize;
1958   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1959                                       numElements, allocatedPtr, cookieSize);
1960 
1961   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1962 
1963   // Make sure that we call delete even if one of the dtors throws.
1964   const FunctionDecl *operatorDelete = E->getOperatorDelete();
1965   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1966                                            allocatedPtr, operatorDelete,
1967                                            numElements, elementType,
1968                                            cookieSize);
1969 
1970   // Destroy the elements.
1971   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1972     assert(numElements && "no element count for a type with a destructor!");
1973 
1974     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1975     CharUnits elementAlign =
1976       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1977 
1978     llvm::Value *arrayBegin = deletedPtr.getPointer();
1979     llvm::Value *arrayEnd =
1980       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1981 
1982     // Note that it is legal to allocate a zero-length array, and we
1983     // can never fold the check away because the length should always
1984     // come from a cookie.
1985     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1986                          CGF.getDestroyer(dtorKind),
1987                          /*checkZeroLength*/ true,
1988                          CGF.needsEHCleanup(dtorKind));
1989   }
1990 
1991   // Pop the cleanup block.
1992   CGF.PopCleanupBlock();
1993 }
1994 
1995 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1996   const Expr *Arg = E->getArgument();
1997   Address Ptr = EmitPointerWithAlignment(Arg);
1998 
1999   // Null check the pointer.
2000   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
2001   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
2002 
2003   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
2004 
2005   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2006   EmitBlock(DeleteNotNull);
2007 
2008   QualType DeleteTy = E->getDestroyedType();
2009 
2010   // A destroying operator delete overrides the entire operation of the
2011   // delete expression.
2012   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2013     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2014     EmitBlock(DeleteEnd);
2015     return;
2016   }
2017 
2018   // We might be deleting a pointer to array.  If so, GEP down to the
2019   // first non-array element.
2020   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
2021   if (DeleteTy->isConstantArrayType()) {
2022     llvm::Value *Zero = Builder.getInt32(0);
2023     SmallVector<llvm::Value*,8> GEP;
2024 
2025     GEP.push_back(Zero); // point at the outermost array
2026 
2027     // For each layer of array type we're pointing at:
2028     while (const ConstantArrayType *Arr
2029              = getContext().getAsConstantArrayType(DeleteTy)) {
2030       // 1. Unpeel the array type.
2031       DeleteTy = Arr->getElementType();
2032 
2033       // 2. GEP to the first element of the array.
2034       GEP.push_back(Zero);
2035     }
2036 
2037     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2038                   Ptr.getAlignment());
2039   }
2040 
2041   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
2042 
2043   if (E->isArrayForm()) {
2044     EmitArrayDelete(*this, E, Ptr, DeleteTy);
2045   } else {
2046     EmitObjectDelete(*this, E, Ptr, DeleteTy);
2047   }
2048 
2049   EmitBlock(DeleteEnd);
2050 }
2051 
2052 static bool isGLValueFromPointerDeref(const Expr *E) {
2053   E = E->IgnoreParens();
2054 
2055   if (const auto *CE = dyn_cast<CastExpr>(E)) {
2056     if (!CE->getSubExpr()->isGLValue())
2057       return false;
2058     return isGLValueFromPointerDeref(CE->getSubExpr());
2059   }
2060 
2061   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2062     return isGLValueFromPointerDeref(OVE->getSourceExpr());
2063 
2064   if (const auto *BO = dyn_cast<BinaryOperator>(E))
2065     if (BO->getOpcode() == BO_Comma)
2066       return isGLValueFromPointerDeref(BO->getRHS());
2067 
2068   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2069     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2070            isGLValueFromPointerDeref(ACO->getFalseExpr());
2071 
2072   // C++11 [expr.sub]p1:
2073   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2074   if (isa<ArraySubscriptExpr>(E))
2075     return true;
2076 
2077   if (const auto *UO = dyn_cast<UnaryOperator>(E))
2078     if (UO->getOpcode() == UO_Deref)
2079       return true;
2080 
2081   return false;
2082 }
2083 
2084 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2085                                          llvm::Type *StdTypeInfoPtrTy) {
2086   // Get the vtable pointer.
2087   Address ThisPtr = CGF.EmitLValue(E).getAddress();
2088 
2089   QualType SrcRecordTy = E->getType();
2090 
2091   // C++ [class.cdtor]p4:
2092   //   If the operand of typeid refers to the object under construction or
2093   //   destruction and the static type of the operand is neither the constructor
2094   //   or destructor’s class nor one of its bases, the behavior is undefined.
2095   CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2096                     ThisPtr.getPointer(), SrcRecordTy);
2097 
2098   // C++ [expr.typeid]p2:
2099   //   If the glvalue expression is obtained by applying the unary * operator to
2100   //   a pointer and the pointer is a null pointer value, the typeid expression
2101   //   throws the std::bad_typeid exception.
2102   //
2103   // However, this paragraph's intent is not clear.  We choose a very generous
2104   // interpretation which implores us to consider comma operators, conditional
2105   // operators, parentheses and other such constructs.
2106   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2107           isGLValueFromPointerDeref(E), SrcRecordTy)) {
2108     llvm::BasicBlock *BadTypeidBlock =
2109         CGF.createBasicBlock("typeid.bad_typeid");
2110     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2111 
2112     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2113     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2114 
2115     CGF.EmitBlock(BadTypeidBlock);
2116     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2117     CGF.EmitBlock(EndBlock);
2118   }
2119 
2120   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2121                                         StdTypeInfoPtrTy);
2122 }
2123 
2124 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2125   llvm::Type *StdTypeInfoPtrTy =
2126     ConvertType(E->getType())->getPointerTo();
2127 
2128   if (E->isTypeOperand()) {
2129     llvm::Constant *TypeInfo =
2130         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2131     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2132   }
2133 
2134   // C++ [expr.typeid]p2:
2135   //   When typeid is applied to a glvalue expression whose type is a
2136   //   polymorphic class type, the result refers to a std::type_info object
2137   //   representing the type of the most derived object (that is, the dynamic
2138   //   type) to which the glvalue refers.
2139   if (E->isPotentiallyEvaluated())
2140     return EmitTypeidFromVTable(*this, E->getExprOperand(),
2141                                 StdTypeInfoPtrTy);
2142 
2143   QualType OperandTy = E->getExprOperand()->getType();
2144   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2145                                StdTypeInfoPtrTy);
2146 }
2147 
2148 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2149                                           QualType DestTy) {
2150   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2151   if (DestTy->isPointerType())
2152     return llvm::Constant::getNullValue(DestLTy);
2153 
2154   /// C++ [expr.dynamic.cast]p9:
2155   ///   A failed cast to reference type throws std::bad_cast
2156   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2157     return nullptr;
2158 
2159   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2160   return llvm::UndefValue::get(DestLTy);
2161 }
2162 
2163 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2164                                               const CXXDynamicCastExpr *DCE) {
2165   CGM.EmitExplicitCastExprType(DCE, this);
2166   QualType DestTy = DCE->getTypeAsWritten();
2167 
2168   QualType SrcTy = DCE->getSubExpr()->getType();
2169 
2170   // C++ [expr.dynamic.cast]p7:
2171   //   If T is "pointer to cv void," then the result is a pointer to the most
2172   //   derived object pointed to by v.
2173   const PointerType *DestPTy = DestTy->getAs<PointerType>();
2174 
2175   bool isDynamicCastToVoid;
2176   QualType SrcRecordTy;
2177   QualType DestRecordTy;
2178   if (DestPTy) {
2179     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2180     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2181     DestRecordTy = DestPTy->getPointeeType();
2182   } else {
2183     isDynamicCastToVoid = false;
2184     SrcRecordTy = SrcTy;
2185     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2186   }
2187 
2188   // C++ [class.cdtor]p5:
2189   //   If the operand of the dynamic_cast refers to the object under
2190   //   construction or destruction and the static type of the operand is not a
2191   //   pointer to or object of the constructor or destructor’s own class or one
2192   //   of its bases, the dynamic_cast results in undefined behavior.
2193   EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2194                 SrcRecordTy);
2195 
2196   if (DCE->isAlwaysNull())
2197     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2198       return T;
2199 
2200   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2201 
2202   // C++ [expr.dynamic.cast]p4:
2203   //   If the value of v is a null pointer value in the pointer case, the result
2204   //   is the null pointer value of type T.
2205   bool ShouldNullCheckSrcValue =
2206       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2207                                                          SrcRecordTy);
2208 
2209   llvm::BasicBlock *CastNull = nullptr;
2210   llvm::BasicBlock *CastNotNull = nullptr;
2211   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2212 
2213   if (ShouldNullCheckSrcValue) {
2214     CastNull = createBasicBlock("dynamic_cast.null");
2215     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2216 
2217     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2218     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2219     EmitBlock(CastNotNull);
2220   }
2221 
2222   llvm::Value *Value;
2223   if (isDynamicCastToVoid) {
2224     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2225                                                   DestTy);
2226   } else {
2227     assert(DestRecordTy->isRecordType() &&
2228            "destination type must be a record type!");
2229     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2230                                                 DestTy, DestRecordTy, CastEnd);
2231     CastNotNull = Builder.GetInsertBlock();
2232   }
2233 
2234   if (ShouldNullCheckSrcValue) {
2235     EmitBranch(CastEnd);
2236 
2237     EmitBlock(CastNull);
2238     EmitBranch(CastEnd);
2239   }
2240 
2241   EmitBlock(CastEnd);
2242 
2243   if (ShouldNullCheckSrcValue) {
2244     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2245     PHI->addIncoming(Value, CastNotNull);
2246     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2247 
2248     Value = PHI;
2249   }
2250 
2251   return Value;
2252 }
2253