Coverage Report

Created: 2024-01-17 10:31

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