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