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