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