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