1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This contains code dealing with code generation of C++ expressions
11 //===----------------------------------------------------------------------===//
13 #include "CGCUDARuntime.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"
24 using namespace clang
;
25 using namespace CodeGen
;
28 struct MemberCallInfo
{
30 // Number of prefix arguments for the call. Ignores the `this` pointer.
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());
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!");
48 const CXXRecordDecl
*RD
=
49 CGF
.CGM
.getCXXABI().getThisArgumentTypeForMethod(GD
);
50 Args
.add(RValue::get(This
), CGF
.getTypes().DeriveThisType(RD
, MD
));
52 // If there is an implicit parameter (e.g. VTT), emit it.
54 Args
.add(RValue::get(ImplicitParam
), ImplicitParamTy
);
57 const FunctionProtoType
*FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
58 RequiredArgs required
= RequiredArgs::forPrototypePlus(FPT
, Args
.size());
59 unsigned PrefixSize
= Args
.size() - 1;
61 // And the rest of the call args.
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
);
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()))
73 static_cast<unsigned>(!M
->isExplicitObjectMemberFunction());
75 CGF
.EmitCallArgs(Args
, FPT
, drop_begin(CE
->arguments(), ArgsToSkip
),
76 CE
->getDirectCallee());
79 FPT
->getNumParams() == 0 &&
80 "No CallExpr specified for function with non-zero number of arguments");
82 return {required
, PrefixSize
};
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
>();
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());
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());
107 assert(!ThisTy
.isNull());
108 assert(ThisTy
->getAsCXXRecordDecl() == DtorDecl
->getParent() &&
109 "Pointer/Object mixup");
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
, DstAS
,
121 commonEmitCXXMemberOrOperatorCall(*this, Dtor
, This
, ImplicitParam
,
122 ImplicitParamTy
, CE
, Args
, nullptr);
123 return EmitCall(CGM
.getTypes().arrangeCXXStructorDeclaration(Dtor
), Callee
,
124 ReturnValueSlot(), Args
, CallOrInvoke
,
125 CE
&& CE
== MustTailCall
,
126 CE
? CE
->getExprLoc() : SourceLocation
{});
129 RValue
CodeGenFunction::EmitCXXPseudoDestructorExpr(
130 const CXXPseudoDestructorExpr
*E
) {
131 QualType DestroyedType
= E
->getDestroyedType();
132 if (DestroyedType
.hasStrongOrWeakObjCLifetime()) {
133 // Automatic Reference Counting:
134 // If the pseudo-expression names a retainable object with weak or
135 // strong lifetime, the object shall be released.
136 Expr
*BaseExpr
= E
->getBase();
137 Address BaseValue
= Address::invalid();
138 Qualifiers BaseQuals
;
140 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
142 BaseValue
= EmitPointerWithAlignment(BaseExpr
);
143 const auto *PTy
= BaseExpr
->getType()->castAs
<PointerType
>();
144 BaseQuals
= PTy
->getPointeeType().getQualifiers();
146 LValue BaseLV
= EmitLValue(BaseExpr
);
147 BaseValue
= BaseLV
.getAddress();
148 QualType BaseTy
= BaseExpr
->getType();
149 BaseQuals
= BaseTy
.getQualifiers();
152 switch (DestroyedType
.getObjCLifetime()) {
153 case Qualifiers::OCL_None
:
154 case Qualifiers::OCL_ExplicitNone
:
155 case Qualifiers::OCL_Autoreleasing
:
158 case Qualifiers::OCL_Strong
:
159 EmitARCRelease(Builder
.CreateLoad(BaseValue
,
160 DestroyedType
.isVolatileQualified()),
164 case Qualifiers::OCL_Weak
:
165 EmitARCDestroyWeak(BaseValue
);
169 // C++ [expr.pseudo]p1:
170 // The result shall only be used as the operand for the function call
171 // operator (), and the result of such a call has type void. The only
172 // effect is the evaluation of the postfix-expression before the dot or
174 EmitIgnoredExpr(E
->getBase());
177 return RValue::get(nullptr);
180 static CXXRecordDecl
*getCXXRecord(const Expr
*E
) {
181 QualType T
= E
->getType();
182 if (const PointerType
*PTy
= T
->getAs
<PointerType
>())
183 T
= PTy
->getPointeeType();
184 const RecordType
*Ty
= T
->castAs
<RecordType
>();
185 return cast
<CXXRecordDecl
>(Ty
->getDecl());
188 // Note: This function also emit constructor calls to support a MSVC
189 // extensions allowing explicit constructor function call.
190 RValue
CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr
*CE
,
191 ReturnValueSlot ReturnValue
,
192 llvm::CallBase
**CallOrInvoke
) {
193 const Expr
*callee
= CE
->getCallee()->IgnoreParens();
195 if (isa
<BinaryOperator
>(callee
))
196 return EmitCXXMemberPointerCallExpr(CE
, ReturnValue
, CallOrInvoke
);
198 const MemberExpr
*ME
= cast
<MemberExpr
>(callee
);
199 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(ME
->getMemberDecl());
201 if (MD
->isStatic()) {
202 // The method is static, emit it as we would a regular call.
204 CGCallee::forDirect(CGM
.GetAddrOfFunction(MD
), GlobalDecl(MD
));
205 return EmitCall(getContext().getPointerType(MD
->getType()), callee
, CE
,
206 ReturnValue
, /*Chain=*/nullptr, CallOrInvoke
);
209 bool HasQualifier
= ME
->hasQualifier();
210 NestedNameSpecifier
*Qualifier
= HasQualifier
? ME
->getQualifier() : nullptr;
211 bool IsArrow
= ME
->isArrow();
212 const Expr
*Base
= ME
->getBase();
214 return EmitCXXMemberOrOperatorMemberCallExpr(CE
, MD
, ReturnValue
,
215 HasQualifier
, Qualifier
, IsArrow
,
219 RValue
CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
220 const CallExpr
*CE
, const CXXMethodDecl
*MD
, ReturnValueSlot ReturnValue
,
221 bool HasQualifier
, NestedNameSpecifier
*Qualifier
, bool IsArrow
,
222 const Expr
*Base
, llvm::CallBase
**CallOrInvoke
) {
223 assert(isa
<CXXMemberCallExpr
>(CE
) || isa
<CXXOperatorCallExpr
>(CE
));
225 // Compute the object pointer.
226 bool CanUseVirtualCall
= MD
->isVirtual() && !HasQualifier
;
228 const CXXMethodDecl
*DevirtualizedMethod
= nullptr;
229 if (CanUseVirtualCall
&&
230 MD
->getDevirtualizedMethod(Base
, getLangOpts().AppleKext
)) {
231 const CXXRecordDecl
*BestDynamicDecl
= Base
->getBestDynamicClassType();
232 DevirtualizedMethod
= MD
->getCorrespondingMethodInClass(BestDynamicDecl
);
233 assert(DevirtualizedMethod
);
234 const CXXRecordDecl
*DevirtualizedClass
= DevirtualizedMethod
->getParent();
235 const Expr
*Inner
= Base
->IgnoreParenBaseCasts();
236 if (DevirtualizedMethod
->getReturnType().getCanonicalType() !=
237 MD
->getReturnType().getCanonicalType())
238 // If the return types are not the same, this might be a case where more
239 // code needs to run to compensate for it. For example, the derived
240 // method might return a type that inherits form from the return
241 // type of MD and has a prefix.
242 // For now we just avoid devirtualizing these covariant cases.
243 DevirtualizedMethod
= nullptr;
244 else if (getCXXRecord(Inner
) == DevirtualizedClass
)
245 // If the class of the Inner expression is where the dynamic method
246 // is defined, build the this pointer from it.
248 else if (getCXXRecord(Base
) != DevirtualizedClass
) {
249 // If the method is defined in a class that is not the best dynamic
250 // one or the one of the full expression, we would have to build
251 // a derived-to-base cast to compute the correct this pointer, but
252 // we don't have support for that yet, so do a virtual call.
253 DevirtualizedMethod
= nullptr;
257 bool TrivialForCodegen
=
258 MD
->isTrivial() || (MD
->isDefaulted() && MD
->getParent()->isUnion());
259 bool TrivialAssignment
=
261 (MD
->isCopyAssignmentOperator() || MD
->isMoveAssignmentOperator()) &&
262 !MD
->getParent()->mayInsertExtraPadding();
264 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
265 // operator before the LHS.
266 CallArgList RtlArgStorage
;
267 CallArgList
*RtlArgs
= nullptr;
268 LValue TrivialAssignmentRHS
;
269 if (auto *OCE
= dyn_cast
<CXXOperatorCallExpr
>(CE
)) {
270 if (OCE
->isAssignmentOp()) {
271 if (TrivialAssignment
) {
272 TrivialAssignmentRHS
= EmitLValue(CE
->getArg(1));
274 RtlArgs
= &RtlArgStorage
;
275 EmitCallArgs(*RtlArgs
, MD
->getType()->castAs
<FunctionProtoType
>(),
276 drop_begin(CE
->arguments(), 1), CE
->getDirectCallee(),
277 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft
);
284 LValueBaseInfo BaseInfo
;
285 TBAAAccessInfo TBAAInfo
;
286 Address ThisValue
= EmitPointerWithAlignment(Base
, &BaseInfo
, &TBAAInfo
);
287 This
= MakeAddrLValue(ThisValue
, Base
->getType()->getPointeeType(),
290 This
= EmitLValue(Base
);
293 if (const CXXConstructorDecl
*Ctor
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
294 // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
295 // constructing a new complete object of type Ctor.
297 assert(ReturnValue
.isNull() && "Constructor shouldn't have return value");
299 commonEmitCXXMemberOrOperatorCall(
300 *this, {Ctor
, Ctor_Complete
}, This
.getPointer(*this),
301 /*ImplicitParam=*/nullptr,
302 /*ImplicitParamTy=*/QualType(), CE
, Args
, nullptr);
304 EmitCXXConstructorCall(Ctor
, Ctor_Complete
, /*ForVirtualBase=*/false,
305 /*Delegating=*/false, This
.getAddress(), Args
,
306 AggValueSlot::DoesNotOverlap
, CE
->getExprLoc(),
307 /*NewPointerIsChecked=*/false, CallOrInvoke
);
308 return RValue::get(nullptr);
311 if (TrivialForCodegen
) {
312 if (isa
<CXXDestructorDecl
>(MD
))
313 return RValue::get(nullptr);
315 if (TrivialAssignment
) {
316 // We don't like to generate the trivial copy/move assignment operator
317 // when it isn't necessary; just produce the proper effect here.
318 // It's important that we use the result of EmitLValue here rather than
319 // emitting call arguments, in order to preserve TBAA information from
321 LValue RHS
= isa
<CXXOperatorCallExpr
>(CE
)
322 ? TrivialAssignmentRHS
323 : EmitLValue(*CE
->arg_begin());
324 EmitAggregateAssign(This
, RHS
, CE
->getType());
325 return RValue::get(This
.getPointer(*this));
328 assert(MD
->getParent()->mayInsertExtraPadding() &&
329 "unknown trivial member function");
332 // Compute the function type we're calling.
333 const CXXMethodDecl
*CalleeDecl
=
334 DevirtualizedMethod
? DevirtualizedMethod
: MD
;
335 const CGFunctionInfo
*FInfo
= nullptr;
336 if (const auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(CalleeDecl
))
337 FInfo
= &CGM
.getTypes().arrangeCXXStructorDeclaration(
338 GlobalDecl(Dtor
, Dtor_Complete
));
340 FInfo
= &CGM
.getTypes().arrangeCXXMethodDeclaration(CalleeDecl
);
342 llvm::FunctionType
*Ty
= CGM
.getTypes().GetFunctionType(*FInfo
);
344 // C++11 [class.mfct.non-static]p2:
345 // If a non-static member function of a class X is called for an object that
346 // is not of type X, or of a type derived from X, the behavior is undefined.
347 SourceLocation CallLoc
;
348 ASTContext
&C
= getContext();
350 CallLoc
= CE
->getExprLoc();
352 SanitizerSet SkippedChecks
;
353 if (const auto *CMCE
= dyn_cast
<CXXMemberCallExpr
>(CE
)) {
354 auto *IOA
= CMCE
->getImplicitObjectArgument();
355 bool IsImplicitObjectCXXThis
= IsWrappedCXXThis(IOA
);
356 if (IsImplicitObjectCXXThis
)
357 SkippedChecks
.set(SanitizerKind::Alignment
, true);
358 if (IsImplicitObjectCXXThis
|| isa
<DeclRefExpr
>(IOA
))
359 SkippedChecks
.set(SanitizerKind::Null
, true);
362 if (sanitizePerformTypeCheck())
363 EmitTypeCheck(CodeGenFunction::TCK_MemberCall
, CallLoc
,
364 This
.emitRawPointer(*this),
365 C
.getRecordType(CalleeDecl
->getParent()),
366 /*Alignment=*/CharUnits::Zero(), SkippedChecks
);
368 // C++ [class.virtual]p12:
369 // Explicit qualification with the scope operator (5.1) suppresses the
370 // virtual call mechanism.
372 // We also don't emit a virtual call if the base expression has a record type
373 // because then we know what the type is.
374 bool UseVirtualCall
= CanUseVirtualCall
&& !DevirtualizedMethod
;
376 if (const CXXDestructorDecl
*Dtor
= dyn_cast
<CXXDestructorDecl
>(CalleeDecl
)) {
377 assert(CE
->arg_begin() == CE
->arg_end() &&
378 "Destructor shouldn't have explicit parameters");
379 assert(ReturnValue
.isNull() && "Destructor shouldn't have return value");
380 if (UseVirtualCall
) {
381 CGM
.getCXXABI().EmitVirtualDestructorCall(
382 *this, Dtor
, Dtor_Complete
, This
.getAddress(),
383 cast
<CXXMemberCallExpr
>(CE
), CallOrInvoke
);
385 GlobalDecl
GD(Dtor
, Dtor_Complete
);
387 if (getLangOpts().AppleKext
&& Dtor
->isVirtual() && HasQualifier
)
388 Callee
= BuildAppleKextVirtualCall(Dtor
, Qualifier
, Ty
);
389 else if (!DevirtualizedMethod
)
391 CGCallee::forDirect(CGM
.getAddrOfCXXStructor(GD
, FInfo
, Ty
), GD
);
393 Callee
= CGCallee::forDirect(CGM
.GetAddrOfFunction(GD
, Ty
), GD
);
397 IsArrow
? Base
->getType()->getPointeeType() : Base
->getType();
398 EmitCXXDestructorCall(GD
, Callee
, This
.getPointer(*this), ThisTy
,
399 /*ImplicitParam=*/nullptr,
400 /*ImplicitParamTy=*/QualType(), CE
, CallOrInvoke
);
402 return RValue::get(nullptr);
405 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
406 // 'CalleeDecl' instead.
409 if (UseVirtualCall
) {
410 Callee
= CGCallee::forVirtual(CE
, MD
, This
.getAddress(), Ty
);
412 if (SanOpts
.has(SanitizerKind::CFINVCall
) &&
413 MD
->getParent()->isDynamicClass()) {
415 const CXXRecordDecl
*RD
;
416 std::tie(VTable
, RD
) = CGM
.getCXXABI().LoadVTablePtr(
417 *this, This
.getAddress(), CalleeDecl
->getParent());
418 EmitVTablePtrCheckForCall(RD
, VTable
, CFITCK_NVCall
, CE
->getBeginLoc());
421 if (getLangOpts().AppleKext
&& MD
->isVirtual() && HasQualifier
)
422 Callee
= BuildAppleKextVirtualCall(MD
, Qualifier
, Ty
);
423 else if (!DevirtualizedMethod
)
425 CGCallee::forDirect(CGM
.GetAddrOfFunction(MD
, Ty
), GlobalDecl(MD
));
428 CGCallee::forDirect(CGM
.GetAddrOfFunction(DevirtualizedMethod
, Ty
),
429 GlobalDecl(DevirtualizedMethod
));
433 if (MD
->isVirtual()) {
434 Address NewThisAddr
=
435 CGM
.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
436 *this, CalleeDecl
, This
.getAddress(), UseVirtualCall
);
437 This
.setAddress(NewThisAddr
);
440 return EmitCXXMemberOrOperatorCall(
441 CalleeDecl
, Callee
, ReturnValue
, This
.getPointer(*this),
442 /*ImplicitParam=*/nullptr, QualType(), CE
, RtlArgs
, CallOrInvoke
);
446 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr
*E
,
447 ReturnValueSlot ReturnValue
,
448 llvm::CallBase
**CallOrInvoke
) {
449 const BinaryOperator
*BO
=
450 cast
<BinaryOperator
>(E
->getCallee()->IgnoreParens());
451 const Expr
*BaseExpr
= BO
->getLHS();
452 const Expr
*MemFnExpr
= BO
->getRHS();
454 const auto *MPT
= MemFnExpr
->getType()->castAs
<MemberPointerType
>();
455 const auto *FPT
= MPT
->getPointeeType()->castAs
<FunctionProtoType
>();
457 cast
<CXXRecordDecl
>(MPT
->getClass()->castAs
<RecordType
>()->getDecl());
459 // Emit the 'this' pointer.
460 Address This
= Address::invalid();
461 if (BO
->getOpcode() == BO_PtrMemI
)
462 This
= EmitPointerWithAlignment(BaseExpr
, nullptr, nullptr, KnownNonNull
);
464 This
= EmitLValue(BaseExpr
, KnownNonNull
).getAddress();
466 EmitTypeCheck(TCK_MemberCall
, E
->getExprLoc(), This
.emitRawPointer(*this),
467 QualType(MPT
->getClass(), 0));
469 // Get the member function pointer.
470 llvm::Value
*MemFnPtr
= EmitScalarExpr(MemFnExpr
);
472 // Ask the ABI to load the callee. Note that This is modified.
473 llvm::Value
*ThisPtrForCall
= nullptr;
475 CGM
.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO
, This
,
476 ThisPtrForCall
, MemFnPtr
, MPT
);
481 getContext().getPointerType(getContext().getTagDeclType(RD
));
483 // Push the this ptr.
484 Args
.add(RValue::get(ThisPtrForCall
), ThisType
);
486 RequiredArgs required
= RequiredArgs::forPrototypePlus(FPT
, 1);
488 // And the rest of the call args
489 EmitCallArgs(Args
, FPT
, E
->arguments());
490 return EmitCall(CGM
.getTypes().arrangeCXXMethodCall(Args
, FPT
, required
,
492 Callee
, ReturnValue
, Args
, CallOrInvoke
, E
== MustTailCall
,
496 RValue
CodeGenFunction::EmitCXXOperatorMemberCallExpr(
497 const CXXOperatorCallExpr
*E
, const CXXMethodDecl
*MD
,
498 ReturnValueSlot ReturnValue
, llvm::CallBase
**CallOrInvoke
) {
499 assert(MD
->isImplicitObjectMemberFunction() &&
500 "Trying to emit a member call expr on a static method!");
501 return EmitCXXMemberOrOperatorMemberCallExpr(
502 E
, MD
, ReturnValue
, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
503 /*IsArrow=*/false, E
->getArg(0), CallOrInvoke
);
506 RValue
CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr
*E
,
507 ReturnValueSlot ReturnValue
,
508 llvm::CallBase
**CallOrInvoke
) {
509 return CGM
.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E
, ReturnValue
,
513 static void EmitNullBaseClassInitialization(CodeGenFunction
&CGF
,
515 const CXXRecordDecl
*Base
) {
519 DestPtr
= DestPtr
.withElementType(CGF
.Int8Ty
);
521 const ASTRecordLayout
&Layout
= CGF
.getContext().getASTRecordLayout(Base
);
522 CharUnits NVSize
= Layout
.getNonVirtualSize();
524 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
525 // present, they are initialized by the most derived class before calling the
527 SmallVector
<std::pair
<CharUnits
, CharUnits
>, 1> Stores
;
528 Stores
.emplace_back(CharUnits::Zero(), NVSize
);
530 // Each store is split by the existence of a vbptr.
531 CharUnits VBPtrWidth
= CGF
.getPointerSize();
532 std::vector
<CharUnits
> VBPtrOffsets
=
533 CGF
.CGM
.getCXXABI().getVBPtrOffsets(Base
);
534 for (CharUnits VBPtrOffset
: VBPtrOffsets
) {
535 // Stop before we hit any virtual base pointers located in virtual bases.
536 if (VBPtrOffset
>= NVSize
)
538 std::pair
<CharUnits
, CharUnits
> LastStore
= Stores
.pop_back_val();
539 CharUnits LastStoreOffset
= LastStore
.first
;
540 CharUnits LastStoreSize
= LastStore
.second
;
542 CharUnits SplitBeforeOffset
= LastStoreOffset
;
543 CharUnits SplitBeforeSize
= VBPtrOffset
- SplitBeforeOffset
;
544 assert(!SplitBeforeSize
.isNegative() && "negative store size!");
545 if (!SplitBeforeSize
.isZero())
546 Stores
.emplace_back(SplitBeforeOffset
, SplitBeforeSize
);
548 CharUnits SplitAfterOffset
= VBPtrOffset
+ VBPtrWidth
;
549 CharUnits SplitAfterSize
= LastStoreSize
- SplitAfterOffset
;
550 assert(!SplitAfterSize
.isNegative() && "negative store size!");
551 if (!SplitAfterSize
.isZero())
552 Stores
.emplace_back(SplitAfterOffset
, SplitAfterSize
);
555 // If the type contains a pointer to data member we can't memset it to zero.
556 // Instead, create a null constant and copy it to the destination.
557 // TODO: there are other patterns besides zero that we can usefully memset,
558 // like -1, which happens to be the pattern used by member-pointers.
559 // TODO: isZeroInitializable can be over-conservative in the case where a
560 // virtual base contains a member pointer.
561 llvm::Constant
*NullConstantForBase
= CGF
.CGM
.EmitNullConstantForBase(Base
);
562 if (!NullConstantForBase
->isNullValue()) {
563 llvm::GlobalVariable
*NullVariable
= new llvm::GlobalVariable(
564 CGF
.CGM
.getModule(), NullConstantForBase
->getType(),
565 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage
,
566 NullConstantForBase
, Twine());
569 std::max(Layout
.getNonVirtualAlignment(), DestPtr
.getAlignment());
570 NullVariable
->setAlignment(Align
.getAsAlign());
572 Address
SrcPtr(NullVariable
, CGF
.Int8Ty
, Align
);
574 // Get and call the appropriate llvm.memcpy overload.
575 for (std::pair
<CharUnits
, CharUnits
> Store
: Stores
) {
576 CharUnits StoreOffset
= Store
.first
;
577 CharUnits StoreSize
= Store
.second
;
578 llvm::Value
*StoreSizeVal
= CGF
.CGM
.getSize(StoreSize
);
579 CGF
.Builder
.CreateMemCpy(
580 CGF
.Builder
.CreateConstInBoundsByteGEP(DestPtr
, StoreOffset
),
581 CGF
.Builder
.CreateConstInBoundsByteGEP(SrcPtr
, StoreOffset
),
585 // Otherwise, just memset the whole thing to zero. This is legal
586 // because in LLVM, all default initializers (other than the ones we just
587 // handled above) are guaranteed to have a bit pattern of all zeros.
589 for (std::pair
<CharUnits
, CharUnits
> Store
: Stores
) {
590 CharUnits StoreOffset
= Store
.first
;
591 CharUnits StoreSize
= Store
.second
;
592 llvm::Value
*StoreSizeVal
= CGF
.CGM
.getSize(StoreSize
);
593 CGF
.Builder
.CreateMemSet(
594 CGF
.Builder
.CreateConstInBoundsByteGEP(DestPtr
, StoreOffset
),
595 CGF
.Builder
.getInt8(0), StoreSizeVal
);
601 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr
*E
,
603 assert(!Dest
.isIgnored() && "Must have a destination!");
604 const CXXConstructorDecl
*CD
= E
->getConstructor();
606 // If we require zero initialization before (or instead of) calling the
607 // constructor, as can be the case with a non-user-provided default
608 // constructor, emit the zero initialization now, unless destination is
610 if (E
->requiresZeroInitialization() && !Dest
.isZeroed()) {
611 switch (E
->getConstructionKind()) {
612 case CXXConstructionKind::Delegating
:
613 case CXXConstructionKind::Complete
:
614 EmitNullInitialization(Dest
.getAddress(), E
->getType());
616 case CXXConstructionKind::VirtualBase
:
617 case CXXConstructionKind::NonVirtualBase
:
618 EmitNullBaseClassInitialization(*this, Dest
.getAddress(),
624 // If this is a call to a trivial default constructor, do nothing.
625 if (CD
->isTrivial() && CD
->isDefaultConstructor())
628 // Elide the constructor if we're constructing from a temporary.
629 if (getLangOpts().ElideConstructors
&& E
->isElidable()) {
630 // FIXME: This only handles the simplest case, where the source object
631 // is passed directly as the first argument to the constructor.
632 // This should also handle stepping though implicit casts and
633 // conversion sequences which involve two steps, with a
634 // conversion operator followed by a converting constructor.
635 const Expr
*SrcObj
= E
->getArg(0);
636 assert(SrcObj
->isTemporaryObject(getContext(), CD
->getParent()));
638 getContext().hasSameUnqualifiedType(E
->getType(), SrcObj
->getType()));
639 EmitAggExpr(SrcObj
, Dest
);
643 if (const ArrayType
*arrayType
644 = getContext().getAsArrayType(E
->getType())) {
645 EmitCXXAggrConstructorCall(CD
, arrayType
, Dest
.getAddress(), E
,
646 Dest
.isSanitizerChecked());
648 CXXCtorType Type
= Ctor_Complete
;
649 bool ForVirtualBase
= false;
650 bool Delegating
= false;
652 switch (E
->getConstructionKind()) {
653 case CXXConstructionKind::Delegating
:
654 // We should be emitting a constructor; GlobalDecl will assert this
655 Type
= CurGD
.getCtorType();
659 case CXXConstructionKind::Complete
:
660 Type
= Ctor_Complete
;
663 case CXXConstructionKind::VirtualBase
:
664 ForVirtualBase
= true;
667 case CXXConstructionKind::NonVirtualBase
:
671 // Call the constructor.
672 EmitCXXConstructorCall(CD
, Type
, ForVirtualBase
, Delegating
, Dest
, E
);
676 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest
, Address Src
,
678 if (const ExprWithCleanups
*E
= dyn_cast
<ExprWithCleanups
>(Exp
))
679 Exp
= E
->getSubExpr();
680 assert(isa
<CXXConstructExpr
>(Exp
) &&
681 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
682 const CXXConstructExpr
* E
= cast
<CXXConstructExpr
>(Exp
);
683 const CXXConstructorDecl
*CD
= E
->getConstructor();
684 RunCleanupsScope
Scope(*this);
686 // If we require zero initialization before (or instead of) calling the
687 // constructor, as can be the case with a non-user-provided default
688 // constructor, emit the zero initialization now.
689 // FIXME. Do I still need this for a copy ctor synthesis?
690 if (E
->requiresZeroInitialization())
691 EmitNullInitialization(Dest
, E
->getType());
693 assert(!getContext().getAsConstantArrayType(E
->getType())
694 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
695 EmitSynthesizedCXXCopyCtorCall(CD
, Dest
, Src
, E
);
698 static CharUnits
CalculateCookiePadding(CodeGenFunction
&CGF
,
699 const CXXNewExpr
*E
) {
701 return CharUnits::Zero();
703 // No cookie is required if the operator new[] being used is the
704 // reserved placement operator new[].
705 if (E
->getOperatorNew()->isReservedGlobalPlacementOperator())
706 return CharUnits::Zero();
708 return CGF
.CGM
.getCXXABI().GetArrayCookieSize(E
);
711 static llvm::Value
*EmitCXXNewAllocSize(CodeGenFunction
&CGF
,
713 unsigned minElements
,
714 llvm::Value
*&numElements
,
715 llvm::Value
*&sizeWithoutCookie
) {
716 QualType type
= e
->getAllocatedType();
719 CharUnits typeSize
= CGF
.getContext().getTypeSizeInChars(type
);
721 = llvm::ConstantInt::get(CGF
.SizeTy
, typeSize
.getQuantity());
722 return sizeWithoutCookie
;
725 // The width of size_t.
726 unsigned sizeWidth
= CGF
.SizeTy
->getBitWidth();
728 // Figure out the cookie size.
729 llvm::APInt
cookieSize(sizeWidth
,
730 CalculateCookiePadding(CGF
, e
).getQuantity());
732 // Emit the array size expression.
733 // We multiply the size of all dimensions for NumElements.
734 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
736 ConstantEmitter(CGF
).tryEmitAbstract(*e
->getArraySize(), e
->getType());
738 numElements
= CGF
.EmitScalarExpr(*e
->getArraySize());
739 assert(isa
<llvm::IntegerType
>(numElements
->getType()));
741 // The number of elements can be have an arbitrary integer type;
742 // essentially, we need to multiply it by a constant factor, add a
743 // cookie size, and verify that the result is representable as a
744 // size_t. That's just a gloss, though, and it's wrong in one
745 // important way: if the count is negative, it's an error even if
746 // the cookie size would bring the total size >= 0.
748 = (*e
->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
749 llvm::IntegerType
*numElementsType
750 = cast
<llvm::IntegerType
>(numElements
->getType());
751 unsigned numElementsWidth
= numElementsType
->getBitWidth();
753 // Compute the constant factor.
754 llvm::APInt
arraySizeMultiplier(sizeWidth
, 1);
755 while (const ConstantArrayType
*CAT
756 = CGF
.getContext().getAsConstantArrayType(type
)) {
757 type
= CAT
->getElementType();
758 arraySizeMultiplier
*= CAT
->getSize();
761 CharUnits typeSize
= CGF
.getContext().getTypeSizeInChars(type
);
762 llvm::APInt
typeSizeMultiplier(sizeWidth
, typeSize
.getQuantity());
763 typeSizeMultiplier
*= arraySizeMultiplier
;
765 // This will be a size_t.
768 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
769 // Don't bloat the -O0 code.
770 if (llvm::ConstantInt
*numElementsC
=
771 dyn_cast
<llvm::ConstantInt
>(numElements
)) {
772 const llvm::APInt
&count
= numElementsC
->getValue();
774 bool hasAnyOverflow
= false;
776 // If 'count' was a negative number, it's an overflow.
777 if (isSigned
&& count
.isNegative())
778 hasAnyOverflow
= true;
780 // We want to do all this arithmetic in size_t. If numElements is
781 // wider than that, check whether it's already too big, and if so,
783 else if (numElementsWidth
> sizeWidth
&&
784 numElementsWidth
- sizeWidth
> count
.countl_zero())
785 hasAnyOverflow
= true;
787 // Okay, compute a count at the right width.
788 llvm::APInt adjustedCount
= count
.zextOrTrunc(sizeWidth
);
790 // If there is a brace-initializer, we cannot allocate fewer elements than
791 // there are initializers. If we do, that's treated like an overflow.
792 if (adjustedCount
.ult(minElements
))
793 hasAnyOverflow
= true;
795 // Scale numElements by that. This might overflow, but we don't
796 // care because it only overflows if allocationSize does, too, and
797 // if that overflows then we shouldn't use this.
798 numElements
= llvm::ConstantInt::get(CGF
.SizeTy
,
799 adjustedCount
* arraySizeMultiplier
);
801 // Compute the size before cookie, and track whether it overflowed.
803 llvm::APInt allocationSize
804 = adjustedCount
.umul_ov(typeSizeMultiplier
, overflow
);
805 hasAnyOverflow
|= overflow
;
807 // Add in the cookie, and check whether it's overflowed.
808 if (cookieSize
!= 0) {
809 // Save the current size without a cookie. This shouldn't be
810 // used if there was overflow.
811 sizeWithoutCookie
= llvm::ConstantInt::get(CGF
.SizeTy
, allocationSize
);
813 allocationSize
= allocationSize
.uadd_ov(cookieSize
, overflow
);
814 hasAnyOverflow
|= overflow
;
817 // On overflow, produce a -1 so operator new will fail.
818 if (hasAnyOverflow
) {
819 size
= llvm::Constant::getAllOnesValue(CGF
.SizeTy
);
821 size
= llvm::ConstantInt::get(CGF
.SizeTy
, allocationSize
);
824 // Otherwise, we might need to use the overflow intrinsics.
826 // There are up to five conditions we need to test for:
827 // 1) if isSigned, we need to check whether numElements is negative;
828 // 2) if numElementsWidth > sizeWidth, we need to check whether
829 // numElements is larger than something representable in size_t;
830 // 3) if minElements > 0, we need to check whether numElements is smaller
832 // 4) we need to compute
833 // sizeWithoutCookie := numElements * typeSizeMultiplier
834 // and check whether it overflows; and
835 // 5) if we need a cookie, we need to compute
836 // size := sizeWithoutCookie + cookieSize
837 // and check whether it overflows.
839 llvm::Value
*hasOverflow
= nullptr;
841 // If numElementsWidth > sizeWidth, then one way or another, we're
842 // going to have to do a comparison for (2), and this happens to
843 // take care of (1), too.
844 if (numElementsWidth
> sizeWidth
) {
845 llvm::APInt threshold
=
846 llvm::APInt::getOneBitSet(numElementsWidth
, sizeWidth
);
848 llvm::Value
*thresholdV
849 = llvm::ConstantInt::get(numElementsType
, threshold
);
851 hasOverflow
= CGF
.Builder
.CreateICmpUGE(numElements
, thresholdV
);
852 numElements
= CGF
.Builder
.CreateTrunc(numElements
, CGF
.SizeTy
);
854 // Otherwise, if we're signed, we want to sext up to size_t.
855 } else if (isSigned
) {
856 if (numElementsWidth
< sizeWidth
)
857 numElements
= CGF
.Builder
.CreateSExt(numElements
, CGF
.SizeTy
);
859 // If there's a non-1 type size multiplier, then we can do the
860 // signedness check at the same time as we do the multiply
861 // because a negative number times anything will cause an
862 // unsigned overflow. Otherwise, we have to do it here. But at least
863 // in this case, we can subsume the >= minElements check.
864 if (typeSizeMultiplier
== 1)
865 hasOverflow
= CGF
.Builder
.CreateICmpSLT(numElements
,
866 llvm::ConstantInt::get(CGF
.SizeTy
, minElements
));
868 // Otherwise, zext up to size_t if necessary.
869 } else if (numElementsWidth
< sizeWidth
) {
870 numElements
= CGF
.Builder
.CreateZExt(numElements
, CGF
.SizeTy
);
873 assert(numElements
->getType() == CGF
.SizeTy
);
876 // Don't allow allocation of fewer elements than we have initializers.
878 hasOverflow
= CGF
.Builder
.CreateICmpULT(numElements
,
879 llvm::ConstantInt::get(CGF
.SizeTy
, minElements
));
880 } else if (numElementsWidth
> sizeWidth
) {
881 // The other existing overflow subsumes this check.
882 // We do an unsigned comparison, since any signed value < -1 is
883 // taken care of either above or below.
884 hasOverflow
= CGF
.Builder
.CreateOr(hasOverflow
,
885 CGF
.Builder
.CreateICmpULT(numElements
,
886 llvm::ConstantInt::get(CGF
.SizeTy
, minElements
)));
892 // Multiply by the type size if necessary. This multiplier
893 // includes all the factors for nested arrays.
895 // This step also causes numElements to be scaled up by the
896 // nested-array factor if necessary. Overflow on this computation
897 // can be ignored because the result shouldn't be used if
899 if (typeSizeMultiplier
!= 1) {
900 llvm::Function
*umul_with_overflow
901 = CGF
.CGM
.getIntrinsic(llvm::Intrinsic::umul_with_overflow
, CGF
.SizeTy
);
904 llvm::ConstantInt::get(CGF
.SizeTy
, typeSizeMultiplier
);
905 llvm::Value
*result
=
906 CGF
.Builder
.CreateCall(umul_with_overflow
, {size
, tsmV
});
908 llvm::Value
*overflowed
= CGF
.Builder
.CreateExtractValue(result
, 1);
910 hasOverflow
= CGF
.Builder
.CreateOr(hasOverflow
, overflowed
);
912 hasOverflow
= overflowed
;
914 size
= CGF
.Builder
.CreateExtractValue(result
, 0);
916 // Also scale up numElements by the array size multiplier.
917 if (arraySizeMultiplier
!= 1) {
918 // If the base element type size is 1, then we can re-use the
919 // multiply we just did.
920 if (typeSize
.isOne()) {
921 assert(arraySizeMultiplier
== typeSizeMultiplier
);
924 // Otherwise we need a separate multiply.
927 llvm::ConstantInt::get(CGF
.SizeTy
, arraySizeMultiplier
);
928 numElements
= CGF
.Builder
.CreateMul(numElements
, asmV
);
932 // numElements doesn't need to be scaled.
933 assert(arraySizeMultiplier
== 1);
936 // Add in the cookie size if necessary.
937 if (cookieSize
!= 0) {
938 sizeWithoutCookie
= size
;
940 llvm::Function
*uadd_with_overflow
941 = CGF
.CGM
.getIntrinsic(llvm::Intrinsic::uadd_with_overflow
, CGF
.SizeTy
);
943 llvm::Value
*cookieSizeV
= llvm::ConstantInt::get(CGF
.SizeTy
, cookieSize
);
944 llvm::Value
*result
=
945 CGF
.Builder
.CreateCall(uadd_with_overflow
, {size
, cookieSizeV
});
947 llvm::Value
*overflowed
= CGF
.Builder
.CreateExtractValue(result
, 1);
949 hasOverflow
= CGF
.Builder
.CreateOr(hasOverflow
, overflowed
);
951 hasOverflow
= overflowed
;
953 size
= CGF
.Builder
.CreateExtractValue(result
, 0);
956 // If we had any possibility of dynamic overflow, make a select to
957 // overwrite 'size' with an all-ones value, which should cause
958 // operator new to throw.
960 size
= CGF
.Builder
.CreateSelect(hasOverflow
,
961 llvm::Constant::getAllOnesValue(CGF
.SizeTy
),
966 sizeWithoutCookie
= size
;
968 assert(sizeWithoutCookie
&& "didn't set sizeWithoutCookie?");
973 static void StoreAnyExprIntoOneUnit(CodeGenFunction
&CGF
, const Expr
*Init
,
974 QualType AllocType
, Address NewPtr
,
975 AggValueSlot::Overlap_t MayOverlap
) {
976 // FIXME: Refactor with EmitExprAsInit.
977 switch (CGF
.getEvaluationKind(AllocType
)) {
979 CGF
.EmitScalarInit(Init
, nullptr,
980 CGF
.MakeAddrLValue(NewPtr
, AllocType
), false);
983 CGF
.EmitComplexExprIntoLValue(Init
, CGF
.MakeAddrLValue(NewPtr
, AllocType
),
986 case TEK_Aggregate
: {
988 = AggValueSlot::forAddr(NewPtr
, AllocType
.getQualifiers(),
989 AggValueSlot::IsDestructed
,
990 AggValueSlot::DoesNotNeedGCBarriers
,
991 AggValueSlot::IsNotAliased
,
992 MayOverlap
, AggValueSlot::IsNotZeroed
,
993 AggValueSlot::IsSanitizerChecked
);
994 CGF
.EmitAggExpr(Init
, Slot
);
998 llvm_unreachable("bad evaluation kind");
1001 void CodeGenFunction::EmitNewArrayInitializer(
1002 const CXXNewExpr
*E
, QualType ElementType
, llvm::Type
*ElementTy
,
1003 Address BeginPtr
, llvm::Value
*NumElements
,
1004 llvm::Value
*AllocSizeWithoutCookie
) {
1005 // If we have a type with trivial initialization and no initializer,
1006 // there's nothing to do.
1007 if (!E
->hasInitializer())
1010 Address CurPtr
= BeginPtr
;
1012 unsigned InitListElements
= 0;
1014 const Expr
*Init
= E
->getInitializer();
1015 Address EndOfInit
= Address::invalid();
1016 QualType::DestructionKind DtorKind
= ElementType
.isDestructedType();
1017 CleanupDeactivationScope
deactivation(*this);
1018 bool pushedCleanup
= false;
1020 CharUnits ElementSize
= getContext().getTypeSizeInChars(ElementType
);
1021 CharUnits ElementAlign
=
1022 BeginPtr
.getAlignment().alignmentOfArrayElement(ElementSize
);
1024 // Attempt to perform zero-initialization using memset.
1025 auto TryMemsetInitialization
= [&]() -> bool {
1026 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1027 // we can initialize with a memset to -1.
1028 if (!CGM
.getTypes().isZeroInitializable(ElementType
))
1031 // Optimization: since zero initialization will just set the memory
1032 // to all zeroes, generate a single memset to do it in one shot.
1034 // Subtract out the size of any elements we've already initialized.
1035 auto *RemainingSize
= AllocSizeWithoutCookie
;
1036 if (InitListElements
) {
1037 // We know this can't overflow; we check this when doing the allocation.
1038 auto *InitializedSize
= llvm::ConstantInt::get(
1039 RemainingSize
->getType(),
1040 getContext().getTypeSizeInChars(ElementType
).getQuantity() *
1042 RemainingSize
= Builder
.CreateSub(RemainingSize
, InitializedSize
);
1045 // Create the memset.
1046 Builder
.CreateMemSet(CurPtr
, Builder
.getInt8(0), RemainingSize
, false);
1050 const InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(Init
);
1051 const CXXParenListInitExpr
*CPLIE
= nullptr;
1052 const StringLiteral
*SL
= nullptr;
1053 const ObjCEncodeExpr
*OCEE
= nullptr;
1054 const Expr
*IgnoreParen
= nullptr;
1056 IgnoreParen
= Init
->IgnoreParenImpCasts();
1057 CPLIE
= dyn_cast
<CXXParenListInitExpr
>(IgnoreParen
);
1058 SL
= dyn_cast
<StringLiteral
>(IgnoreParen
);
1059 OCEE
= dyn_cast
<ObjCEncodeExpr
>(IgnoreParen
);
1062 // If the initializer is an initializer list, first do the explicit elements.
1063 if (ILE
|| CPLIE
|| SL
|| OCEE
) {
1064 // Initializing from a (braced) string literal is a special case; the init
1065 // list element does not initialize a (single) array element.
1066 if ((ILE
&& ILE
->isStringLiteralInit()) || SL
|| OCEE
) {
1069 // Initialize the initial portion of length equal to that of the string
1070 // literal. The allocation must be for at least this much; we emitted a
1071 // check for that earlier.
1073 AggValueSlot::forAddr(CurPtr
, ElementType
.getQualifiers(),
1074 AggValueSlot::IsDestructed
,
1075 AggValueSlot::DoesNotNeedGCBarriers
,
1076 AggValueSlot::IsNotAliased
,
1077 AggValueSlot::DoesNotOverlap
,
1078 AggValueSlot::IsNotZeroed
,
1079 AggValueSlot::IsSanitizerChecked
);
1080 EmitAggExpr(ILE
? ILE
->getInit(0) : Init
, Slot
);
1082 // Move past these elements.
1084 cast
<ConstantArrayType
>(Init
->getType()->getAsArrayTypeUnsafe())
1086 CurPtr
= Builder
.CreateConstInBoundsGEP(
1087 CurPtr
, InitListElements
, "string.init.end");
1089 // Zero out the rest, if any remain.
1090 llvm::ConstantInt
*ConstNum
= dyn_cast
<llvm::ConstantInt
>(NumElements
);
1091 if (!ConstNum
|| !ConstNum
->equalsInt(InitListElements
)) {
1092 bool OK
= TryMemsetInitialization();
1094 assert(OK
&& "couldn't memset character type?");
1099 ArrayRef
<const Expr
*> InitExprs
=
1100 ILE
? ILE
->inits() : CPLIE
->getInitExprs();
1101 InitListElements
= InitExprs
.size();
1103 // If this is a multi-dimensional array new, we will initialize multiple
1104 // elements with each init list element.
1105 QualType AllocType
= E
->getAllocatedType();
1106 if (const ConstantArrayType
*CAT
= dyn_cast_or_null
<ConstantArrayType
>(
1107 AllocType
->getAsArrayTypeUnsafe())) {
1108 ElementTy
= ConvertTypeForMem(AllocType
);
1109 CurPtr
= CurPtr
.withElementType(ElementTy
);
1110 InitListElements
*= getContext().getConstantArrayElementCount(CAT
);
1113 // Enter a partial-destruction Cleanup if necessary.
1115 AllocaTrackerRAII
AllocaTracker(*this);
1116 // In principle we could tell the Cleanup where we are more
1117 // directly, but the control flow can get so varied here that it
1118 // would actually be quite complex. Therefore we go through an
1120 llvm::Instruction
*DominatingIP
=
1121 Builder
.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy
));
1122 EndOfInit
= CreateTempAlloca(BeginPtr
.getType(), getPointerAlign(),
1124 pushIrregularPartialArrayCleanup(BeginPtr
.emitRawPointer(*this),
1125 EndOfInit
, ElementType
, ElementAlign
,
1126 getDestroyer(DtorKind
));
1127 cast
<EHCleanupScope
>(*EHStack
.find(EHStack
.stable_begin()))
1128 .AddAuxAllocas(AllocaTracker
.Take());
1129 DeferredDeactivationCleanupStack
.push_back(
1130 {EHStack
.stable_begin(), DominatingIP
});
1131 pushedCleanup
= true;
1134 CharUnits StartAlign
= CurPtr
.getAlignment();
1136 for (const Expr
*IE
: InitExprs
) {
1137 // Tell the cleanup that it needs to destroy up to this
1138 // element. TODO: some of these stores can be trivially
1139 // observed to be unnecessary.
1140 if (EndOfInit
.isValid()) {
1141 Builder
.CreateStore(CurPtr
.emitRawPointer(*this), EndOfInit
);
1143 // FIXME: If the last initializer is an incomplete initializer list for
1144 // an array, and we have an array filler, we can fold together the two
1145 // initialization loops.
1146 StoreAnyExprIntoOneUnit(*this, IE
, IE
->getType(), CurPtr
,
1147 AggValueSlot::DoesNotOverlap
);
1148 CurPtr
= Address(Builder
.CreateInBoundsGEP(CurPtr
.getElementType(),
1149 CurPtr
.emitRawPointer(*this),
1152 CurPtr
.getElementType(),
1153 StartAlign
.alignmentAtOffset((++i
) * ElementSize
));
1156 // The remaining elements are filled with the array filler expression.
1157 Init
= ILE
? ILE
->getArrayFiller() : CPLIE
->getArrayFiller();
1159 // Extract the initializer for the individual array elements by pulling
1160 // out the array filler from all the nested initializer lists. This avoids
1161 // generating a nested loop for the initialization.
1162 while (Init
&& Init
->getType()->isConstantArrayType()) {
1163 auto *SubILE
= dyn_cast
<InitListExpr
>(Init
);
1166 assert(SubILE
->getNumInits() == 0 && "explicit inits in array filler?");
1167 Init
= SubILE
->getArrayFiller();
1170 // Switch back to initializing one base element at a time.
1171 CurPtr
= CurPtr
.withElementType(BeginPtr
.getElementType());
1174 // If all elements have already been initialized, skip any further
1176 llvm::ConstantInt
*ConstNum
= dyn_cast
<llvm::ConstantInt
>(NumElements
);
1177 if (ConstNum
&& ConstNum
->getZExtValue() <= InitListElements
) {
1181 assert(Init
&& "have trailing elements to initialize but no initializer");
1183 // If this is a constructor call, try to optimize it out, and failing that
1184 // emit a single loop to initialize all remaining elements.
1185 if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(Init
)) {
1186 CXXConstructorDecl
*Ctor
= CCE
->getConstructor();
1187 if (Ctor
->isTrivial()) {
1188 // If new expression did not specify value-initialization, then there
1189 // is no initialization.
1190 if (!CCE
->requiresZeroInitialization() || Ctor
->getParent()->isEmpty())
1193 if (TryMemsetInitialization())
1197 // Store the new Cleanup position for irregular Cleanups.
1199 // FIXME: Share this cleanup with the constructor call emission rather than
1200 // having it create a cleanup of its own.
1201 if (EndOfInit
.isValid())
1202 Builder
.CreateStore(CurPtr
.emitRawPointer(*this), EndOfInit
);
1204 // Emit a constructor call loop to initialize the remaining elements.
1205 if (InitListElements
)
1206 NumElements
= Builder
.CreateSub(
1208 llvm::ConstantInt::get(NumElements
->getType(), InitListElements
));
1209 EmitCXXAggrConstructorCall(Ctor
, NumElements
, CurPtr
, CCE
,
1210 /*NewPointerIsChecked*/true,
1211 CCE
->requiresZeroInitialization());
1215 // If this is value-initialization, we can usually use memset.
1216 ImplicitValueInitExpr
IVIE(ElementType
);
1217 if (isa
<ImplicitValueInitExpr
>(Init
)) {
1218 if (TryMemsetInitialization())
1221 // Switch to an ImplicitValueInitExpr for the element type. This handles
1222 // only one case: multidimensional array new of pointers to members. In
1223 // all other cases, we already have an initializer for the array element.
1227 // At this point we should have found an initializer for the individual
1228 // elements of the array.
1229 assert(getContext().hasSameUnqualifiedType(ElementType
, Init
->getType()) &&
1230 "got wrong type of element to initialize");
1232 // If we have an empty initializer list, we can usually use memset.
1233 if (auto *ILE
= dyn_cast
<InitListExpr
>(Init
))
1234 if (ILE
->getNumInits() == 0 && TryMemsetInitialization())
1237 // If we have a struct whose every field is value-initialized, we can
1238 // usually use memset.
1239 if (auto *ILE
= dyn_cast
<InitListExpr
>(Init
)) {
1240 if (const RecordType
*RType
= ILE
->getType()->getAs
<RecordType
>()) {
1241 if (RType
->getDecl()->isStruct()) {
1242 unsigned NumElements
= 0;
1243 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RType
->getDecl()))
1244 NumElements
= CXXRD
->getNumBases();
1245 for (auto *Field
: RType
->getDecl()->fields())
1246 if (!Field
->isUnnamedBitField())
1248 // FIXME: Recurse into nested InitListExprs.
1249 if (ILE
->getNumInits() == NumElements
)
1250 for (unsigned i
= 0, e
= ILE
->getNumInits(); i
!= e
; ++i
)
1251 if (!isa
<ImplicitValueInitExpr
>(ILE
->getInit(i
)))
1253 if (ILE
->getNumInits() == NumElements
&& TryMemsetInitialization())
1259 // Create the loop blocks.
1260 llvm::BasicBlock
*EntryBB
= Builder
.GetInsertBlock();
1261 llvm::BasicBlock
*LoopBB
= createBasicBlock("new.loop");
1262 llvm::BasicBlock
*ContBB
= createBasicBlock("new.loop.end");
1264 // Find the end of the array, hoisted out of the loop.
1265 llvm::Value
*EndPtr
= Builder
.CreateInBoundsGEP(
1266 BeginPtr
.getElementType(), BeginPtr
.emitRawPointer(*this), NumElements
,
1269 // If the number of elements isn't constant, we have to now check if there is
1270 // anything left to initialize.
1272 llvm::Value
*IsEmpty
= Builder
.CreateICmpEQ(CurPtr
.emitRawPointer(*this),
1273 EndPtr
, "array.isempty");
1274 Builder
.CreateCondBr(IsEmpty
, ContBB
, LoopBB
);
1280 // Set up the current-element phi.
1281 llvm::PHINode
*CurPtrPhi
=
1282 Builder
.CreatePHI(CurPtr
.getType(), 2, "array.cur");
1283 CurPtrPhi
->addIncoming(CurPtr
.emitRawPointer(*this), EntryBB
);
1285 CurPtr
= Address(CurPtrPhi
, CurPtr
.getElementType(), ElementAlign
);
1287 // Store the new Cleanup position for irregular Cleanups.
1288 if (EndOfInit
.isValid())
1289 Builder
.CreateStore(CurPtr
.emitRawPointer(*this), EndOfInit
);
1291 // Enter a partial-destruction Cleanup if necessary.
1292 if (!pushedCleanup
&& needsEHCleanup(DtorKind
)) {
1293 llvm::Instruction
*DominatingIP
=
1294 Builder
.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy
));
1295 pushRegularPartialArrayCleanup(BeginPtr
.emitRawPointer(*this),
1296 CurPtr
.emitRawPointer(*this), ElementType
,
1297 ElementAlign
, getDestroyer(DtorKind
));
1298 DeferredDeactivationCleanupStack
.push_back(
1299 {EHStack
.stable_begin(), DominatingIP
});
1302 // Emit the initializer into this element.
1303 StoreAnyExprIntoOneUnit(*this, Init
, Init
->getType(), CurPtr
,
1304 AggValueSlot::DoesNotOverlap
);
1306 // Leave the Cleanup if we entered one.
1307 deactivation
.ForceDeactivate();
1309 // Advance to the next element by adjusting the pointer type as necessary.
1310 llvm::Value
*NextPtr
= Builder
.CreateConstInBoundsGEP1_32(
1311 ElementTy
, CurPtr
.emitRawPointer(*this), 1, "array.next");
1313 // Check whether we've gotten to the end of the array and, if so,
1315 llvm::Value
*IsEnd
= Builder
.CreateICmpEQ(NextPtr
, EndPtr
, "array.atend");
1316 Builder
.CreateCondBr(IsEnd
, ContBB
, LoopBB
);
1317 CurPtrPhi
->addIncoming(NextPtr
, Builder
.GetInsertBlock());
1322 static void EmitNewInitializer(CodeGenFunction
&CGF
, const CXXNewExpr
*E
,
1323 QualType ElementType
, llvm::Type
*ElementTy
,
1324 Address NewPtr
, llvm::Value
*NumElements
,
1325 llvm::Value
*AllocSizeWithoutCookie
) {
1326 ApplyDebugLocation
DL(CGF
, E
);
1328 CGF
.EmitNewArrayInitializer(E
, ElementType
, ElementTy
, NewPtr
, NumElements
,
1329 AllocSizeWithoutCookie
);
1330 else if (const Expr
*Init
= E
->getInitializer())
1331 StoreAnyExprIntoOneUnit(CGF
, Init
, E
->getAllocatedType(), NewPtr
,
1332 AggValueSlot::DoesNotOverlap
);
1335 /// Emit a call to an operator new or operator delete function, as implicitly
1336 /// created by new-expressions and delete-expressions.
1337 static RValue
EmitNewDeleteCall(CodeGenFunction
&CGF
,
1338 const FunctionDecl
*CalleeDecl
,
1339 const FunctionProtoType
*CalleeType
,
1340 const CallArgList
&Args
) {
1341 llvm::CallBase
*CallOrInvoke
;
1342 llvm::Constant
*CalleePtr
= CGF
.CGM
.GetAddrOfFunction(CalleeDecl
);
1343 CGCallee Callee
= CGCallee::forDirect(CalleePtr
, GlobalDecl(CalleeDecl
));
1345 CGF
.EmitCall(CGF
.CGM
.getTypes().arrangeFreeFunctionCall(
1346 Args
, CalleeType
, /*ChainCall=*/false),
1347 Callee
, ReturnValueSlot(), Args
, &CallOrInvoke
);
1349 /// C++1y [expr.new]p10:
1350 /// [In a new-expression,] an implementation is allowed to omit a call
1351 /// to a replaceable global allocation function.
1353 /// We model such elidable calls with the 'builtin' attribute.
1354 llvm::Function
*Fn
= dyn_cast
<llvm::Function
>(CalleePtr
);
1355 if (CalleeDecl
->isReplaceableGlobalAllocationFunction() &&
1356 Fn
&& Fn
->hasFnAttribute(llvm::Attribute::NoBuiltin
)) {
1357 CallOrInvoke
->addFnAttr(llvm::Attribute::Builtin
);
1363 RValue
CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType
*Type
,
1364 const CallExpr
*TheCall
,
1367 EmitCallArgs(Args
, Type
, TheCall
->arguments());
1368 // Find the allocation or deallocation function that we're calling.
1369 ASTContext
&Ctx
= getContext();
1370 DeclarationName Name
= Ctx
.DeclarationNames
1371 .getCXXOperatorName(IsDelete
? OO_Delete
: OO_New
);
1373 for (auto *Decl
: Ctx
.getTranslationUnitDecl()->lookup(Name
))
1374 if (auto *FD
= dyn_cast
<FunctionDecl
>(Decl
))
1375 if (Ctx
.hasSameType(FD
->getType(), QualType(Type
, 0)))
1376 return EmitNewDeleteCall(*this, FD
, Type
, Args
);
1377 llvm_unreachable("predeclared global operator new/delete is missing");
1381 /// The parameters to pass to a usual operator delete.
1382 struct UsualDeleteParams
{
1383 bool DestroyingDelete
= false;
1385 bool Alignment
= false;
1389 static UsualDeleteParams
getUsualDeleteParams(const FunctionDecl
*FD
) {
1390 UsualDeleteParams Params
;
1392 const FunctionProtoType
*FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
1393 auto AI
= FPT
->param_type_begin(), AE
= FPT
->param_type_end();
1395 // The first argument is always a void*.
1398 // The next parameter may be a std::destroying_delete_t.
1399 if (FD
->isDestroyingOperatorDelete()) {
1400 Params
.DestroyingDelete
= true;
1405 // Figure out what other parameters we should be implicitly passing.
1406 if (AI
!= AE
&& (*AI
)->isIntegerType()) {
1411 if (AI
!= AE
&& (*AI
)->isAlignValT()) {
1412 Params
.Alignment
= true;
1416 assert(AI
== AE
&& "unexpected usual deallocation function parameter");
1421 /// A cleanup to call the given 'operator delete' function upon abnormal
1422 /// exit from a new expression. Templated on a traits type that deals with
1423 /// ensuring that the arguments dominate the cleanup if necessary.
1424 template<typename Traits
>
1425 class CallDeleteDuringNew final
: public EHScopeStack::Cleanup
{
1426 /// Type used to hold llvm::Value*s.
1427 typedef typename
Traits::ValueTy ValueTy
;
1428 /// Type used to hold RValues.
1429 typedef typename
Traits::RValueTy RValueTy
;
1430 struct PlacementArg
{
1435 unsigned NumPlacementArgs
: 31;
1436 LLVM_PREFERRED_TYPE(bool)
1437 unsigned PassAlignmentToPlacementDelete
: 1;
1438 const FunctionDecl
*OperatorDelete
;
1441 CharUnits AllocAlign
;
1443 PlacementArg
*getPlacementArgs() {
1444 return reinterpret_cast<PlacementArg
*>(this + 1);
1448 static size_t getExtraSize(size_t NumPlacementArgs
) {
1449 return NumPlacementArgs
* sizeof(PlacementArg
);
1452 CallDeleteDuringNew(size_t NumPlacementArgs
,
1453 const FunctionDecl
*OperatorDelete
, ValueTy Ptr
,
1454 ValueTy AllocSize
, bool PassAlignmentToPlacementDelete
,
1455 CharUnits AllocAlign
)
1456 : NumPlacementArgs(NumPlacementArgs
),
1457 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete
),
1458 OperatorDelete(OperatorDelete
), Ptr(Ptr
), AllocSize(AllocSize
),
1459 AllocAlign(AllocAlign
) {}
1461 void setPlacementArg(unsigned I
, RValueTy Arg
, QualType Type
) {
1462 assert(I
< NumPlacementArgs
&& "index out of range");
1463 getPlacementArgs()[I
] = {Arg
, Type
};
1466 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1467 const auto *FPT
= OperatorDelete
->getType()->castAs
<FunctionProtoType
>();
1468 CallArgList DeleteArgs
;
1470 // The first argument is always a void* (or C* for a destroying operator
1471 // delete for class type C).
1472 DeleteArgs
.add(Traits::get(CGF
, Ptr
), FPT
->getParamType(0));
1474 // Figure out what other parameters we should be implicitly passing.
1475 UsualDeleteParams Params
;
1476 if (NumPlacementArgs
) {
1477 // A placement deallocation function is implicitly passed an alignment
1478 // if the placement allocation function was, but is never passed a size.
1479 Params
.Alignment
= PassAlignmentToPlacementDelete
;
1481 // For a non-placement new-expression, 'operator delete' can take a
1482 // size and/or an alignment if it has the right parameters.
1483 Params
= getUsualDeleteParams(OperatorDelete
);
1486 assert(!Params
.DestroyingDelete
&&
1487 "should not call destroying delete in a new-expression");
1489 // The second argument can be a std::size_t (for non-placement delete).
1491 DeleteArgs
.add(Traits::get(CGF
, AllocSize
),
1492 CGF
.getContext().getSizeType());
1494 // The next (second or third) argument can be a std::align_val_t, which
1495 // is an enum whose underlying type is std::size_t.
1496 // FIXME: Use the right type as the parameter type. Note that in a call
1497 // to operator delete(size_t, ...), we may not have it available.
1498 if (Params
.Alignment
)
1499 DeleteArgs
.add(RValue::get(llvm::ConstantInt::get(
1500 CGF
.SizeTy
, AllocAlign
.getQuantity())),
1501 CGF
.getContext().getSizeType());
1503 // Pass the rest of the arguments, which must match exactly.
1504 for (unsigned I
= 0; I
!= NumPlacementArgs
; ++I
) {
1505 auto Arg
= getPlacementArgs()[I
];
1506 DeleteArgs
.add(Traits::get(CGF
, Arg
.ArgValue
), Arg
.ArgType
);
1509 // Call 'operator delete'.
1510 EmitNewDeleteCall(CGF
, OperatorDelete
, FPT
, DeleteArgs
);
1515 /// Enter a cleanup to call 'operator delete' if the initializer in a
1516 /// new-expression throws.
1517 static void EnterNewDeleteCleanup(CodeGenFunction
&CGF
,
1518 const CXXNewExpr
*E
,
1520 llvm::Value
*AllocSize
,
1521 CharUnits AllocAlign
,
1522 const CallArgList
&NewArgs
) {
1523 unsigned NumNonPlacementArgs
= E
->passAlignment() ? 2 : 1;
1525 // If we're not inside a conditional branch, then the cleanup will
1526 // dominate and we can do the easier (and more efficient) thing.
1527 if (!CGF
.isInConditionalBranch()) {
1528 struct DirectCleanupTraits
{
1529 typedef llvm::Value
*ValueTy
;
1530 typedef RValue RValueTy
;
1531 static RValue
get(CodeGenFunction
&, ValueTy V
) { return RValue::get(V
); }
1532 static RValue
get(CodeGenFunction
&, RValueTy V
) { return V
; }
1535 typedef CallDeleteDuringNew
<DirectCleanupTraits
> DirectCleanup
;
1537 DirectCleanup
*Cleanup
= CGF
.EHStack
.pushCleanupWithExtra
<DirectCleanup
>(
1538 EHCleanup
, E
->getNumPlacementArgs(), E
->getOperatorDelete(),
1539 NewPtr
.emitRawPointer(CGF
), AllocSize
, E
->passAlignment(), AllocAlign
);
1540 for (unsigned I
= 0, N
= E
->getNumPlacementArgs(); I
!= N
; ++I
) {
1541 auto &Arg
= NewArgs
[I
+ NumNonPlacementArgs
];
1542 Cleanup
->setPlacementArg(I
, Arg
.getRValue(CGF
), Arg
.Ty
);
1548 // Otherwise, we need to save all this stuff.
1549 DominatingValue
<RValue
>::saved_type SavedNewPtr
=
1550 DominatingValue
<RValue
>::save(CGF
, RValue::get(NewPtr
, CGF
));
1551 DominatingValue
<RValue
>::saved_type SavedAllocSize
=
1552 DominatingValue
<RValue
>::save(CGF
, RValue::get(AllocSize
));
1554 struct ConditionalCleanupTraits
{
1555 typedef DominatingValue
<RValue
>::saved_type ValueTy
;
1556 typedef DominatingValue
<RValue
>::saved_type RValueTy
;
1557 static RValue
get(CodeGenFunction
&CGF
, ValueTy V
) {
1558 return V
.restore(CGF
);
1561 typedef CallDeleteDuringNew
<ConditionalCleanupTraits
> ConditionalCleanup
;
1563 ConditionalCleanup
*Cleanup
= CGF
.EHStack
1564 .pushCleanupWithExtra
<ConditionalCleanup
>(EHCleanup
,
1565 E
->getNumPlacementArgs(),
1566 E
->getOperatorDelete(),
1571 for (unsigned I
= 0, N
= E
->getNumPlacementArgs(); I
!= N
; ++I
) {
1572 auto &Arg
= NewArgs
[I
+ NumNonPlacementArgs
];
1573 Cleanup
->setPlacementArg(
1574 I
, DominatingValue
<RValue
>::save(CGF
, Arg
.getRValue(CGF
)), Arg
.Ty
);
1577 CGF
.initFullExprCleanup();
1580 llvm::Value
*CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr
*E
) {
1581 // The element type being allocated.
1582 QualType allocType
= getContext().getBaseElementType(E
->getAllocatedType());
1584 // 1. Build a call to the allocation function.
1585 FunctionDecl
*allocator
= E
->getOperatorNew();
1587 // If there is a brace-initializer or C++20 parenthesized initializer, cannot
1588 // allocate fewer elements than inits.
1589 unsigned minElements
= 0;
1590 if (E
->isArray() && E
->hasInitializer()) {
1591 const Expr
*Init
= E
->getInitializer();
1592 const InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(Init
);
1593 const CXXParenListInitExpr
*CPLIE
= dyn_cast
<CXXParenListInitExpr
>(Init
);
1594 const Expr
*IgnoreParen
= Init
->IgnoreParenImpCasts();
1595 if ((ILE
&& ILE
->isStringLiteralInit()) ||
1596 isa
<StringLiteral
>(IgnoreParen
) || isa
<ObjCEncodeExpr
>(IgnoreParen
)) {
1598 cast
<ConstantArrayType
>(Init
->getType()->getAsArrayTypeUnsafe())
1600 } else if (ILE
|| CPLIE
) {
1601 minElements
= ILE
? ILE
->getNumInits() : CPLIE
->getInitExprs().size();
1605 llvm::Value
*numElements
= nullptr;
1606 llvm::Value
*allocSizeWithoutCookie
= nullptr;
1607 llvm::Value
*allocSize
=
1608 EmitCXXNewAllocSize(*this, E
, minElements
, numElements
,
1609 allocSizeWithoutCookie
);
1610 CharUnits allocAlign
= getContext().getTypeAlignInChars(allocType
);
1612 // Emit the allocation call. If the allocator is a global placement
1613 // operator, just "inline" it directly.
1614 Address allocation
= Address::invalid();
1615 CallArgList allocatorArgs
;
1616 if (allocator
->isReservedGlobalPlacementOperator()) {
1617 assert(E
->getNumPlacementArgs() == 1);
1618 const Expr
*arg
= *E
->placement_arguments().begin();
1620 LValueBaseInfo BaseInfo
;
1621 allocation
= EmitPointerWithAlignment(arg
, &BaseInfo
);
1623 // The pointer expression will, in many cases, be an opaque void*.
1624 // In these cases, discard the computed alignment and use the
1625 // formal alignment of the allocated type.
1626 if (BaseInfo
.getAlignmentSource() != AlignmentSource::Decl
)
1627 allocation
.setAlignment(allocAlign
);
1629 // Set up allocatorArgs for the call to operator delete if it's not
1630 // the reserved global operator.
1631 if (E
->getOperatorDelete() &&
1632 !E
->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1633 allocatorArgs
.add(RValue::get(allocSize
), getContext().getSizeType());
1634 allocatorArgs
.add(RValue::get(allocation
, *this), arg
->getType());
1638 const FunctionProtoType
*allocatorType
=
1639 allocator
->getType()->castAs
<FunctionProtoType
>();
1640 unsigned ParamsToSkip
= 0;
1642 // The allocation size is the first argument.
1643 QualType sizeType
= getContext().getSizeType();
1644 allocatorArgs
.add(RValue::get(allocSize
), sizeType
);
1647 if (allocSize
!= allocSizeWithoutCookie
) {
1648 CharUnits cookieAlign
= getSizeAlign(); // FIXME: Ask the ABI.
1649 allocAlign
= std::max(allocAlign
, cookieAlign
);
1652 // The allocation alignment may be passed as the second argument.
1653 if (E
->passAlignment()) {
1654 QualType AlignValT
= sizeType
;
1655 if (allocatorType
->getNumParams() > 1) {
1656 AlignValT
= allocatorType
->getParamType(1);
1657 assert(getContext().hasSameUnqualifiedType(
1658 AlignValT
->castAs
<EnumType
>()->getDecl()->getIntegerType(),
1660 "wrong type for alignment parameter");
1663 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1664 assert(allocator
->isVariadic() && "can't pass alignment to allocator");
1667 RValue::get(llvm::ConstantInt::get(SizeTy
, allocAlign
.getQuantity())),
1671 // FIXME: Why do we not pass a CalleeDecl here?
1672 EmitCallArgs(allocatorArgs
, allocatorType
, E
->placement_arguments(),
1673 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip
);
1676 EmitNewDeleteCall(*this, allocator
, allocatorType
, allocatorArgs
);
1678 // Set !heapallocsite metadata on the call to operator new.
1680 if (auto *newCall
= dyn_cast
<llvm::CallBase
>(RV
.getScalarVal()))
1681 getDebugInfo()->addHeapAllocSiteMetadata(newCall
, allocType
,
1684 // If this was a call to a global replaceable allocation function that does
1685 // not take an alignment argument, the allocator is known to produce
1686 // storage that's suitably aligned for any object that fits, up to a known
1687 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1688 CharUnits allocationAlign
= allocAlign
;
1689 if (!E
->passAlignment() &&
1690 allocator
->isReplaceableGlobalAllocationFunction()) {
1691 unsigned AllocatorAlign
= llvm::bit_floor(std::min
<uint64_t>(
1692 Target
.getNewAlign(), getContext().getTypeSize(allocType
)));
1693 allocationAlign
= std::max(
1694 allocationAlign
, getContext().toCharUnitsFromBits(AllocatorAlign
));
1697 allocation
= Address(RV
.getScalarVal(), Int8Ty
, allocationAlign
);
1700 // Emit a null check on the allocation result if the allocation
1701 // function is allowed to return null (because it has a non-throwing
1702 // exception spec or is the reserved placement new) and we have an
1703 // interesting initializer will be running sanitizers on the initialization.
1704 bool nullCheck
= E
->shouldNullCheckAllocation() &&
1705 (!allocType
.isPODType(getContext()) || E
->hasInitializer() ||
1706 sanitizePerformTypeCheck());
1708 llvm::BasicBlock
*nullCheckBB
= nullptr;
1709 llvm::BasicBlock
*contBB
= nullptr;
1711 // The null-check means that the initializer is conditionally
1713 ConditionalEvaluation
conditional(*this);
1716 conditional
.begin(*this);
1718 nullCheckBB
= Builder
.GetInsertBlock();
1719 llvm::BasicBlock
*notNullBB
= createBasicBlock("new.notnull");
1720 contBB
= createBasicBlock("new.cont");
1722 llvm::Value
*isNull
= Builder
.CreateIsNull(allocation
, "new.isnull");
1723 Builder
.CreateCondBr(isNull
, contBB
, notNullBB
);
1724 EmitBlock(notNullBB
);
1727 // If there's an operator delete, enter a cleanup to call it if an
1728 // exception is thrown.
1729 EHScopeStack::stable_iterator operatorDeleteCleanup
;
1730 llvm::Instruction
*cleanupDominator
= nullptr;
1731 if (E
->getOperatorDelete() &&
1732 !E
->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1733 EnterNewDeleteCleanup(*this, E
, allocation
, allocSize
, allocAlign
,
1735 operatorDeleteCleanup
= EHStack
.stable_begin();
1736 cleanupDominator
= Builder
.CreateUnreachable();
1739 assert((allocSize
== allocSizeWithoutCookie
) ==
1740 CalculateCookiePadding(*this, E
).isZero());
1741 if (allocSize
!= allocSizeWithoutCookie
) {
1742 assert(E
->isArray());
1743 allocation
= CGM
.getCXXABI().InitializeArrayCookie(*this, allocation
,
1748 llvm::Type
*elementTy
= ConvertTypeForMem(allocType
);
1749 Address result
= allocation
.withElementType(elementTy
);
1751 // Passing pointer through launder.invariant.group to avoid propagation of
1752 // vptrs information which may be included in previous type.
1753 // To not break LTO with different optimizations levels, we do it regardless
1754 // of optimization level.
1755 if (CGM
.getCodeGenOpts().StrictVTablePointers
&&
1756 allocator
->isReservedGlobalPlacementOperator())
1757 result
= Builder
.CreateLaunderInvariantGroup(result
);
1759 // Emit sanitizer checks for pointer value now, so that in the case of an
1760 // array it was checked only once and not at each constructor call. We may
1761 // have already checked that the pointer is non-null.
1762 // FIXME: If we have an array cookie and a potentially-throwing allocator,
1763 // we'll null check the wrong pointer here.
1764 SanitizerSet SkippedChecks
;
1765 SkippedChecks
.set(SanitizerKind::Null
, nullCheck
);
1766 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall
,
1767 E
->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1768 result
, allocType
, result
.getAlignment(), SkippedChecks
,
1771 EmitNewInitializer(*this, E
, allocType
, elementTy
, result
, numElements
,
1772 allocSizeWithoutCookie
);
1773 llvm::Value
*resultPtr
= result
.emitRawPointer(*this);
1775 // Deactivate the 'operator delete' cleanup if we finished
1777 if (operatorDeleteCleanup
.isValid()) {
1778 DeactivateCleanupBlock(operatorDeleteCleanup
, cleanupDominator
);
1779 cleanupDominator
->eraseFromParent();
1783 conditional
.end(*this);
1785 llvm::BasicBlock
*notNullBB
= Builder
.GetInsertBlock();
1788 llvm::PHINode
*PHI
= Builder
.CreatePHI(resultPtr
->getType(), 2);
1789 PHI
->addIncoming(resultPtr
, notNullBB
);
1790 PHI
->addIncoming(llvm::Constant::getNullValue(resultPtr
->getType()),
1799 void CodeGenFunction::EmitDeleteCall(const FunctionDecl
*DeleteFD
,
1800 llvm::Value
*DeletePtr
, QualType DeleteTy
,
1801 llvm::Value
*NumElements
,
1802 CharUnits CookieSize
) {
1803 assert((!NumElements
&& CookieSize
.isZero()) ||
1804 DeleteFD
->getOverloadedOperator() == OO_Array_Delete
);
1806 const auto *DeleteFTy
= DeleteFD
->getType()->castAs
<FunctionProtoType
>();
1807 CallArgList DeleteArgs
;
1809 auto Params
= getUsualDeleteParams(DeleteFD
);
1810 auto ParamTypeIt
= DeleteFTy
->param_type_begin();
1812 // Pass the pointer itself.
1813 QualType ArgTy
= *ParamTypeIt
++;
1814 DeleteArgs
.add(RValue::get(DeletePtr
), ArgTy
);
1816 // Pass the std::destroying_delete tag if present.
1817 llvm::AllocaInst
*DestroyingDeleteTag
= nullptr;
1818 if (Params
.DestroyingDelete
) {
1819 QualType DDTag
= *ParamTypeIt
++;
1820 llvm::Type
*Ty
= getTypes().ConvertType(DDTag
);
1821 CharUnits Align
= CGM
.getNaturalTypeAlignment(DDTag
);
1822 DestroyingDeleteTag
= CreateTempAlloca(Ty
, "destroying.delete.tag");
1823 DestroyingDeleteTag
->setAlignment(Align
.getAsAlign());
1825 RValue::getAggregate(Address(DestroyingDeleteTag
, Ty
, Align
)), DDTag
);
1828 // Pass the size if the delete function has a size_t parameter.
1830 QualType SizeType
= *ParamTypeIt
++;
1831 CharUnits DeleteTypeSize
= getContext().getTypeSizeInChars(DeleteTy
);
1832 llvm::Value
*Size
= llvm::ConstantInt::get(ConvertType(SizeType
),
1833 DeleteTypeSize
.getQuantity());
1835 // For array new, multiply by the number of elements.
1837 Size
= Builder
.CreateMul(Size
, NumElements
);
1839 // If there is a cookie, add the cookie size.
1840 if (!CookieSize
.isZero())
1841 Size
= Builder
.CreateAdd(
1842 Size
, llvm::ConstantInt::get(SizeTy
, CookieSize
.getQuantity()));
1844 DeleteArgs
.add(RValue::get(Size
), SizeType
);
1847 // Pass the alignment if the delete function has an align_val_t parameter.
1848 if (Params
.Alignment
) {
1849 QualType AlignValType
= *ParamTypeIt
++;
1850 CharUnits DeleteTypeAlign
=
1851 getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1852 DeleteTy
, true /* NeedsPreferredAlignment */));
1853 llvm::Value
*Align
= llvm::ConstantInt::get(ConvertType(AlignValType
),
1854 DeleteTypeAlign
.getQuantity());
1855 DeleteArgs
.add(RValue::get(Align
), AlignValType
);
1858 assert(ParamTypeIt
== DeleteFTy
->param_type_end() &&
1859 "unknown parameter to usual delete function");
1861 // Emit the call to delete.
1862 EmitNewDeleteCall(*this, DeleteFD
, DeleteFTy
, DeleteArgs
);
1864 // If call argument lowering didn't use the destroying_delete_t alloca,
1866 if (DestroyingDeleteTag
&& DestroyingDeleteTag
->use_empty())
1867 DestroyingDeleteTag
->eraseFromParent();
1871 /// Calls the given 'operator delete' on a single object.
1872 struct CallObjectDelete final
: EHScopeStack::Cleanup
{
1874 const FunctionDecl
*OperatorDelete
;
1875 QualType ElementType
;
1877 CallObjectDelete(llvm::Value
*Ptr
,
1878 const FunctionDecl
*OperatorDelete
,
1879 QualType ElementType
)
1880 : Ptr(Ptr
), OperatorDelete(OperatorDelete
), ElementType(ElementType
) {}
1882 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1883 CGF
.EmitDeleteCall(OperatorDelete
, Ptr
, ElementType
);
1889 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl
*OperatorDelete
,
1890 llvm::Value
*CompletePtr
,
1891 QualType ElementType
) {
1892 EHStack
.pushCleanup
<CallObjectDelete
>(NormalAndEHCleanup
, CompletePtr
,
1893 OperatorDelete
, ElementType
);
1896 /// Emit the code for deleting a single object with a destroying operator
1897 /// delete. If the element type has a non-virtual destructor, Ptr has already
1898 /// been converted to the type of the parameter of 'operator delete'. Otherwise
1899 /// Ptr points to an object of the static type.
1900 static void EmitDestroyingObjectDelete(CodeGenFunction
&CGF
,
1901 const CXXDeleteExpr
*DE
, Address Ptr
,
1902 QualType ElementType
) {
1903 auto *Dtor
= ElementType
->getAsCXXRecordDecl()->getDestructor();
1904 if (Dtor
&& Dtor
->isVirtual())
1905 CGF
.CGM
.getCXXABI().emitVirtualObjectDelete(CGF
, DE
, Ptr
, ElementType
,
1908 CGF
.EmitDeleteCall(DE
->getOperatorDelete(), Ptr
.emitRawPointer(CGF
),
1912 /// Emit the code for deleting a single object.
1913 /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1915 static bool EmitObjectDelete(CodeGenFunction
&CGF
,
1916 const CXXDeleteExpr
*DE
,
1918 QualType ElementType
,
1919 llvm::BasicBlock
*UnconditionalDeleteBlock
) {
1920 // C++11 [expr.delete]p3:
1921 // If the static type of the object to be deleted is different from its
1922 // dynamic type, the static type shall be a base class of the dynamic type
1923 // of the object to be deleted and the static type shall have a virtual
1924 // destructor or the behavior is undefined.
1925 CGF
.EmitTypeCheck(CodeGenFunction::TCK_MemberCall
, DE
->getExprLoc(), Ptr
,
1928 const FunctionDecl
*OperatorDelete
= DE
->getOperatorDelete();
1929 assert(!OperatorDelete
->isDestroyingOperatorDelete());
1931 // Find the destructor for the type, if applicable. If the
1932 // destructor is virtual, we'll just emit the vcall and return.
1933 const CXXDestructorDecl
*Dtor
= nullptr;
1934 if (const RecordType
*RT
= ElementType
->getAs
<RecordType
>()) {
1935 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
1936 if (RD
->hasDefinition() && !RD
->hasTrivialDestructor()) {
1937 Dtor
= RD
->getDestructor();
1939 if (Dtor
->isVirtual()) {
1940 bool UseVirtualCall
= true;
1941 const Expr
*Base
= DE
->getArgument();
1942 if (auto *DevirtualizedDtor
=
1943 dyn_cast_or_null
<const CXXDestructorDecl
>(
1944 Dtor
->getDevirtualizedMethod(
1945 Base
, CGF
.CGM
.getLangOpts().AppleKext
))) {
1946 UseVirtualCall
= false;
1947 const CXXRecordDecl
*DevirtualizedClass
=
1948 DevirtualizedDtor
->getParent();
1949 if (declaresSameEntity(getCXXRecord(Base
), DevirtualizedClass
)) {
1950 // Devirtualized to the class of the base type (the type of the
1951 // whole expression).
1952 Dtor
= DevirtualizedDtor
;
1954 // Devirtualized to some other type. Would need to cast the this
1955 // pointer to that type but we don't have support for that yet, so
1956 // do a virtual call. FIXME: handle the case where it is
1957 // devirtualized to the derived type (the type of the inner
1958 // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1959 UseVirtualCall
= true;
1962 if (UseVirtualCall
) {
1963 CGF
.CGM
.getCXXABI().emitVirtualObjectDelete(CGF
, DE
, Ptr
, ElementType
,
1971 // Make sure that we call delete even if the dtor throws.
1972 // This doesn't have to a conditional cleanup because we're going
1973 // to pop it off in a second.
1974 CGF
.EHStack
.pushCleanup
<CallObjectDelete
>(
1975 NormalAndEHCleanup
, Ptr
.emitRawPointer(CGF
), OperatorDelete
, ElementType
);
1978 CGF
.EmitCXXDestructorCall(Dtor
, Dtor_Complete
,
1979 /*ForVirtualBase=*/false,
1980 /*Delegating=*/false,
1982 else if (auto Lifetime
= ElementType
.getObjCLifetime()) {
1984 case Qualifiers::OCL_None
:
1985 case Qualifiers::OCL_ExplicitNone
:
1986 case Qualifiers::OCL_Autoreleasing
:
1989 case Qualifiers::OCL_Strong
:
1990 CGF
.EmitARCDestroyStrong(Ptr
, ARCPreciseLifetime
);
1993 case Qualifiers::OCL_Weak
:
1994 CGF
.EmitARCDestroyWeak(Ptr
);
1999 // When optimizing for size, call 'operator delete' unconditionally.
2000 if (CGF
.CGM
.getCodeGenOpts().OptimizeSize
> 1) {
2001 CGF
.EmitBlock(UnconditionalDeleteBlock
);
2002 CGF
.PopCleanupBlock();
2006 CGF
.PopCleanupBlock();
2011 /// Calls the given 'operator delete' on an array of objects.
2012 struct CallArrayDelete final
: EHScopeStack::Cleanup
{
2014 const FunctionDecl
*OperatorDelete
;
2015 llvm::Value
*NumElements
;
2016 QualType ElementType
;
2017 CharUnits CookieSize
;
2019 CallArrayDelete(llvm::Value
*Ptr
,
2020 const FunctionDecl
*OperatorDelete
,
2021 llvm::Value
*NumElements
,
2022 QualType ElementType
,
2023 CharUnits CookieSize
)
2024 : Ptr(Ptr
), OperatorDelete(OperatorDelete
), NumElements(NumElements
),
2025 ElementType(ElementType
), CookieSize(CookieSize
) {}
2027 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
2028 CGF
.EmitDeleteCall(OperatorDelete
, Ptr
, ElementType
, NumElements
,
2034 /// Emit the code for deleting an array of objects.
2035 static void EmitArrayDelete(CodeGenFunction
&CGF
,
2036 const CXXDeleteExpr
*E
,
2038 QualType elementType
) {
2039 llvm::Value
*numElements
= nullptr;
2040 llvm::Value
*allocatedPtr
= nullptr;
2041 CharUnits cookieSize
;
2042 CGF
.CGM
.getCXXABI().ReadArrayCookie(CGF
, deletedPtr
, E
, elementType
,
2043 numElements
, allocatedPtr
, cookieSize
);
2045 assert(allocatedPtr
&& "ReadArrayCookie didn't set allocated pointer");
2047 // Make sure that we call delete even if one of the dtors throws.
2048 const FunctionDecl
*operatorDelete
= E
->getOperatorDelete();
2049 CGF
.EHStack
.pushCleanup
<CallArrayDelete
>(NormalAndEHCleanup
,
2050 allocatedPtr
, operatorDelete
,
2051 numElements
, elementType
,
2054 // Destroy the elements.
2055 if (QualType::DestructionKind dtorKind
= elementType
.isDestructedType()) {
2056 assert(numElements
&& "no element count for a type with a destructor!");
2058 CharUnits elementSize
= CGF
.getContext().getTypeSizeInChars(elementType
);
2059 CharUnits elementAlign
=
2060 deletedPtr
.getAlignment().alignmentOfArrayElement(elementSize
);
2062 llvm::Value
*arrayBegin
= deletedPtr
.emitRawPointer(CGF
);
2063 llvm::Value
*arrayEnd
= CGF
.Builder
.CreateInBoundsGEP(
2064 deletedPtr
.getElementType(), arrayBegin
, numElements
, "delete.end");
2066 // Note that it is legal to allocate a zero-length array, and we
2067 // can never fold the check away because the length should always
2068 // come from a cookie.
2069 CGF
.emitArrayDestroy(arrayBegin
, arrayEnd
, elementType
, elementAlign
,
2070 CGF
.getDestroyer(dtorKind
),
2071 /*checkZeroLength*/ true,
2072 CGF
.needsEHCleanup(dtorKind
));
2075 // Pop the cleanup block.
2076 CGF
.PopCleanupBlock();
2079 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr
*E
) {
2080 const Expr
*Arg
= E
->getArgument();
2081 Address Ptr
= EmitPointerWithAlignment(Arg
);
2083 // Null check the pointer.
2085 // We could avoid this null check if we can determine that the object
2086 // destruction is trivial and doesn't require an array cookie; we can
2087 // unconditionally perform the operator delete call in that case. For now, we
2088 // assume that deleted pointers are null rarely enough that it's better to
2089 // keep the branch. This might be worth revisiting for a -O0 code size win.
2090 llvm::BasicBlock
*DeleteNotNull
= createBasicBlock("delete.notnull");
2091 llvm::BasicBlock
*DeleteEnd
= createBasicBlock("delete.end");
2093 llvm::Value
*IsNull
= Builder
.CreateIsNull(Ptr
, "isnull");
2095 Builder
.CreateCondBr(IsNull
, DeleteEnd
, DeleteNotNull
);
2096 EmitBlock(DeleteNotNull
);
2097 Ptr
.setKnownNonNull();
2099 QualType DeleteTy
= E
->getDestroyedType();
2101 // A destroying operator delete overrides the entire operation of the
2102 // delete expression.
2103 if (E
->getOperatorDelete()->isDestroyingOperatorDelete()) {
2104 EmitDestroyingObjectDelete(*this, E
, Ptr
, DeleteTy
);
2105 EmitBlock(DeleteEnd
);
2109 // We might be deleting a pointer to array. If so, GEP down to the
2110 // first non-array element.
2111 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
2112 if (DeleteTy
->isConstantArrayType()) {
2113 llvm::Value
*Zero
= Builder
.getInt32(0);
2114 SmallVector
<llvm::Value
*,8> GEP
;
2116 GEP
.push_back(Zero
); // point at the outermost array
2118 // For each layer of array type we're pointing at:
2119 while (const ConstantArrayType
*Arr
2120 = getContext().getAsConstantArrayType(DeleteTy
)) {
2121 // 1. Unpeel the array type.
2122 DeleteTy
= Arr
->getElementType();
2124 // 2. GEP to the first element of the array.
2125 GEP
.push_back(Zero
);
2128 Ptr
= Builder
.CreateInBoundsGEP(Ptr
, GEP
, ConvertTypeForMem(DeleteTy
),
2129 Ptr
.getAlignment(), "del.first");
2132 assert(ConvertTypeForMem(DeleteTy
) == Ptr
.getElementType());
2134 if (E
->isArrayForm()) {
2135 EmitArrayDelete(*this, E
, Ptr
, DeleteTy
);
2136 EmitBlock(DeleteEnd
);
2138 if (!EmitObjectDelete(*this, E
, Ptr
, DeleteTy
, DeleteEnd
))
2139 EmitBlock(DeleteEnd
);
2143 static llvm::Value
*EmitTypeidFromVTable(CodeGenFunction
&CGF
, const Expr
*E
,
2144 llvm::Type
*StdTypeInfoPtrTy
,
2145 bool HasNullCheck
) {
2146 // Get the vtable pointer.
2147 Address ThisPtr
= CGF
.EmitLValue(E
).getAddress();
2149 QualType SrcRecordTy
= E
->getType();
2151 // C++ [class.cdtor]p4:
2152 // If the operand of typeid refers to the object under construction or
2153 // destruction and the static type of the operand is neither the constructor
2154 // or destructor’s class nor one of its bases, the behavior is undefined.
2155 CGF
.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation
, E
->getExprLoc(),
2156 ThisPtr
, SrcRecordTy
);
2158 // Whether we need an explicit null pointer check. For example, with the
2159 // Microsoft ABI, if this is a call to __RTtypeid, the null pointer check and
2160 // exception throw is inside the __RTtypeid(nullptr) call
2162 CGF
.CGM
.getCXXABI().shouldTypeidBeNullChecked(SrcRecordTy
)) {
2163 llvm::BasicBlock
*BadTypeidBlock
=
2164 CGF
.createBasicBlock("typeid.bad_typeid");
2165 llvm::BasicBlock
*EndBlock
= CGF
.createBasicBlock("typeid.end");
2167 llvm::Value
*IsNull
= CGF
.Builder
.CreateIsNull(ThisPtr
);
2168 CGF
.Builder
.CreateCondBr(IsNull
, BadTypeidBlock
, EndBlock
);
2170 CGF
.EmitBlock(BadTypeidBlock
);
2171 CGF
.CGM
.getCXXABI().EmitBadTypeidCall(CGF
);
2172 CGF
.EmitBlock(EndBlock
);
2175 return CGF
.CGM
.getCXXABI().EmitTypeid(CGF
, SrcRecordTy
, ThisPtr
,
2179 llvm::Value
*CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr
*E
) {
2180 // Ideally, we would like to use GlobalsInt8PtrTy here, however, we cannot,
2181 // primarily because the result of applying typeid is a value of type
2182 // type_info, which is declared & defined by the standard library
2183 // implementation and expects to operate on the generic (default) AS.
2184 // https://reviews.llvm.org/D157452 has more context, and a possible solution.
2185 llvm::Type
*PtrTy
= Int8PtrTy
;
2186 LangAS GlobAS
= CGM
.GetGlobalVarAddressSpace(nullptr);
2188 auto MaybeASCast
= [=](auto &&TypeInfo
) {
2189 if (GlobAS
== LangAS::Default
)
2191 return getTargetHooks().performAddrSpaceCast(CGM
,TypeInfo
, GlobAS
,
2192 LangAS::Default
, PtrTy
);
2195 if (E
->isTypeOperand()) {
2196 llvm::Constant
*TypeInfo
=
2197 CGM
.GetAddrOfRTTIDescriptor(E
->getTypeOperand(getContext()));
2198 return MaybeASCast(TypeInfo
);
2201 // C++ [expr.typeid]p2:
2202 // When typeid is applied to a glvalue expression whose type is a
2203 // polymorphic class type, the result refers to a std::type_info object
2204 // representing the type of the most derived object (that is, the dynamic
2205 // type) to which the glvalue refers.
2206 // If the operand is already most derived object, no need to look up vtable.
2207 if (E
->isPotentiallyEvaluated() && !E
->isMostDerived(getContext()))
2208 return EmitTypeidFromVTable(*this, E
->getExprOperand(), PtrTy
,
2211 QualType OperandTy
= E
->getExprOperand()->getType();
2212 return MaybeASCast(CGM
.GetAddrOfRTTIDescriptor(OperandTy
));
2215 static llvm::Value
*EmitDynamicCastToNull(CodeGenFunction
&CGF
,
2217 llvm::Type
*DestLTy
= CGF
.ConvertType(DestTy
);
2218 if (DestTy
->isPointerType())
2219 return llvm::Constant::getNullValue(DestLTy
);
2221 /// C++ [expr.dynamic.cast]p9:
2222 /// A failed cast to reference type throws std::bad_cast
2223 if (!CGF
.CGM
.getCXXABI().EmitBadCastCall(CGF
))
2226 CGF
.Builder
.ClearInsertionPoint();
2227 return llvm::PoisonValue::get(DestLTy
);
2230 llvm::Value
*CodeGenFunction::EmitDynamicCast(Address ThisAddr
,
2231 const CXXDynamicCastExpr
*DCE
) {
2232 CGM
.EmitExplicitCastExprType(DCE
, this);
2233 QualType DestTy
= DCE
->getTypeAsWritten();
2235 QualType SrcTy
= DCE
->getSubExpr()->getType();
2237 // C++ [expr.dynamic.cast]p7:
2238 // If T is "pointer to cv void," then the result is a pointer to the most
2239 // derived object pointed to by v.
2240 bool IsDynamicCastToVoid
= DestTy
->isVoidPointerType();
2241 QualType SrcRecordTy
;
2242 QualType DestRecordTy
;
2243 if (IsDynamicCastToVoid
) {
2244 SrcRecordTy
= SrcTy
->getPointeeType();
2246 } else if (const PointerType
*DestPTy
= DestTy
->getAs
<PointerType
>()) {
2247 SrcRecordTy
= SrcTy
->castAs
<PointerType
>()->getPointeeType();
2248 DestRecordTy
= DestPTy
->getPointeeType();
2250 SrcRecordTy
= SrcTy
;
2251 DestRecordTy
= DestTy
->castAs
<ReferenceType
>()->getPointeeType();
2254 // C++ [class.cdtor]p5:
2255 // If the operand of the dynamic_cast refers to the object under
2256 // construction or destruction and the static type of the operand is not a
2257 // pointer to or object of the constructor or destructor’s own class or one
2258 // of its bases, the dynamic_cast results in undefined behavior.
2259 EmitTypeCheck(TCK_DynamicOperation
, DCE
->getExprLoc(), ThisAddr
, SrcRecordTy
);
2261 if (DCE
->isAlwaysNull()) {
2262 if (llvm::Value
*T
= EmitDynamicCastToNull(*this, DestTy
)) {
2263 // Expression emission is expected to retain a valid insertion point.
2264 if (!Builder
.GetInsertBlock())
2265 EmitBlock(createBasicBlock("dynamic_cast.unreachable"));
2270 assert(SrcRecordTy
->isRecordType() && "source type must be a record type!");
2272 // If the destination is effectively final, the cast succeeds if and only
2273 // if the dynamic type of the pointer is exactly the destination type.
2274 bool IsExact
= !IsDynamicCastToVoid
&&
2275 CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
2276 DestRecordTy
->getAsCXXRecordDecl()->isEffectivelyFinal() &&
2277 CGM
.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy
);
2279 // C++ [expr.dynamic.cast]p4:
2280 // If the value of v is a null pointer value in the pointer case, the result
2281 // is the null pointer value of type T.
2282 bool ShouldNullCheckSrcValue
=
2283 IsExact
|| CGM
.getCXXABI().shouldDynamicCastCallBeNullChecked(
2284 SrcTy
->isPointerType(), SrcRecordTy
);
2286 llvm::BasicBlock
*CastNull
= nullptr;
2287 llvm::BasicBlock
*CastNotNull
= nullptr;
2288 llvm::BasicBlock
*CastEnd
= createBasicBlock("dynamic_cast.end");
2290 if (ShouldNullCheckSrcValue
) {
2291 CastNull
= createBasicBlock("dynamic_cast.null");
2292 CastNotNull
= createBasicBlock("dynamic_cast.notnull");
2294 llvm::Value
*IsNull
= Builder
.CreateIsNull(ThisAddr
);
2295 Builder
.CreateCondBr(IsNull
, CastNull
, CastNotNull
);
2296 EmitBlock(CastNotNull
);
2300 if (IsDynamicCastToVoid
) {
2301 Value
= CGM
.getCXXABI().emitDynamicCastToVoid(*this, ThisAddr
, SrcRecordTy
);
2302 } else if (IsExact
) {
2303 // If the destination type is effectively final, this pointer points to the
2304 // right type if and only if its vptr has the right value.
2305 Value
= CGM
.getCXXABI().emitExactDynamicCast(
2306 *this, ThisAddr
, SrcRecordTy
, DestTy
, DestRecordTy
, CastEnd
, CastNull
);
2308 assert(DestRecordTy
->isRecordType() &&
2309 "destination type must be a record type!");
2310 Value
= CGM
.getCXXABI().emitDynamicCastCall(*this, ThisAddr
, SrcRecordTy
,
2311 DestTy
, DestRecordTy
, CastEnd
);
2313 CastNotNull
= Builder
.GetInsertBlock();
2315 llvm::Value
*NullValue
= nullptr;
2316 if (ShouldNullCheckSrcValue
) {
2317 EmitBranch(CastEnd
);
2319 EmitBlock(CastNull
);
2320 NullValue
= EmitDynamicCastToNull(*this, DestTy
);
2321 CastNull
= Builder
.GetInsertBlock();
2323 EmitBranch(CastEnd
);
2329 llvm::PHINode
*PHI
= Builder
.CreatePHI(Value
->getType(), 2);
2330 PHI
->addIncoming(Value
, CastNotNull
);
2331 PHI
->addIncoming(NullValue
, CastNull
);