clang 20.0.0git
CGExprCXX.cpp
Go to the documentation of this file.
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"
22#include "llvm/IR/Intrinsics.h"
23
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
28struct MemberCallInfo {
29 RequiredArgs ReqArgs;
30 // Number of prefix arguments for the call. Ignores the `this` pointer.
31 unsigned PrefixSize;
32};
33}
34
35static MemberCallInfo
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 =
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
85RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
86 const CXXMethodDecl *MD, const CGCallee &Callee,
87 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
88 QualType ImplicitParamTy, const CallExpr *CE, CallArgList *RtlArgs,
89 llvm::CallBase **CallOrInvoke) {
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
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, DstAS,
117 NewType);
118 }
119
120 CallArgList Args;
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{});
127}
128
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;
139
140 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
141 if (E->isArrow()) {
142 BaseValue = EmitPointerWithAlignment(BaseExpr);
143 const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
144 BaseQuals = PTy->getPointeeType().getQualifiers();
145 } else {
146 LValue BaseLV = EmitLValue(BaseExpr);
147 BaseValue = BaseLV.getAddress();
148 QualType BaseTy = BaseExpr->getType();
149 BaseQuals = BaseTy.getQualifiers();
150 }
151
152 switch (DestroyedType.getObjCLifetime()) {
156 break;
157
160 DestroyedType.isVolatileQualified()),
162 break;
163
165 EmitARCDestroyWeak(BaseValue);
166 break;
167 }
168 } else {
169 // C++ [expr.pseudo]p1:
170 // The result shall only be used as the operand for the function call
171 // operator (), and the result of such a call has type void. The only
172 // effect is the evaluation of the postfix-expression before the dot or
173 // arrow.
174 EmitIgnoredExpr(E->getBase());
175 }
176
177 return RValue::get(nullptr);
178}
179
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());
186}
187
188// Note: This function also emit constructor calls to support a MSVC
189// extensions allowing explicit constructor function call.
191 ReturnValueSlot ReturnValue,
192 llvm::CallBase **CallOrInvoke) {
193 const Expr *callee = CE->getCallee()->IgnoreParens();
194
195 if (isa<BinaryOperator>(callee))
196 return EmitCXXMemberPointerCallExpr(CE, ReturnValue, CallOrInvoke);
197
198 const MemberExpr *ME = cast<MemberExpr>(callee);
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
200
201 if (MD->isStatic()) {
202 // The method is static, emit it as we would a regular call.
203 CGCallee callee =
205 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
206 ReturnValue, /*Chain=*/nullptr, CallOrInvoke);
207 }
208
209 bool HasQualifier = ME->hasQualifier();
210 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
211 bool IsArrow = ME->isArrow();
212 const Expr *Base = ME->getBase();
213
215 HasQualifier, Qualifier, IsArrow,
216 Base, CallOrInvoke);
217}
218
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));
224
225 // Compute the object pointer.
226 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
227
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() !=
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.
247 Base = Inner;
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;
254 }
255 }
256
257 bool TrivialForCodegen =
258 MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
259 bool TrivialAssignment =
260 TrivialForCodegen &&
263
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));
273 } else {
274 RtlArgs = &RtlArgStorage;
275 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
276 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
277 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
278 }
279 }
280 }
281
282 LValue This;
283 if (IsArrow) {
284 LValueBaseInfo BaseInfo;
285 TBAAAccessInfo TBAAInfo;
286 Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
287 This = MakeAddrLValue(ThisValue, Base->getType()->getPointeeType(),
288 BaseInfo, TBAAInfo);
289 } else {
291 }
292
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.
296 assert(!RtlArgs);
297 assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
298 CallArgList Args;
300 *this, {Ctor, Ctor_Complete}, This.getPointer(*this),
301 /*ImplicitParam=*/nullptr,
302 /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
303
304 EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
305 /*Delegating=*/false, This.getAddress(), Args,
307 /*NewPointerIsChecked=*/false, CallOrInvoke);
308 return RValue::get(nullptr);
309 }
310
311 if (TrivialForCodegen) {
312 if (isa<CXXDestructorDecl>(MD))
313 return RValue::get(nullptr);
314
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
320 // the RHS.
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));
326 }
327
328 assert(MD->getParent()->mayInsertExtraPadding() &&
329 "unknown trivial member function");
330 }
331
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))
339 else
340 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
341
342 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
343
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;
349 if (CE)
350 CallLoc = CE->getExprLoc();
351
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);
360 }
361
364 This.emitRawPointer(*this),
365 C.getRecordType(CalleeDecl->getParent()),
366 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
367
368 // C++ [class.virtual]p12:
369 // Explicit qualification with the scope operator (5.1) suppresses the
370 // virtual call mechanism.
371 //
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;
375
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) {
382 *this, Dtor, Dtor_Complete, This.getAddress(),
383 cast<CXXMemberCallExpr>(CE), CallOrInvoke);
384 } else {
385 GlobalDecl GD(Dtor, Dtor_Complete);
387 if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
388 Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
389 else if (!DevirtualizedMethod)
390 Callee =
391 CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
392 else {
394 }
395
396 QualType ThisTy =
397 IsArrow ? Base->getType()->getPointeeType() : Base->getType();
398 EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
399 /*ImplicitParam=*/nullptr,
400 /*ImplicitParamTy=*/QualType(), CE, CallOrInvoke);
401 }
402 return RValue::get(nullptr);
403 }
404
405 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
406 // 'CalleeDecl' instead.
407
409 if (UseVirtualCall) {
410 Callee = CGCallee::forVirtual(CE, MD, This.getAddress(), Ty);
411 } else {
412 if (SanOpts.has(SanitizerKind::CFINVCall) &&
413 MD->getParent()->isDynamicClass()) {
414 llvm::Value *VTable;
415 const CXXRecordDecl *RD;
416 std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
417 *this, This.getAddress(), CalleeDecl->getParent());
419 }
420
421 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
422 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
423 else if (!DevirtualizedMethod)
424 Callee =
426 else {
427 Callee =
428 CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
429 GlobalDecl(DevirtualizedMethod));
430 }
431 }
432
433 if (MD->isVirtual()) {
434 Address NewThisAddr =
436 *this, CalleeDecl, This.getAddress(), UseVirtualCall);
437 This.setAddress(NewThisAddr);
438 }
439
441 CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
442 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs, CallOrInvoke);
443}
444
445RValue
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();
453
454 const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
455 const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
456 const auto *RD =
457 cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
458
459 // Emit the 'this' pointer.
461 if (BO->getOpcode() == BO_PtrMemI)
462 This = EmitPointerWithAlignment(BaseExpr, nullptr, nullptr, KnownNonNull);
463 else
464 This = EmitLValue(BaseExpr, KnownNonNull).getAddress();
465
466 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.emitRawPointer(*this),
467 QualType(MPT->getClass(), 0));
468
469 // Get the member function pointer.
470 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
471
472 // Ask the ABI to load the callee. Note that This is modified.
473 llvm::Value *ThisPtrForCall = nullptr;
476 ThisPtrForCall, MemFnPtr, MPT);
477
478 CallArgList Args;
479
480 QualType ThisType =
481 getContext().getPointerType(getContext().getTagDeclType(RD));
482
483 // Push the this ptr.
484 Args.add(RValue::get(ThisPtrForCall), ThisType);
485
487
488 // And the rest of the call args
489 EmitCallArgs(Args, FPT, E->arguments());
490 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
491 /*PrefixSize=*/0),
492 Callee, ReturnValue, Args, CallOrInvoke, E == MustTailCall,
493 E->getExprLoc());
494}
495
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!");
502 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
503 /*IsArrow=*/false, E->getArg(0), CallOrInvoke);
504}
505
507 ReturnValueSlot ReturnValue,
508 llvm::CallBase **CallOrInvoke) {
510 CallOrInvoke);
511}
512
514 Address DestPtr,
515 const CXXRecordDecl *Base) {
516 if (Base->isEmpty())
517 return;
518
519 DestPtr = DestPtr.withElementType(CGF.Int8Ty);
520
521 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
522 CharUnits NVSize = Layout.getNonVirtualSize();
523
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
526 // constructor.
528 Stores.emplace_back(CharUnits::Zero(), NVSize);
529
530 // Each store is split by the existence of a vbptr.
531 CharUnits VBPtrWidth = CGF.getPointerSize();
532 std::vector<CharUnits> VBPtrOffsets =
534 for (CharUnits VBPtrOffset : VBPtrOffsets) {
535 // Stop before we hit any virtual base pointers located in virtual bases.
536 if (VBPtrOffset >= NVSize)
537 break;
538 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
539 CharUnits LastStoreOffset = LastStore.first;
540 CharUnits LastStoreSize = LastStore.second;
541
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);
547
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);
553 }
554
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());
567
568 CharUnits Align =
569 std::max(Layout.getNonVirtualAlignment(), DestPtr.getAlignment());
570 NullVariable->setAlignment(Align.getAsAlign());
571
572 Address SrcPtr(NullVariable, CGF.Int8Ty, Align);
573
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);
580 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
581 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
582 StoreSizeVal);
583 }
584
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.
588 } else {
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);
594 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
595 CGF.Builder.getInt8(0), StoreSizeVal);
596 }
597 }
598}
599
600void
602 AggValueSlot Dest) {
603 assert(!Dest.isIgnored() && "Must have a destination!");
604 const CXXConstructorDecl *CD = E->getConstructor();
605
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
609 // already zeroed.
610 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
611 switch (E->getConstructionKind()) {
615 break;
619 CD->getParent());
620 break;
621 }
622 }
623
624 // If this is a call to a trivial default constructor, do nothing.
625 if (CD->isTrivial() && CD->isDefaultConstructor())
626 return;
627
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()));
637 assert(
638 getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
639 EmitAggExpr(SrcObj, Dest);
640 return;
641 }
642
643 if (const ArrayType *arrayType
644 = getContext().getAsArrayType(E->getType())) {
646 Dest.isSanitizerChecked());
647 } else {
649 bool ForVirtualBase = false;
650 bool Delegating = false;
651
652 switch (E->getConstructionKind()) {
654 // We should be emitting a constructor; GlobalDecl will assert this
656 Delegating = true;
657 break;
658
661 break;
662
664 ForVirtualBase = true;
665 [[fallthrough]];
666
668 Type = Ctor_Base;
669 }
670
671 // Call the constructor.
672 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
673 }
674}
675
677 const Expr *Exp) {
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);
685
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())
692
693 assert(!getContext().getAsConstantArrayType(E->getType())
694 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
695 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
696}
697
699 const CXXNewExpr *E) {
700 if (!E->isArray())
701 return CharUnits::Zero();
702
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();
707
708 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
709}
710
711static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
712 const CXXNewExpr *e,
713 unsigned minElements,
714 llvm::Value *&numElements,
715 llvm::Value *&sizeWithoutCookie) {
717
718 if (!e->isArray()) {
720 sizeWithoutCookie
721 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
722 return sizeWithoutCookie;
723 }
724
725 // The width of size_t.
726 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
727
728 // Figure out the cookie size.
729 llvm::APInt cookieSize(sizeWidth,
730 CalculateCookiePadding(CGF, e).getQuantity());
731
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.
735 numElements =
737 if (!numElements)
738 numElements = CGF.EmitScalarExpr(*e->getArraySize());
739 assert(isa<llvm::IntegerType>(numElements->getType()));
740
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.
747 bool isSigned
748 = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
749 llvm::IntegerType *numElementsType
750 = cast<llvm::IntegerType>(numElements->getType());
751 unsigned numElementsWidth = numElementsType->getBitWidth();
752
753 // Compute the constant factor.
754 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
755 while (const ConstantArrayType *CAT
757 type = CAT->getElementType();
758 arraySizeMultiplier *= CAT->getSize();
759 }
760
762 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
763 typeSizeMultiplier *= arraySizeMultiplier;
764
765 // This will be a size_t.
766 llvm::Value *size;
767
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();
773
774 bool hasAnyOverflow = false;
775
776 // If 'count' was a negative number, it's an overflow.
777 if (isSigned && count.isNegative())
778 hasAnyOverflow = true;
779
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,
782 // overflow.
783 else if (numElementsWidth > sizeWidth &&
784 numElementsWidth - sizeWidth > count.countl_zero())
785 hasAnyOverflow = true;
786
787 // Okay, compute a count at the right width.
788 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
789
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;
794
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);
800
801 // Compute the size before cookie, and track whether it overflowed.
802 bool overflow;
803 llvm::APInt allocationSize
804 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
805 hasAnyOverflow |= overflow;
806
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);
812
813 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
814 hasAnyOverflow |= overflow;
815 }
816
817 // On overflow, produce a -1 so operator new will fail.
818 if (hasAnyOverflow) {
819 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
820 } else {
821 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
822 }
823
824 // Otherwise, we might need to use the overflow intrinsics.
825 } else {
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
831 // than that.
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.
838
839 llvm::Value *hasOverflow = nullptr;
840
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);
847
848 llvm::Value *thresholdV
849 = llvm::ConstantInt::get(numElementsType, threshold);
850
851 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
852 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
853
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);
858
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));
867
868 // Otherwise, zext up to size_t if necessary.
869 } else if (numElementsWidth < sizeWidth) {
870 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
871 }
872
873 assert(numElements->getType() == CGF.SizeTy);
874
875 if (minElements) {
876 // Don't allow allocation of fewer elements than we have initializers.
877 if (!hasOverflow) {
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)));
887 }
888 }
889
890 size = numElements;
891
892 // Multiply by the type size if necessary. This multiplier
893 // includes all the factors for nested arrays.
894 //
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
898 // allocation fails.
899 if (typeSizeMultiplier != 1) {
900 llvm::Function *umul_with_overflow
901 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
902
903 llvm::Value *tsmV =
904 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
905 llvm::Value *result =
906 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
907
908 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
909 if (hasOverflow)
910 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
911 else
912 hasOverflow = overflowed;
913
914 size = CGF.Builder.CreateExtractValue(result, 0);
915
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);
922 numElements = size;
923
924 // Otherwise we need a separate multiply.
925 } else {
926 llvm::Value *asmV =
927 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
928 numElements = CGF.Builder.CreateMul(numElements, asmV);
929 }
930 }
931 } else {
932 // numElements doesn't need to be scaled.
933 assert(arraySizeMultiplier == 1);
934 }
935
936 // Add in the cookie size if necessary.
937 if (cookieSize != 0) {
938 sizeWithoutCookie = size;
939
940 llvm::Function *uadd_with_overflow
941 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
942
943 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
944 llvm::Value *result =
945 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
946
947 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
948 if (hasOverflow)
949 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
950 else
951 hasOverflow = overflowed;
952
953 size = CGF.Builder.CreateExtractValue(result, 0);
954 }
955
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.
959 if (hasOverflow)
960 size = CGF.Builder.CreateSelect(hasOverflow,
961 llvm::Constant::getAllOnesValue(CGF.SizeTy),
962 size);
963 }
964
965 if (cookieSize == 0)
966 sizeWithoutCookie = size;
967 else
968 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
969
970 return size;
971}
972
974 QualType AllocType, Address NewPtr,
975 AggValueSlot::Overlap_t MayOverlap) {
976 // FIXME: Refactor with EmitExprAsInit.
977 switch (CGF.getEvaluationKind(AllocType)) {
978 case TEK_Scalar:
979 CGF.EmitScalarInit(Init, nullptr,
980 CGF.MakeAddrLValue(NewPtr, AllocType), false);
981 return;
982 case TEK_Complex:
983 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
984 /*isInit*/ true);
985 return;
986 case TEK_Aggregate: {
987 AggValueSlot Slot
988 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
992 MayOverlap, AggValueSlot::IsNotZeroed,
994 CGF.EmitAggExpr(Init, Slot);
995 return;
996 }
997 }
998 llvm_unreachable("bad evaluation kind");
999}
1000
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())
1008 return;
1009
1010 Address CurPtr = BeginPtr;
1011
1012 unsigned InitListElements = 0;
1013
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;
1019
1020 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
1021 CharUnits ElementAlign =
1022 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
1023
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))
1029 return false;
1030
1031 // Optimization: since zero initialization will just set the memory
1032 // to all zeroes, generate a single memset to do it in one shot.
1033
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() *
1041 InitListElements);
1042 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1043 }
1044
1045 // Create the memset.
1046 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1047 return true;
1048 };
1049
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;
1055 if (!ILE) {
1056 IgnoreParen = Init->IgnoreParenImpCasts();
1057 CPLIE = dyn_cast<CXXParenListInitExpr>(IgnoreParen);
1058 SL = dyn_cast<StringLiteral>(IgnoreParen);
1059 OCEE = dyn_cast<ObjCEncodeExpr>(IgnoreParen);
1060 }
1061
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) {
1067 if (!ILE)
1068 Init = IgnoreParen;
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.
1072 AggValueSlot Slot =
1073 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1080 EmitAggExpr(ILE ? ILE->getInit(0) : Init, Slot);
1081
1082 // Move past these elements.
1083 InitListElements =
1084 cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1085 ->getZExtSize();
1087 CurPtr, InitListElements, "string.init.end");
1088
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();
1093 (void)OK;
1094 assert(OK && "couldn't memset character type?");
1095 }
1096 return;
1097 }
1098
1099 ArrayRef<const Expr *> InitExprs =
1100 ILE ? ILE->inits() : CPLIE->getInitExprs();
1101 InitListElements = InitExprs.size();
1102
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);
1111 }
1112
1113 // Enter a partial-destruction Cleanup if necessary.
1114 if (DtorKind) {
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
1119 // alloca.
1120 llvm::Instruction *DominatingIP =
1121 Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));
1122 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1123 "array.init.end");
1125 EndOfInit, ElementType, ElementAlign,
1126 getDestroyer(DtorKind));
1127 cast<EHCleanupScope>(*EHStack.find(EHStack.stable_begin()))
1128 .AddAuxAllocas(AllocaTracker.Take());
1130 {EHStack.stable_begin(), DominatingIP});
1131 pushedCleanup = true;
1132 }
1133
1134 CharUnits StartAlign = CurPtr.getAlignment();
1135 unsigned i = 0;
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);
1142 }
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,
1149 CurPtr.emitRawPointer(*this),
1150 Builder.getSize(1),
1151 "array.exp.next"),
1152 CurPtr.getElementType(),
1153 StartAlign.alignmentAtOffset((++i) * ElementSize));
1154 }
1155
1156 // The remaining elements are filled with the array filler expression.
1157 Init = ILE ? ILE->getArrayFiller() : CPLIE->getArrayFiller();
1158
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);
1164 if (!SubILE)
1165 break;
1166 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1167 Init = SubILE->getArrayFiller();
1168 }
1169
1170 // Switch back to initializing one base element at a time.
1171 CurPtr = CurPtr.withElementType(BeginPtr.getElementType());
1172 }
1173
1174 // If all elements have already been initialized, skip any further
1175 // initialization.
1176 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1177 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1178 return;
1179 }
1180
1181 assert(Init && "have trailing elements to initialize but no initializer");
1182
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())
1191 return;
1192
1193 if (TryMemsetInitialization())
1194 return;
1195 }
1196
1197 // Store the new Cleanup position for irregular Cleanups.
1198 //
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);
1203
1204 // Emit a constructor call loop to initialize the remaining elements.
1205 if (InitListElements)
1206 NumElements = Builder.CreateSub(
1207 NumElements,
1208 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1209 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1210 /*NewPointerIsChecked*/true,
1211 CCE->requiresZeroInitialization());
1212 return;
1213 }
1214
1215 // If this is value-initialization, we can usually use memset.
1216 ImplicitValueInitExpr IVIE(ElementType);
1217 if (isa<ImplicitValueInitExpr>(Init)) {
1218 if (TryMemsetInitialization())
1219 return;
1220
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.
1224 Init = &IVIE;
1225 }
1226
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");
1231
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())
1235 return;
1236
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())
1247 ++NumElements;
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)))
1252 --NumElements;
1253 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1254 return;
1255 }
1256 }
1257 }
1258
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");
1263
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,
1267 "array.end");
1268
1269 // If the number of elements isn't constant, we have to now check if there is
1270 // anything left to initialize.
1271 if (!ConstNum) {
1272 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr.emitRawPointer(*this),
1273 EndPtr, "array.isempty");
1274 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1275 }
1276
1277 // Enter the loop.
1278 EmitBlock(LoopBB);
1279
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);
1284
1285 CurPtr = Address(CurPtrPhi, CurPtr.getElementType(), ElementAlign);
1286
1287 // Store the new Cleanup position for irregular Cleanups.
1288 if (EndOfInit.isValid())
1289 Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
1290
1291 // Enter a partial-destruction Cleanup if necessary.
1292 if (!pushedCleanup && needsEHCleanup(DtorKind)) {
1293 llvm::Instruction *DominatingIP =
1294 Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));
1296 CurPtr.emitRawPointer(*this), ElementType,
1297 ElementAlign, getDestroyer(DtorKind));
1299 {EHStack.stable_begin(), DominatingIP});
1300 }
1301
1302 // Emit the initializer into this element.
1303 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1305
1306 // Leave the Cleanup if we entered one.
1307 deactivation.ForceDeactivate();
1308
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");
1312
1313 // Check whether we've gotten to the end of the array and, if so,
1314 // exit the loop.
1315 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1316 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1317 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1318
1319 EmitBlock(ContBB);
1320}
1321
1323 QualType ElementType, llvm::Type *ElementTy,
1324 Address NewPtr, llvm::Value *NumElements,
1325 llvm::Value *AllocSizeWithoutCookie) {
1326 ApplyDebugLocation DL(CGF, E);
1327 if (E->isArray())
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,
1333}
1334
1335/// Emit a call to an operator new or operator delete function, as implicitly
1336/// created by new-expressions and delete-expressions.
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));
1344 RValue RV =
1346 Args, CalleeType, /*ChainCall=*/false),
1347 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1348
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.
1352 ///
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);
1358 }
1359
1360 return RV;
1361}
1362
1364 const CallExpr *TheCall,
1365 bool IsDelete) {
1366 CallArgList Args;
1367 EmitCallArgs(Args, Type, TheCall->arguments());
1368 // Find the allocation or deallocation function that we're calling.
1369 ASTContext &Ctx = getContext();
1371 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1372
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");
1378}
1379
1380namespace {
1381/// The parameters to pass to a usual operator delete.
1382struct UsualDeleteParams {
1383 bool DestroyingDelete = false;
1384 bool Size = false;
1385 bool Alignment = false;
1386};
1387}
1388
1389static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1390 UsualDeleteParams Params;
1391
1392 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1393 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1394
1395 // The first argument is always a void*.
1396 ++AI;
1397
1398 // The next parameter may be a std::destroying_delete_t.
1399 if (FD->isDestroyingOperatorDelete()) {
1400 Params.DestroyingDelete = true;
1401 assert(AI != AE);
1402 ++AI;
1403 }
1404
1405 // Figure out what other parameters we should be implicitly passing.
1406 if (AI != AE && (*AI)->isIntegerType()) {
1407 Params.Size = true;
1408 ++AI;
1409 }
1410
1411 if (AI != AE && (*AI)->isAlignValT()) {
1412 Params.Alignment = true;
1413 ++AI;
1414 }
1415
1416 assert(AI == AE && "unexpected usual deallocation function parameter");
1417 return Params;
1418}
1419
1420namespace {
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 {
1431 RValueTy ArgValue;
1432 QualType ArgType;
1433 };
1434
1435 unsigned NumPlacementArgs : 31;
1436 LLVM_PREFERRED_TYPE(bool)
1437 unsigned PassAlignmentToPlacementDelete : 1;
1438 const FunctionDecl *OperatorDelete;
1439 ValueTy Ptr;
1440 ValueTy AllocSize;
1441 CharUnits AllocAlign;
1442
1443 PlacementArg *getPlacementArgs() {
1444 return reinterpret_cast<PlacementArg *>(this + 1);
1445 }
1446
1447 public:
1448 static size_t getExtraSize(size_t NumPlacementArgs) {
1449 return NumPlacementArgs * sizeof(PlacementArg);
1450 }
1451
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) {}
1460
1461 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1462 assert(I < NumPlacementArgs && "index out of range");
1463 getPlacementArgs()[I] = {Arg, Type};
1464 }
1465
1466 void Emit(CodeGenFunction &CGF, Flags flags) override {
1467 const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1468 CallArgList DeleteArgs;
1469
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));
1473
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;
1480 } else {
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);
1484 }
1485
1486 assert(!Params.DestroyingDelete &&
1487 "should not call destroying delete in a new-expression");
1488
1489 // The second argument can be a std::size_t (for non-placement delete).
1490 if (Params.Size)
1491 DeleteArgs.add(Traits::get(CGF, AllocSize),
1492 CGF.getContext().getSizeType());
1493
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());
1502
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);
1507 }
1508
1509 // Call 'operator delete'.
1510 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1511 }
1512 };
1513}
1514
1515/// Enter a cleanup to call 'operator delete' if the initializer in a
1516/// new-expression throws.
1518 const CXXNewExpr *E,
1519 Address NewPtr,
1520 llvm::Value *AllocSize,
1521 CharUnits AllocAlign,
1522 const CallArgList &NewArgs) {
1523 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1524
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; }
1533 };
1534
1535 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1536
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);
1543 }
1544
1545 return;
1546 }
1547
1548 // Otherwise, we need to save all this stuff.
1550 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr, CGF));
1553
1554 struct ConditionalCleanupTraits {
1556 typedef DominatingValue<RValue>::saved_type RValueTy;
1557 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1558 return V.restore(CGF);
1559 }
1560 };
1561 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1562
1563 ConditionalCleanup *Cleanup = CGF.EHStack
1564 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1565 E->getNumPlacementArgs(),
1566 E->getOperatorDelete(),
1567 SavedNewPtr,
1568 SavedAllocSize,
1569 E->passAlignment(),
1570 AllocAlign);
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);
1575 }
1576
1577 CGF.initFullExprCleanup();
1578}
1579
1580llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1581 // The element type being allocated.
1582 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1583
1584 // 1. Build a call to the allocation function.
1585 FunctionDecl *allocator = E->getOperatorNew();
1586
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)) {
1597 minElements =
1598 cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1599 ->getZExtSize();
1600 } else if (ILE || CPLIE) {
1601 minElements = ILE ? ILE->getNumInits() : CPLIE->getInitExprs().size();
1602 }
1603 }
1604
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);
1611
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();
1619
1620 LValueBaseInfo BaseInfo;
1621 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1622
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);
1628
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());
1635 }
1636
1637 } else {
1638 const FunctionProtoType *allocatorType =
1639 allocator->getType()->castAs<FunctionProtoType>();
1640 unsigned ParamsToSkip = 0;
1641
1642 // The allocation size is the first argument.
1643 QualType sizeType = getContext().getSizeType();
1644 allocatorArgs.add(RValue::get(allocSize), sizeType);
1645 ++ParamsToSkip;
1646
1647 if (allocSize != allocSizeWithoutCookie) {
1648 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1649 allocAlign = std::max(allocAlign, cookieAlign);
1650 }
1651
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(),
1659 sizeType) &&
1660 "wrong type for alignment parameter");
1661 ++ParamsToSkip;
1662 } else {
1663 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1664 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1665 }
1666 allocatorArgs.add(
1667 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1668 AlignValT);
1669 }
1670
1671 // FIXME: Why do we not pass a CalleeDecl here?
1672 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1673 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1674
1675 RValue RV =
1676 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1677
1678 // Set !heapallocsite metadata on the call to operator new.
1679 if (getDebugInfo())
1680 if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
1681 getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
1682 E->getExprLoc());
1683
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() &&
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));
1695 }
1696
1697 allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);
1698 }
1699
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() ||
1707
1708 llvm::BasicBlock *nullCheckBB = nullptr;
1709 llvm::BasicBlock *contBB = nullptr;
1710
1711 // The null-check means that the initializer is conditionally
1712 // evaluated.
1713 ConditionalEvaluation conditional(*this);
1714
1715 if (nullCheck) {
1716 conditional.begin(*this);
1717
1718 nullCheckBB = Builder.GetInsertBlock();
1719 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1720 contBB = createBasicBlock("new.cont");
1721
1722 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1723 Builder.CreateCondBr(isNull, contBB, notNullBB);
1724 EmitBlock(notNullBB);
1725 }
1726
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,
1734 allocatorArgs);
1735 operatorDeleteCleanup = EHStack.stable_begin();
1736 cleanupDominator = Builder.CreateUnreachable();
1737 }
1738
1739 assert((allocSize == allocSizeWithoutCookie) ==
1740 CalculateCookiePadding(*this, E).isZero());
1741 if (allocSize != allocSizeWithoutCookie) {
1742 assert(E->isArray());
1743 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1744 numElements,
1745 E, allocType);
1746 }
1747
1748 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1749 Address result = allocation.withElementType(elementTy);
1750
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 &&
1757 result = Builder.CreateLaunderInvariantGroup(result);
1758
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);
1767 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1768 result, allocType, result.getAlignment(), SkippedChecks,
1769 numElements);
1770
1771 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1772 allocSizeWithoutCookie);
1773 llvm::Value *resultPtr = result.emitRawPointer(*this);
1774
1775 // Deactivate the 'operator delete' cleanup if we finished
1776 // initialization.
1777 if (operatorDeleteCleanup.isValid()) {
1778 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1779 cleanupDominator->eraseFromParent();
1780 }
1781
1782 if (nullCheck) {
1783 conditional.end(*this);
1784
1785 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1786 EmitBlock(contBB);
1787
1788 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1789 PHI->addIncoming(resultPtr, notNullBB);
1790 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1791 nullCheckBB);
1792
1793 resultPtr = PHI;
1794 }
1795
1796 return resultPtr;
1797}
1798
1800 llvm::Value *DeletePtr, QualType DeleteTy,
1801 llvm::Value *NumElements,
1802 CharUnits CookieSize) {
1803 assert((!NumElements && CookieSize.isZero()) ||
1804 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1805
1806 const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
1807 CallArgList DeleteArgs;
1808
1809 auto Params = getUsualDeleteParams(DeleteFD);
1810 auto ParamTypeIt = DeleteFTy->param_type_begin();
1811
1812 // Pass the pointer itself.
1813 QualType ArgTy = *ParamTypeIt++;
1814 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1815
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());
1824 DeleteArgs.add(
1825 RValue::getAggregate(Address(DestroyingDeleteTag, Ty, Align)), DDTag);
1826 }
1827
1828 // Pass the size if the delete function has a size_t parameter.
1829 if (Params.Size) {
1830 QualType SizeType = *ParamTypeIt++;
1831 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1832 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1833 DeleteTypeSize.getQuantity());
1834
1835 // For array new, multiply by the number of elements.
1836 if (NumElements)
1837 Size = Builder.CreateMul(Size, NumElements);
1838
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()));
1843
1844 DeleteArgs.add(RValue::get(Size), SizeType);
1845 }
1846
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);
1856 }
1857
1858 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1859 "unknown parameter to usual delete function");
1860
1861 // Emit the call to delete.
1862 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1863
1864 // If call argument lowering didn't use the destroying_delete_t alloca,
1865 // remove it again.
1866 if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1867 DestroyingDeleteTag->eraseFromParent();
1868}
1869
1870namespace {
1871 /// Calls the given 'operator delete' on a single object.
1872 struct CallObjectDelete final : EHScopeStack::Cleanup {
1873 llvm::Value *Ptr;
1874 const FunctionDecl *OperatorDelete;
1875 QualType ElementType;
1876
1877 CallObjectDelete(llvm::Value *Ptr,
1878 const FunctionDecl *OperatorDelete,
1879 QualType ElementType)
1880 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1881
1882 void Emit(CodeGenFunction &CGF, Flags flags) override {
1883 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1884 }
1885 };
1886}
1887
1888void
1890 llvm::Value *CompletePtr,
1891 QualType ElementType) {
1892 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1893 OperatorDelete, ElementType);
1894}
1895
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.
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,
1906 Dtor);
1907 else
1909 ElementType);
1910}
1911
1912/// Emit the code for deleting a single object.
1913/// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1914/// if not.
1916 const CXXDeleteExpr *DE,
1917 Address Ptr,
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.
1926 ElementType);
1927
1928 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1929 assert(!OperatorDelete->isDestroyingOperatorDelete());
1930
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();
1938
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>(
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;
1953 } else {
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;
1960 }
1961 }
1962 if (UseVirtualCall) {
1963 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1964 Dtor);
1965 return false;
1966 }
1967 }
1968 }
1969 }
1970
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);
1976
1977 if (Dtor)
1979 /*ForVirtualBase=*/false,
1980 /*Delegating=*/false,
1981 Ptr, ElementType);
1982 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1983 switch (Lifetime) {
1987 break;
1988
1991 break;
1992
1994 CGF.EmitARCDestroyWeak(Ptr);
1995 break;
1996 }
1997 }
1998
1999 // When optimizing for size, call 'operator delete' unconditionally.
2000 if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
2001 CGF.EmitBlock(UnconditionalDeleteBlock);
2002 CGF.PopCleanupBlock();
2003 return true;
2004 }
2005
2006 CGF.PopCleanupBlock();
2007 return false;
2008}
2009
2010namespace {
2011 /// Calls the given 'operator delete' on an array of objects.
2012 struct CallArrayDelete final : EHScopeStack::Cleanup {
2013 llvm::Value *Ptr;
2014 const FunctionDecl *OperatorDelete;
2015 llvm::Value *NumElements;
2016 QualType ElementType;
2017 CharUnits CookieSize;
2018
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) {}
2026
2027 void Emit(CodeGenFunction &CGF, Flags flags) override {
2028 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
2029 CookieSize);
2030 }
2031 };
2032}
2033
2034/// Emit the code for deleting an array of objects.
2036 const CXXDeleteExpr *E,
2037 Address deletedPtr,
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);
2044
2045 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
2046
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,
2052 cookieSize);
2053
2054 // Destroy the elements.
2055 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2056 assert(numElements && "no element count for a type with a destructor!");
2057
2058 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2059 CharUnits elementAlign =
2060 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2061
2062 llvm::Value *arrayBegin = deletedPtr.emitRawPointer(CGF);
2063 llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2064 deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
2065
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));
2073 }
2074
2075 // Pop the cleanup block.
2076 CGF.PopCleanupBlock();
2077}
2078
2080 const Expr *Arg = E->getArgument();
2082
2083 // Null check the pointer.
2084 //
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");
2092
2093 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
2094
2095 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2096 EmitBlock(DeleteNotNull);
2097 Ptr.setKnownNonNull();
2098
2099 QualType DeleteTy = E->getDestroyedType();
2100
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);
2106 return;
2107 }
2108
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);
2115
2116 GEP.push_back(Zero); // point at the outermost array
2117
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();
2123
2124 // 2. GEP to the first element of the array.
2125 GEP.push_back(Zero);
2126 }
2127
2128 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, ConvertTypeForMem(DeleteTy),
2129 Ptr.getAlignment(), "del.first");
2130 }
2131
2132 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
2133
2134 if (E->isArrayForm()) {
2135 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2136 EmitBlock(DeleteEnd);
2137 } else {
2138 if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
2139 EmitBlock(DeleteEnd);
2140 }
2141}
2142
2143static 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();
2148
2149 QualType SrcRecordTy = E->getType();
2150
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.
2156 ThisPtr, SrcRecordTy);
2157
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
2161 if (HasNullCheck &&
2162 CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(SrcRecordTy)) {
2163 llvm::BasicBlock *BadTypeidBlock =
2164 CGF.createBasicBlock("typeid.bad_typeid");
2165 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2166
2167 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
2168 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2169
2170 CGF.EmitBlock(BadTypeidBlock);
2171 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2172 CGF.EmitBlock(EndBlock);
2173 }
2174
2175 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2176 StdTypeInfoPtrTy);
2177}
2178
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);
2187
2188 auto MaybeASCast = [=](auto &&TypeInfo) {
2189 if (GlobAS == LangAS::Default)
2190 return TypeInfo;
2192 LangAS::Default, PtrTy);
2193 };
2194
2195 if (E->isTypeOperand()) {
2196 llvm::Constant *TypeInfo =
2197 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2198 return MaybeASCast(TypeInfo);
2199 }
2200
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,
2209 E->hasNullCheck());
2210
2211 QualType OperandTy = E->getExprOperand()->getType();
2212 return MaybeASCast(CGM.GetAddrOfRTTIDescriptor(OperandTy));
2213}
2214
2216 QualType DestTy) {
2217 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2218 if (DestTy->isPointerType())
2219 return llvm::Constant::getNullValue(DestLTy);
2220
2221 /// C++ [expr.dynamic.cast]p9:
2222 /// A failed cast to reference type throws std::bad_cast
2223 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2224 return nullptr;
2225
2226 CGF.Builder.ClearInsertionPoint();
2227 return llvm::PoisonValue::get(DestLTy);
2228}
2229
2230llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2231 const CXXDynamicCastExpr *DCE) {
2232 CGM.EmitExplicitCastExprType(DCE, this);
2233 QualType DestTy = DCE->getTypeAsWritten();
2234
2235 QualType SrcTy = DCE->getSubExpr()->getType();
2236
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();
2245 // No DestRecordTy.
2246 } else if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
2247 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2248 DestRecordTy = DestPTy->getPointeeType();
2249 } else {
2250 SrcRecordTy = SrcTy;
2251 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2252 }
2253
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);
2260
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"));
2266 return T;
2267 }
2268 }
2269
2270 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2271
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() &&
2278
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 =
2284 SrcTy->isPointerType(), SrcRecordTy);
2285
2286 llvm::BasicBlock *CastNull = nullptr;
2287 llvm::BasicBlock *CastNotNull = nullptr;
2288 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2289
2290 if (ShouldNullCheckSrcValue) {
2291 CastNull = createBasicBlock("dynamic_cast.null");
2292 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2293
2294 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr);
2295 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2296 EmitBlock(CastNotNull);
2297 }
2298
2299 llvm::Value *Value;
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.
2306 *this, ThisAddr, SrcRecordTy, DestTy, DestRecordTy, CastEnd, CastNull);
2307 } else {
2308 assert(DestRecordTy->isRecordType() &&
2309 "destination type must be a record type!");
2310 Value = CGM.getCXXABI().emitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2311 DestTy, DestRecordTy, CastEnd);
2312 }
2313 CastNotNull = Builder.GetInsertBlock();
2314
2315 llvm::Value *NullValue = nullptr;
2316 if (ShouldNullCheckSrcValue) {
2317 EmitBranch(CastEnd);
2318
2319 EmitBlock(CastNull);
2320 NullValue = EmitDynamicCastToNull(*this, DestTy);
2321 CastNull = Builder.GetInsertBlock();
2322
2323 EmitBranch(CastEnd);
2324 }
2325
2326 EmitBlock(CastEnd);
2327
2328 if (CastNull) {
2329 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2330 PHI->addIncoming(Value, CastNotNull);
2331 PHI->addIncoming(NullValue, CastNull);
2332
2333 Value = PHI;
2334 }
2335
2336 return Value;
2337}
#define V(N, I)
Definition: ASTContext.h:3443
static MemberCallInfo commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args, CallArgList *RtlArgs)
Definition: CGExprCXX.cpp:36
static llvm::Value * EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, llvm::Type *StdTypeInfoPtrTy, bool HasNullCheck)
Definition: CGExprCXX.cpp:2143
static llvm::Value * EmitDynamicCastToNull(CodeGenFunction &CGF, QualType DestTy)
Definition: CGExprCXX.cpp:2215
static RValue EmitNewDeleteCall(CodeGenFunction &CGF, const FunctionDecl *CalleeDecl, const FunctionProtoType *CalleeType, const CallArgList &Args)
Emit a call to an operator new or operator delete function, as implicitly created by new-expressions ...
Definition: CGExprCXX.cpp:1337
static void EmitDestroyingObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType)
Emit the code for deleting a single object with a destroying operator delete.
Definition: CGExprCXX.cpp:1900
static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, Address DestPtr, const CXXRecordDecl *Base)
Definition: CGExprCXX.cpp:513
static void EnterNewDeleteCleanup(CodeGenFunction &CGF, const CXXNewExpr *E, Address NewPtr, llvm::Value *AllocSize, CharUnits AllocAlign, const CallArgList &NewArgs)
Enter a cleanup to call 'operator delete' if the initializer in a new-expression throws.
Definition: CGExprCXX.cpp:1517
static bool EmitObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType, llvm::BasicBlock *UnconditionalDeleteBlock)
Emit the code for deleting a single object.
Definition: CGExprCXX.cpp:1915
static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD)
Definition: CGExprCXX.cpp:1389
static CXXRecordDecl * getCXXRecord(const Expr *E)
Definition: CGExprCXX.cpp:180
static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, const CXXNewExpr *E)
Definition: CGExprCXX.cpp:698
static void EmitArrayDelete(CodeGenFunction &CGF, const CXXDeleteExpr *E, Address deletedPtr, QualType elementType)
Emit the code for deleting an array of objects.
Definition: CGExprCXX.cpp:2035
static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, QualType AllocType, Address NewPtr, AggValueSlot::Overlap_t MayOverlap)
Definition: CGExprCXX.cpp:973
static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, Address NewPtr, llvm::Value *NumElements, llvm::Value *AllocSizeWithoutCookie)
Definition: CGExprCXX.cpp:1322
static llvm::Value * EmitCXXNewAllocSize(CodeGenFunction &CGF, const CXXNewExpr *e, unsigned minElements, llvm::Value *&numElements, llvm::Value *&sizeWithoutCookie)
Definition: CGExprCXX.cpp:711
Expr * E
llvm::MachO::Target Target
Definition: MachO.h:51
static QualType getPointeeType(const MemRegion *R)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
Expr * getLHS() const
Definition: Expr.h:3959
Expr * getRHS() const
Definition: Expr.h:3961
Opcode getOpcode() const
Definition: Expr.h:3954
Represents a call to a CUDA kernel function.
Definition: ExprCXX.h:231
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2845
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2537
Expr * getArgument()
Definition: ExprCXX.h:2539
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:478
bool isAlwaysNull() const
isAlwaysNull - Return whether the result of the dynamic_cast is proven to always be null.
Definition: ExprCXX.cpp:820
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2556
bool isVirtual() const
Definition: DeclCXX.h:2133
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2657
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:2387
CXXMethodDecl * getCorrespondingMethodInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find the method in RD that corresponds to this one.
Definition: DeclCXX.cpp:2333
bool isStatic() const
Definition: DeclCXX.cpp:2280
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2241
bool isArray() const
Definition: ExprCXX.h:2349
QualType getAllocatedType() const
Definition: ExprCXX.h:2319
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition: ExprCXX.h:2354
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4960
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:5000
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2617
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isEffectivelyFinal() const
Determine whether it's impossible for a class to be derived from this class.
Definition: DeclCXX.cpp:2208
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool hasDefinition() const
Definition: DeclCXX.h:572
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2069
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3068
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
arg_iterator arg_begin()
Definition: Expr.h:3121
arg_iterator arg_end()
Definition: Expr.h:3124
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
Expr * getCallee()
Definition: Expr.h:3024
arg_range arguments()
Definition: Expr.h:3116
Expr * getSubExpr()
Definition: Expr.h:3597
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition: CharUnits.h:207
bool isNegative() const
isNegative - Test whether the quantity is less than zero.
Definition: CharUnits.h:131
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition: CharUnits.h:214
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
static Address invalid()
Definition: Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:251
CharUnits getAlignment() const
Definition: Address.h:189
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:207
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
Address setKnownNonNull()
Definition: Address.h:236
void setAlignment(CharUnits Value)
Definition: Address.h:191
bool isValid() const
Definition: Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:199
An aggregate value slot.
Definition: CGValue.h:504
bool isSanitizerChecked() const
Definition: CGValue.h:662
Address getAddress() const
Definition: CGValue.h:644
IsZeroed_t isZeroed() const
Definition: CGValue.h:675
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:587
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:856
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:305
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition: CGBuilder.h:356
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:398
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:158
Address CreateLaunderInvariantGroup(Address Addr)
Definition: CGBuilder.h:437
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:365
llvm::ConstantInt * getSize(CharUnits N)
Definition: CGBuilder.h:99
Address CreateConstInBoundsGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = T* ... produce name = getelementptr inbounds addr, i64 index where i64 is actually the t...
Definition: CGBuilder.h:261
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:346
virtual RValue EmitCUDAKernelCallExpr(CodeGenFunction &CGF, const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
virtual bool shouldEmitExactDynamicCast(QualType DestRecordTy)=0
virtual std::vector< CharUnits > getVBPtrOffsets(const CXXRecordDecl *RD)
Gets the offsets of all the virtual base pointers in a given class.
Definition: CGCXXABI.cpp:342
virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr, const CXXDeleteExpr *expr, QualType ElementType, llvm::Value *&NumElements, llvm::Value *&AllocPtr, CharUnits &CookieSize)
Reads the array cookie associated with the given pointer, if it has one.
Definition: CGCXXABI.cpp:255
virtual bool shouldTypeidBeNullChecked(QualType SrcRecordTy)=0
virtual std::pair< llvm::Value *, const CXXRecordDecl * > LoadVTablePtr(CodeGenFunction &CGF, Address This, const CXXRecordDecl *RD)=0
Load a vtable from This, an object of polymorphic type RD, or from one of its virtual bases if it doe...
virtual Address adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, Address This, bool VirtualCall)
Perform ABI-specific "this" argument adjustment required prior to a call of a virtual function.
Definition: CGCXXABI.h:395
virtual void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType, const CXXDestructorDecl *Dtor)=0
virtual llvm::Value * emitExactDynamicCast(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastSuccess, llvm::BasicBlock *CastFail)=0
Emit a dynamic_cast from SrcRecordTy to DestRecordTy.
virtual const CXXRecordDecl * getThisArgumentTypeForMethod(GlobalDecl GD)
Get the type of the implicit "this" parameter used by a method.
Definition: CGCXXABI.h:387
virtual bool EmitBadCastCall(CodeGenFunction &CGF)=0
virtual llvm::Value * EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, Address ThisPtr, llvm::Type *StdTypeInfoPtrTy)=0
virtual CGCallee EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, Address This, llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr, const MemberPointerType *MPT)
Load a member function from an object and a member function pointer.
Definition: CGCXXABI.cpp:47
virtual llvm::Value * EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke)=0
Emit the ABI-specific virtual destructor call.
virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr)
Returns the extra size required in order to store the array cookie for the given new-expression.
Definition: CGCXXABI.cpp:215
virtual void EmitBadTypeidCall(CodeGenFunction &CGF)=0
virtual llvm::Value * emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy)=0
virtual llvm::Value * emitDynamicCastCall(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd)=0
virtual Address InitializeArrayCookie(CodeGenFunction &CGF, Address NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType)
Initialize the array cookie for the given allocation.
Definition: CGCXXABI.cpp:226
virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, QualType SrcRecordTy)=0
All available information about a concrete callee.
Definition: CGCall.h:63
static CGCallee forVirtual(const CallExpr *CE, GlobalDecl MD, Address Addr, llvm::FunctionType *FTy)
Definition: CGCall.h:147
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:137
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
CGFunctionInfo - Class to encapsulate the information about a function definition.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
void add(RValue rvalue, QualType type)
Definition: CGCall.h:305
void addFrom(const CallArgList &other)
Add all the arguments from another CallArgList to this one.
Definition: CGCall.h:314
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, Address This, Address Src, const CXXConstructExpr *E)
void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, llvm::Value *CompletePtr, QualType ElementType)
void EmitARCDestroyWeak(Address addr)
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
SanitizerSet SanOpts
Sanitizers enabled for this function.
void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, CFITypeCheckKind TCK, SourceLocation Loc)
EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
RValue EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, const CGCallee &Callee, ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *E, CallArgList *RtlArgs, llvm::CallBase **CallOrInvoke)
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp)
void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, const ArrayType *ArrayTy, Address ArrayPtr, const CXXConstructExpr *E, bool NewPointerIsChecked, bool ZeroInitialization=false)
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, const Expr *Base, llvm::CallBase **CallOrInvoke)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, QualType DeleteTy, llvm::Value *NumElements=nullptr, CharUnits CookieSize=CharUnits())
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
const LangOptions & getLangOpts() const
void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, QualType elementType, CharUnits elementAlign, Destroyer *destroyer, bool checkZeroLength, bool useEHCleanup)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
@ TCK_ConstructorCall
Checking the 'this' pointer for a constructor call.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
@ TCK_DynamicOperation
Checking the operand of a dynamic_cast or a typeid expression.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy)
Emit an aggregate assignment.
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, llvm::Type *ElementTy, Address NewPtr, llvm::Value *NumElements, llvm::Value *AllocSizeWithoutCookie)
void initFullExprCleanup()
Set up the last cleanup that was pushed as a conditional full-expression cleanup.
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, const CallExpr *TheCallExpr, bool IsDelete)
void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, AggValueSlot ThisAVS, const CXXConstructExpr *E)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
void EmitCXXDeleteExpr(const CXXDeleteExpr *E)
const TargetCodeGenInfo & getTargetHooks() const
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty)
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
llvm::Type * ConvertType(QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
CodeGenTypes & getTypes() const
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
llvm::Value * EmitCXXNewExpr(const CXXNewExpr *E)
void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise)
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition: CGExpr.cpp:1263
llvm::Module & getModule() const
llvm::Constant * EmitNullConstantForBase(const CXXRecordDecl *Record)
Return a null constant appropriate for zero-initializing a base class with the given type.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CGCXXABI & getCXXABI() const
const CodeGenOptions & getCodeGenOpts() const
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition: CGCall.cpp:307
CanQualType DeriveThisType(const CXXRecordDecl *RD, const CXXMethodDecl *MD)
Derives the 'this' type for codegen purposes, i.e.
Definition: CGCall.cpp:87
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1630
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:701
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments.
Definition: CGCall.cpp:638
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:335
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
A saved depth on the scope stack.
Definition: EHScopeStack.h:101
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
T * pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A)
Push a cleanup with non-constant storage requirements on the stack.
Definition: EHScopeStack.h:317
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition: CGCleanup.h:639
AlignmentSource getAlignmentSource() const
Definition: CGValue.h:171
LValue - This represents an lvalue references.
Definition: CGValue.h:182
Address getAddress() const
Definition: CGValue.h:361
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
static RValue get(llvm::Value *V)
Definition: CGValue.h:98
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition: CGValue.h:125
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:71
A class for recording the number of arguments that a function signature requires.
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:386
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3826
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3474
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3086
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3224
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3480
QualType getReturnType() const
Definition: Decl.h:2720
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3347
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3372
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
param_type_iterator param_type_begin() const
Definition: Type.h:5515
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
param_type_iterator param_type_end() const
Definition: Type.h:5519
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:105
const Decl * getDecl() const
Definition: GlobalDecl.h:103
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5841
Describes an C or C++ initializer list.
Definition: Expr.h:5088
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition: Expr.cpp:2446
unsigned getNumInits() const
Definition: Expr.h:5118
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:5182
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
ArrayRef< Expr * > inits()
Definition: Expr.h:5128
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3333
Expr * getBase() const
Definition: Expr.h:3313
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3347
bool isArrow() const
Definition: Expr.h:3420
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7983
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2641
bool hasStrongOrWeakObjCLifetime() const
Definition: Type.h:1441
The collection of all-type qualifiers we support.
Definition: Type.h:324
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
LangAS getAddressSpace() const
Definition: Type.h:564
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:5166
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Encodes a location in the source.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
bool isUnion() const
Definition: Decl.h:3770
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isConstantArrayType() const
Definition: Type.h:8262
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isPointerType() const
Definition: Type.h:8186
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isAlignValT() const
Definition: Type.cpp:3115
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isRecordType() const
Definition: Type.h:8286
QualType getType() const
Definition: Decl.h:682
QualType getType() const
Definition: Value.cpp:234
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
@ ARCPreciseLifetime
Definition: CGValue.h:136
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2445
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2408
The JSON file list parser is used to communicate input to InstallAPI.
CXXCtorType
C++ constructor types.
Definition: ABI.h:24
@ Ctor_Base
Base object ctor.
Definition: ABI.h:26
@ Ctor_Complete
Complete object ctor.
Definition: ABI.h:25
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
A metaprogramming class for ensuring that a value will dominate an arbitrary position in a function.
Definition: EHScopeStack.h:65
static saved_type save(CodeGenFunction &CGF, type value)
Definition: EHScopeStack.h:59
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:168
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159