Debian Codegraph @

clang/lib/CodeGen/CGExprCXX.cpp

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