Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGExprScalar.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
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 to emit Expr nodes with scalar LLVM types as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGCleanup.h"
15
#include "CGDebugInfo.h"
16
#include "CGObjCRuntime.h"
17
#include "CGOpenMPRuntime.h"
18
#include "CodeGenFunction.h"
19
#include "CodeGenModule.h"
20
#include "ConstantEmitter.h"
21
#include "TargetInfo.h"
22
#include "clang/AST/ASTContext.h"
23
#include "clang/AST/Attr.h"
24
#include "clang/AST/DeclObjC.h"
25
#include "clang/AST/Expr.h"
26
#include "clang/AST/RecordLayout.h"
27
#include "clang/AST/StmtVisitor.h"
28
#include "clang/Basic/CodeGenOptions.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "llvm/ADT/APFixedPoint.h"
31
#include "llvm/ADT/Optional.h"
32
#include "llvm/IR/CFG.h"
33
#include "llvm/IR/Constants.h"
34
#include "llvm/IR/DataLayout.h"
35
#include "llvm/IR/FixedPointBuilder.h"
36
#include "llvm/IR/Function.h"
37
#include "llvm/IR/GetElementPtrTypeIterator.h"
38
#include "llvm/IR/GlobalVariable.h"
39
#include "llvm/IR/Intrinsics.h"
40
#include "llvm/IR/IntrinsicsPowerPC.h"
41
#include "llvm/IR/MatrixBuilder.h"
42
#include "llvm/IR/Module.h"
43
#include <cstdarg>
44
45
using namespace clang;
46
using namespace CodeGen;
47
using llvm::Value;
48
49
//===----------------------------------------------------------------------===//
50
//                         Scalar Expression Emitter
51
//===----------------------------------------------------------------------===//
52
53
namespace {
54
55
/// Determine whether the given binary operation may overflow.
56
/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
57
/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
58
/// the returned overflow check is precise. The returned value is 'true' for
59
/// all other opcodes, to be conservative.
60
bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
61
                             BinaryOperator::Opcode Opcode, bool Signed,
62
90
                             llvm::APInt &Result) {
63
  // Assume overflow is possible, unless we can prove otherwise.
64
90
  bool Overflow = true;
65
90
  const auto &LHSAP = LHS->getValue();
66
90
  const auto &RHSAP = RHS->getValue();
67
90
  if (Opcode == BO_Add) {
68
4
    if (Signed)
69
2
      Result = LHSAP.sadd_ov(RHSAP, Overflow);
70
2
    else
71
2
      Result = LHSAP.uadd_ov(RHSAP, Overflow);
72
86
  } else if (Opcode == BO_Sub) {
73
7
    if (Signed)
74
5
      Result = LHSAP.ssub_ov(RHSAP, Overflow);
75
2
    else
76
2
      Result = LHSAP.usub_ov(RHSAP, Overflow);
77
79
  } else if (Opcode == BO_Mul) {
78
69
    if (Signed)
79
67
      Result = LHSAP.smul_ov(RHSAP, Overflow);
80
2
    else
81
2
      Result = LHSAP.umul_ov(RHSAP, Overflow);
82
69
  } else 
if (10
Opcode == BO_Div10
||
Opcode == BO_Rem5
) {
83
10
    if (Signed && 
!RHS->isZero()6
)
84
4
      Result = LHSAP.sdiv_ov(RHSAP, Overflow);
85
6
    else
86
6
      return false;
87
10
  }
88
84
  return Overflow;
89
90
}
90
91
struct BinOpInfo {
92
  Value *LHS;
93
  Value *RHS;
94
  QualType Ty;  // Computation Type.
95
  BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
96
  FPOptions FPFeatures;
97
  const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
98
99
  /// Check if the binop can result in integer overflow.
100
121
  bool mayHaveIntegerOverflow() const {
101
    // Without constant input, we can't rule out overflow.
102
121
    auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
103
121
    auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
104
121
    if (!LHSCI || 
!RHSCI32
)
105
96
      return true;
106
107
25
    llvm::APInt Result;
108
25
    return ::mayHaveIntegerOverflow(
109
25
        LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
110
121
  }
111
112
  /// Check if the binop computes a division or a remainder.
113
29
  bool isDivremOp() const {
114
29
    return Opcode == BO_Div || 
Opcode == BO_Rem11
||
Opcode == BO_DivAssign1
||
115
29
           
Opcode == BO_RemAssign0
;
116
29
  }
117
118
  /// Check if the binop can result in an integer division by zero.
119
27
  bool mayHaveIntegerDivisionByZero() const {
120
27
    if (isDivremOp())
121
27
      if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
122
12
        return CI->isZero();
123
15
    return true;
124
27
  }
125
126
  /// Check if the binop can result in a float division by zero.
127
2
  bool mayHaveFloatDivisionByZero() const {
128
2
    if (isDivremOp())
129
2
      if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
130
2
        return CFP->isZero();
131
0
    return true;
132
2
  }
133
134
  /// Check if at least one operand is a fixed point type. In such cases, this
135
  /// operation did not follow usual arithmetic conversion and both operands
136
  /// might not be of the same type.
137
184k
  bool isFixedPointOp() const {
138
    // We cannot simply check the result type since comparison operations return
139
    // an int.
140
184k
    if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
141
184k
      QualType LHSType = BinOp->getLHS()->getType();
142
184k
      QualType RHSType = BinOp->getRHS()->getType();
143
184k
      return LHSType->isFixedPointType() || 
RHSType->isFixedPointType()183k
;
144
184k
    }
145
117
    if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
146
117
      return UnOp->getSubExpr()->getType()->isFixedPointType();
147
0
    return false;
148
117
  }
149
};
150
151
16.2k
static bool MustVisitNullValue(const Expr *E) {
152
  // If a null pointer expression's type is the C++0x nullptr_t, then
153
  // it's not necessarily a simple constant and it must be evaluated
154
  // for its potential side effects.
155
16.2k
  return E->getType()->isNullPtrType();
156
16.2k
}
157
158
/// If \p E is a widened promoted integer, get its base (unpromoted) type.
159
static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
160
108
                                                        const Expr *E) {
161
108
  const Expr *Base = E->IgnoreImpCasts();
162
108
  if (E == Base)
163
9
    return llvm::None;
164
165
99
  QualType BaseTy = Base->getType();
166
99
  if (!BaseTy->isPromotableIntegerType() ||
167
99
      
Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType())32
)
168
68
    return llvm::None;
169
170
31
  return BaseTy;
171
99
}
172
173
/// Check if \p E is a widened promoted integer.
174
19
static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
175
19
  return getUnwidenedIntegerType(Ctx, E).hasValue();
176
19
}
177
178
/// Check if we can skip the overflow check for \p Op.
179
98
static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
180
98
  assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
181
98
         "Expected a unary or binary operator");
182
183
  // If the binop has constant inputs and we can prove there is no overflow,
184
  // we can elide the overflow check.
185
98
  if (!Op.mayHaveIntegerOverflow())
186
15
    return true;
187
188
  // If a unary op has a widened operand, the op cannot overflow.
189
83
  if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
190
7
    return !UO->canOverflow();
191
192
  // We usually don't need overflow checks for binops with widened operands.
193
  // Multiplication with promoted unsigned operands is a special case.
194
76
  const auto *BO = cast<BinaryOperator>(Op.E);
195
76
  auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
196
76
  if (!OptionalLHSTy)
197
63
    return false;
198
199
13
  auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
200
13
  if (!OptionalRHSTy)
201
1
    return false;
202
203
12
  QualType LHSTy = *OptionalLHSTy;
204
12
  QualType RHSTy = *OptionalRHSTy;
205
206
  // This is the simple case: binops without unsigned multiplication, and with
207
  // widened operands. No overflow check is needed here.
208
12
  if ((Op.Opcode != BO_Mul && 
Op.Opcode != BO_MulAssign7
) ||
209
12
      
!LHSTy->isUnsignedIntegerType()5
||
!RHSTy->isUnsignedIntegerType()3
)
210
9
    return true;
211
212
  // For unsigned multiplication the overflow check can be elided if either one
213
  // of the unpromoted types are less than half the size of the promoted type.
214
3
  unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
215
3
  return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
216
3
         
(2 * Ctx.getTypeSize(RHSTy)) < PromotedSize2
;
217
12
}
218
219
class ScalarExprEmitter
220
  : public StmtVisitor<ScalarExprEmitter, Value*> {
221
  CodeGenFunction &CGF;
222
  CGBuilderTy &Builder;
223
  bool IgnoreResultAssign;
224
  llvm::LLVMContext &VMContext;
225
public:
226
227
  ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
228
    : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
229
2.35M
      VMContext(cgf.getLLVMContext()) {
230
2.35M
  }
231
232
  //===--------------------------------------------------------------------===//
233
  //                               Utilities
234
  //===--------------------------------------------------------------------===//
235
236
2.76M
  bool TestAndClearIgnoreResultAssign() {
237
2.76M
    bool I = IgnoreResultAssign;
238
2.76M
    IgnoreResultAssign = false;
239
2.76M
    return I;
240
2.76M
  }
241
242
454k
  llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
243
42.2k
  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
244
1.45M
  LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
245
1.45M
    return CGF.EmitCheckedLValue(E, TCK);
246
1.45M
  }
247
248
  void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
249
                      const BinOpInfo &Info);
250
251
1.45M
  Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
252
1.45M
    return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
253
1.45M
  }
254
255
1.75M
  void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
256
1.75M
    const AlignValueAttr *AVAttr = nullptr;
257
1.75M
    if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
258
1.23M
      const ValueDecl *VD = DRE->getDecl();
259
260
1.23M
      if (VD->getType()->isReferenceType()) {
261
5.19k
        if (const auto *TTy =
262
5.19k
            dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
263
655
          AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
264
1.23M
      } else {
265
        // Assumptions for function parameters are emitted at the start of the
266
        // function, so there is no need to repeat that here,
267
        // unless the alignment-assumption sanitizer is enabled,
268
        // then we prefer the assumption over alignment attribute
269
        // on IR function param.
270
1.23M
        if (isa<ParmVarDecl>(VD) && 
!CGF.SanOpts.has(SanitizerKind::Alignment)661k
)
271
661k
          return;
272
273
572k
        AVAttr = VD->getAttr<AlignValueAttr>();
274
572k
      }
275
1.23M
    }
276
277
1.09M
    if (!AVAttr)
278
1.09M
      if (const auto *TTy =
279
1.09M
          dyn_cast<TypedefType>(E->getType()))
280
330k
        AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
281
282
1.09M
    if (!AVAttr)
283
1.09M
      return;
284
285
13
    Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
286
13
    llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
287
13
    CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
288
13
  }
289
290
  /// EmitLoadOfLValue - Given an expression with complex type that represents a
291
  /// value l-value, this method emits the address of the l-value, then loads
292
  /// and returns the result.
293
1.39M
  Value *EmitLoadOfLValue(const Expr *E) {
294
1.39M
    Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
295
1.39M
                                E->getExprLoc());
296
297
1.39M
    EmitLValueAlignmentAssumption(E, V);
298
1.39M
    return V;
299
1.39M
  }
300
301
  /// EmitConversionToBool - Convert the specified expression value to a
302
  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
303
  Value *EmitConversionToBool(Value *Src, QualType DstTy);
304
305
  /// Emit a check that a conversion from a floating-point type does not
306
  /// overflow.
307
  void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
308
                                Value *Src, QualType SrcType, QualType DstType,
309
                                llvm::Type *DstTy, SourceLocation Loc);
310
311
  /// Known implicit conversion check kinds.
312
  /// Keep in sync with the enum of the same name in ubsan_handlers.h
313
  enum ImplicitConversionCheckKind : unsigned char {
314
    ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
315
    ICCK_UnsignedIntegerTruncation = 1,
316
    ICCK_SignedIntegerTruncation = 2,
317
    ICCK_IntegerSignChange = 3,
318
    ICCK_SignedIntegerTruncationOrSignChange = 4,
319
  };
320
321
  /// Emit a check that an [implicit] truncation of an integer  does not
322
  /// discard any bits. It is not UB, so we use the value after truncation.
323
  void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
324
                                  QualType DstType, SourceLocation Loc);
325
326
  /// Emit a check that an [implicit] conversion of an integer does not change
327
  /// the sign of the value. It is not UB, so we use the value after conversion.
328
  /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
329
  void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
330
                                  QualType DstType, SourceLocation Loc);
331
332
  /// Emit a conversion from the specified type to the specified destination
333
  /// type, both of which are LLVM scalar types.
334
  struct ScalarConversionOpts {
335
    bool TreatBooleanAsSigned;
336
    bool EmitImplicitIntegerTruncationChecks;
337
    bool EmitImplicitIntegerSignChangeChecks;
338
339
    ScalarConversionOpts()
340
        : TreatBooleanAsSigned(false),
341
          EmitImplicitIntegerTruncationChecks(false),
342
524k
          EmitImplicitIntegerSignChangeChecks(false) {}
343
344
    ScalarConversionOpts(clang::SanitizerSet SanOpts)
345
        : TreatBooleanAsSigned(false),
346
          EmitImplicitIntegerTruncationChecks(
347
              SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
348
          EmitImplicitIntegerSignChangeChecks(
349
198k
              SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
350
  };
351
  Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
352
                        llvm::Type *SrcTy, llvm::Type *DstTy,
353
                        ScalarConversionOpts Opts);
354
  Value *
355
  EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
356
                       SourceLocation Loc,
357
                       ScalarConversionOpts Opts = ScalarConversionOpts());
358
359
  /// Convert between either a fixed point and other fixed point or fixed point
360
  /// and an integer.
361
  Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
362
                                  SourceLocation Loc);
363
364
  /// Emit a conversion from the specified complex type to the specified
365
  /// destination type, where the destination type is an LLVM scalar type.
366
  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
367
                                       QualType SrcTy, QualType DstTy,
368
                                       SourceLocation Loc);
369
370
  /// EmitNullValue - Emit a value that corresponds to null for the given type.
371
  Value *EmitNullValue(QualType Ty);
372
373
  /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
374
131
  Value *EmitFloatToBoolConversion(Value *V) {
375
    // Compare against 0.0 for fp scalars.
376
131
    llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
377
131
    return Builder.CreateFCmpUNE(V, Zero, "tobool");
378
131
  }
379
380
  /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
381
8.72k
  Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
382
8.72k
    Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
383
384
8.72k
    return Builder.CreateICmpNE(V, Zero, "tobool");
385
8.72k
  }
386
387
85.6k
  Value *EmitIntToBoolConversion(Value *V) {
388
    // Because of the type rules of C, we often end up computing a
389
    // logical value, then zero extending it to int, then wanting it
390
    // as a logical value again.  Optimize this common case.
391
85.6k
    if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
392
2.76k
      if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
393
2.76k
        Value *Result = ZI->getOperand(0);
394
        // If there aren't any more uses, zap the instruction to save space.
395
        // Note that there can be more uses, for example if this
396
        // is the result of an assignment.
397
2.76k
        if (ZI->use_empty())
398
2.76k
          ZI->eraseFromParent();
399
2.76k
        return Result;
400
2.76k
      }
401
2.76k
    }
402
403
82.9k
    return Builder.CreateIsNotNull(V, "tobool");
404
85.6k
  }
405
406
  //===--------------------------------------------------------------------===//
407
  //                            Visitor Methods
408
  //===--------------------------------------------------------------------===//
409
410
5.52M
  Value *Visit(Expr *E) {
411
5.52M
    ApplyDebugLocation DL(CGF, E);
412
5.52M
    return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
413
5.52M
  }
414
415
0
  Value *VisitStmt(Stmt *S) {
416
0
    S->dump(llvm::errs(), CGF.getContext());
417
0
    llvm_unreachable("Stmt can't have complex result type!");
418
0
  }
419
  Value *VisitExpr(Expr *S);
420
421
571
  Value *VisitConstantExpr(ConstantExpr *E) {
422
571
    if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
423
571
      if (E->isGLValue())
424
4
        return CGF.Builder.CreateLoad(Address(
425
4
            Result, CGF.getContext().getTypeAlignInChars(E->getType())));
426
567
      return Result;
427
571
    }
428
0
    return Visit(E->getSubExpr());
429
571
  }
430
324k
  Value *VisitParenExpr(ParenExpr *PE) {
431
324k
    return Visit(PE->getSubExpr());
432
324k
  }
433
9.71k
  Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
434
9.71k
    return Visit(E->getReplacement());
435
9.71k
  }
436
146
  Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
437
146
    return Visit(GE->getResultExpr());
438
146
  }
439
123
  Value *VisitCoawaitExpr(CoawaitExpr *S) {
440
123
    return CGF.EmitCoawaitExpr(*S).getScalarVal();
441
123
  }
442
1
  Value *VisitCoyieldExpr(CoyieldExpr *S) {
443
1
    return CGF.EmitCoyieldExpr(*S).getScalarVal();
444
1
  }
445
0
  Value *VisitUnaryCoawait(const UnaryOperator *E) {
446
0
    return Visit(E->getSubExpr());
447
0
  }
448
449
  // Leaves.
450
539k
  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
451
539k
    return Builder.getInt(E->getValue());
452
539k
  }
453
56
  Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
454
56
    return Builder.getInt(E->getValue());
455
56
  }
456
7.09k
  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
457
7.09k
    return llvm::ConstantFP::get(VMContext, E->getValue());
458
7.09k
  }
459
8.29k
  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
460
8.29k
    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
461
8.29k
  }
462
313
  Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
463
313
    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
464
313
  }
465
2.71k
  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
466
2.71k
    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
467
2.71k
  }
468
2.94k
  Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
469
2.94k
    return EmitNullValue(E->getType());
470
2.94k
  }
471
7
  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
472
7
    return EmitNullValue(E->getType());
473
7
  }
474
  Value *VisitOffsetOfExpr(OffsetOfExpr *E);
475
  Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
476
21
  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
477
21
    llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
478
21
    return Builder.CreateBitCast(V, ConvertType(E->getType()));
479
21
  }
480
481
1
  Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
482
1
    return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
483
1
  }
484
485
1.68k
  Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
486
1.68k
    return CGF.EmitPseudoObjectRValue(E).getScalarVal();
487
1.68k
  }
488
489
  Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
490
491
2.55k
  Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
492
2.55k
    if (E->isGLValue())
493
225
      return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
494
225
                              E->getExprLoc());
495
496
    // Otherwise, assume the mapping is the scalar directly.
497
2.33k
    return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
498
2.55k
  }
499
500
  // l-values.
501
1.24M
  Value *VisitDeclRefExpr(DeclRefExpr *E) {
502
1.24M
    if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
503
6.48k
      return CGF.emitScalarConstant(Constant, E);
504
1.23M
    return EmitLoadOfLValue(E);
505
1.24M
  }
506
507
97
  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
508
97
    return CGF.EmitObjCSelectorExpr(E);
509
97
  }
510
17
  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
511
17
    return CGF.EmitObjCProtocolExpr(E);
512
17
  }
513
619
  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
514
619
    return EmitLoadOfLValue(E);
515
619
  }
516
12.1k
  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
517
12.1k
    if (E->getMethodDecl() &&
518
12.1k
        
E->getMethodDecl()->getReturnType()->isReferenceType()11.5k
)
519
3
      return EmitLoadOfLValue(E);
520
12.1k
    return CGF.EmitObjCMessageExpr(E).getScalarVal();
521
12.1k
  }
522
523
18
  Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
524
18
    LValue LV = CGF.EmitObjCIsaExpr(E);
525
18
    Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
526
18
    return V;
527
18
  }
528
529
20
  Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
530
20
    VersionTuple Version = E->getVersion();
531
532
    // If we're checking for a platform older than our minimum deployment
533
    // target, we can fold the check away.
534
20
    if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
535
4
      return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
536
537
16
    return CGF.EmitBuiltinAvailable(Version);
538
20
  }
539
540
  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
541
  Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
542
  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
543
  Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
544
  Value *VisitMemberExpr(MemberExpr *E);
545
246
  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
546
2.08k
  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
547
    // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
548
    // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
549
    // literals aren't l-values in C++. We do so simply because that's the
550
    // cleanest way to handle compound literals in C++.
551
    // See the discussion here: https://reviews.llvm.org/D64464
552
2.08k
    return EmitLoadOfLValue(E);
553
2.08k
  }
554
555
  Value *VisitInitListExpr(InitListExpr *E);
556
557
29
  Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
558
29
    assert(CGF.getArrayInitIndex() &&
559
29
           "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
560
0
    return CGF.getArrayInitIndex();
561
29
  }
562
563
1.00k
  Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
564
1.00k
    return EmitNullValue(E->getType());
565
1.00k
  }
566
289k
  Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
567
289k
    CGF.CGM.EmitExplicitCastExprType(E, &CGF);
568
289k
    return VisitCastExpr(E);
569
289k
  }
570
  Value *VisitCastExpr(CastExpr *E);
571
572
364k
  Value *VisitCallExpr(const CallExpr *E) {
573
364k
    if (E->getCallReturnType(CGF.getContext())->isReferenceType())
574
8.77k
      return EmitLoadOfLValue(E);
575
576
356k
    Value *V = CGF.EmitCallExpr(E).getScalarVal();
577
578
356k
    EmitLValueAlignmentAssumption(E, V);
579
356k
    return V;
580
364k
  }
581
582
  Value *VisitStmtExpr(const StmtExpr *E);
583
584
  // Unary Operators.
585
197
  Value *VisitUnaryPostDec(const UnaryOperator *E) {
586
197
    LValue LV = EmitLValue(E->getSubExpr());
587
197
    return EmitScalarPrePostIncDec(E, LV, false, false);
588
197
  }
589
5.70k
  Value *VisitUnaryPostInc(const UnaryOperator *E) {
590
5.70k
    LValue LV = EmitLValue(E->getSubExpr());
591
5.70k
    return EmitScalarPrePostIncDec(E, LV, true, false);
592
5.70k
  }
593
805
  Value *VisitUnaryPreDec(const UnaryOperator *E) {
594
805
    LValue LV = EmitLValue(E->getSubExpr());
595
805
    return EmitScalarPrePostIncDec(E, LV, false, true);
596
805
  }
597
7.30k
  Value *VisitUnaryPreInc(const UnaryOperator *E) {
598
7.30k
    LValue LV = EmitLValue(E->getSubExpr());
599
7.30k
    return EmitScalarPrePostIncDec(E, LV, true, true);
600
7.30k
  }
601
602
  llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
603
                                                  llvm::Value *InVal,
604
                                                  bool IsInc);
605
606
  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
607
                                       bool isInc, bool isPre);
608
609
610
26.2k
  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
611
26.2k
    if (isa<MemberPointerType>(E->getType())) // never sugared
612
607
      return CGF.CGM.getMemberPointerConstant(E);
613
614
25.6k
    return EmitLValue(E->getSubExpr()).getPointer(CGF);
615
26.2k
  }
616
26.7k
  Value *VisitUnaryDeref(const UnaryOperator *E) {
617
26.7k
    if (E->getType()->isVoidType())
618
8
      return Visit(E->getSubExpr()); // the actual value should be unused
619
26.7k
    return EmitLoadOfLValue(E);
620
26.7k
  }
621
62
  Value *VisitUnaryPlus(const UnaryOperator *E) {
622
    // This differs from gcc, though, most likely due to a bug in gcc.
623
62
    TestAndClearIgnoreResultAssign();
624
62
    return Visit(E->getSubExpr());
625
62
  }
626
  Value *VisitUnaryMinus    (const UnaryOperator *E);
627
  Value *VisitUnaryNot      (const UnaryOperator *E);
628
  Value *VisitUnaryLNot     (const UnaryOperator *E);
629
  Value *VisitUnaryReal     (const UnaryOperator *E);
630
  Value *VisitUnaryImag     (const UnaryOperator *E);
631
4.02k
  Value *VisitUnaryExtension(const UnaryOperator *E) {
632
4.02k
    return Visit(E->getSubExpr());
633
4.02k
  }
634
635
  // C++
636
11
  Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
637
11
    return EmitLoadOfLValue(E);
638
11
  }
639
141
  Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
640
141
    auto &Ctx = CGF.getContext();
641
141
    APValue Evaluated =
642
141
        SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
643
141
    return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
644
141
                                             SLE->getType());
645
141
  }
646
647
3.60k
  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
648
3.60k
    CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
649
3.60k
    return Visit(DAE->getExpr());
650
3.60k
  }
651
420
  Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
652
420
    CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
653
420
    return Visit(DIE->getExpr());
654
420
  }
655
77.2k
  Value *VisitCXXThisExpr(CXXThisExpr *TE) {
656
77.2k
    return CGF.LoadCXXThis();
657
77.2k
  }
658
659
  Value *VisitExprWithCleanups(ExprWithCleanups *E);
660
2.02k
  Value *VisitCXXNewExpr(const CXXNewExpr *E) {
661
2.02k
    return CGF.EmitCXXNewExpr(E);
662
2.02k
  }
663
879
  Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
664
879
    CGF.EmitCXXDeleteExpr(E);
665
879
    return nullptr;
666
879
  }
667
668
9
  Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
669
9
    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
670
9
  }
671
672
0
  Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
673
0
    return Builder.getInt1(E->isSatisfied());
674
0
  }
675
676
0
  Value *VisitRequiresExpr(const RequiresExpr *E) {
677
0
    return Builder.getInt1(E->isSatisfied());
678
0
  }
679
680
0
  Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
681
0
    return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
682
0
  }
683
684
0
  Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
685
0
    return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
686
0
  }
687
688
0
  Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
689
    // C++ [expr.pseudo]p1:
690
    //   The result shall only be used as the operand for the function call
691
    //   operator (), and the result of such a call has type void. The only
692
    //   effect is the evaluation of the postfix-expression before the dot or
693
    //   arrow.
694
0
    CGF.EmitScalarExpr(E->getBase());
695
0
    return nullptr;
696
0
  }
697
698
6.67k
  Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
699
6.67k
    return EmitNullValue(E->getType());
700
6.67k
  }
701
702
555
  Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
703
555
    CGF.EmitCXXThrowExpr(E);
704
555
    return nullptr;
705
555
  }
706
707
11
  Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
708
11
    return Builder.getInt1(E->getValue());
709
11
  }
710
711
  // Binary Operators.
712
35.6k
  Value *EmitMul(const BinOpInfo &Ops) {
713
35.6k
    if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
714
25.1k
      switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
715
1
      case LangOptions::SOB_Defined:
716
1
        return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
717
25.1k
      case LangOptions::SOB_Undefined:
718
25.1k
        if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
719
25.1k
          return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
720
25.1k
        
LLVM_FALLTHROUGH16
;16
721
18
      case LangOptions::SOB_Trapping:
722
18
        if (CanElideOverflowCheck(CGF.getContext(), Ops))
723
5
          return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
724
13
        return EmitOverflowCheckedBinOp(Ops);
725
25.1k
      }
726
25.1k
    }
727
728
10.4k
    if (Ops.Ty->isConstantMatrixType()) {
729
43
      llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
730
      // We need to check the types of the operands of the operator to get the
731
      // correct matrix dimensions.
732
43
      auto *BO = cast<BinaryOperator>(Ops.E);
733
43
      auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
734
43
          BO->getLHS()->getType().getCanonicalType());
735
43
      auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
736
43
          BO->getRHS()->getType().getCanonicalType());
737
43
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
738
43
      if (LHSMatTy && 
RHSMatTy39
)
739
24
        return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
740
24
                                       LHSMatTy->getNumColumns(),
741
24
                                       RHSMatTy->getNumColumns());
742
19
      return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
743
43
    }
744
745
10.4k
    if (Ops.Ty->isUnsignedIntegerType() &&
746
10.4k
        
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)7.10k
&&
747
10.4k
        
!CanElideOverflowCheck(CGF.getContext(), Ops)7
)
748
5
      return EmitOverflowCheckedBinOp(Ops);
749
750
10.4k
    if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
751
      //  Preserve the old values
752
2.86k
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
753
2.86k
      return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
754
2.86k
    }
755
7.55k
    if (Ops.isFixedPointOp())
756
72
      return EmitFixedPointBinOp(Ops);
757
7.48k
    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
758
7.55k
  }
759
  /// Create a binary op that checks for overflow.
760
  /// Currently only supports +, - and *.
761
  Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
762
763
  // Check for undefined division and modulus behaviors.
764
  void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
765
                                                  llvm::Value *Zero,bool isDiv);
766
  // Common helper for getting how wide LHS of shift is.
767
  static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
768
769
  // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
770
  // non powers of two.
771
  Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
772
773
  Value *EmitDiv(const BinOpInfo &Ops);
774
  Value *EmitRem(const BinOpInfo &Ops);
775
  Value *EmitAdd(const BinOpInfo &Ops);
776
  Value *EmitSub(const BinOpInfo &Ops);
777
  Value *EmitShl(const BinOpInfo &Ops);
778
  Value *EmitShr(const BinOpInfo &Ops);
779
5.27k
  Value *EmitAnd(const BinOpInfo &Ops) {
780
5.27k
    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
781
5.27k
  }
782
654
  Value *EmitXor(const BinOpInfo &Ops) {
783
654
    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
784
654
  }
785
1.61k
  Value *EmitOr (const BinOpInfo &Ops) {
786
1.61k
    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
787
1.61k
  }
788
789
  // Helper functions for fixed point binary operations.
790
  Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
791
792
  BinOpInfo EmitBinOps(const BinaryOperator *E);
793
  LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
794
                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
795
                                  Value *&Result);
796
797
  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
798
                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
799
800
  // Binary operators and binary compound assignment operators.
801
#define HANDLEBINOP(OP) \
802
367k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
367k
    return Emit ## OP(EmitBinOps(E));                                      \
804
367k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinMul(clang::BinaryOperator const*)
Line
Count
Source
802
35.1k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
35.1k
    return Emit ## OP(EmitBinOps(E));                                      \
804
35.1k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinDiv(clang::BinaryOperator const*)
Line
Count
Source
802
55.9k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
55.9k
    return Emit ## OP(EmitBinOps(E));                                      \
804
55.9k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinRem(clang::BinaryOperator const*)
Line
Count
Source
802
665
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
665
    return Emit ## OP(EmitBinOps(E));                                      \
804
665
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinAdd(clang::BinaryOperator const*)
Line
Count
Source
802
131k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
131k
    return Emit ## OP(EmitBinOps(E));                                      \
804
131k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinSub(clang::BinaryOperator const*)
Line
Count
Source
802
129k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
129k
    return Emit ## OP(EmitBinOps(E));                                      \
804
129k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinShl(clang::BinaryOperator const*)
Line
Count
Source
802
7.02k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
7.02k
    return Emit ## OP(EmitBinOps(E));                                      \
804
7.02k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinShr(clang::BinaryOperator const*)
Line
Count
Source
802
804
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
804
    return Emit ## OP(EmitBinOps(E));                                      \
804
804
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinAnd(clang::BinaryOperator const*)
Line
Count
Source
802
5.03k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
5.03k
    return Emit ## OP(EmitBinOps(E));                                      \
804
5.03k
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinXor(clang::BinaryOperator const*)
Line
Count
Source
802
481
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
481
    return Emit ## OP(EmitBinOps(E));                                      \
804
481
  }                                                                        \
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinOr(clang::BinaryOperator const*)
Line
Count
Source
802
1.29k
  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
803
1.29k
    return Emit ## OP(EmitBinOps(E));                                      \
804
1.29k
  }                                                                        \
805
2.58k
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
2.58k
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
2.58k
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinMulAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
375
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
375
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
375
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinDivAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
245
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
245
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
245
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinRemAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
126
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
126
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
126
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinAddAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
822
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
822
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
822
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinSubAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
279
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
279
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
279
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinShlAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
147
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
147
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
147
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinShrAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
136
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
136
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
136
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinAndAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
131
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
131
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
131
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinOrAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
169
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
169
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
169
  }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinXorAssign(clang::CompoundAssignOperator const*)
Line
Count
Source
805
152
  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
806
152
    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
807
152
  }
808
  HANDLEBINOP(Mul)
809
  HANDLEBINOP(Div)
810
  HANDLEBINOP(Rem)
811
  HANDLEBINOP(Add)
812
  HANDLEBINOP(Sub)
813
  HANDLEBINOP(Shl)
814
  HANDLEBINOP(Shr)
815
  HANDLEBINOP(And)
816
  HANDLEBINOP(Xor)
817
  HANDLEBINOP(Or)
818
#undef HANDLEBINOP
819
820
  // Comparisons.
821
  Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
822
                     llvm::CmpInst::Predicate SICmpOpc,
823
                     llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
824
#define VISITCOMP(CODE, UI, SI, FP, SIG) \
825
82.0k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
82.0k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
82.0k
                         llvm::FCmpInst::FP, SIG); }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinLT(clang::BinaryOperator const*)
Line
Count
Source
825
22.5k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
22.5k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
22.5k
                         llvm::FCmpInst::FP, SIG); }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinGT(clang::BinaryOperator const*)
Line
Count
Source
825
12.4k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
12.4k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
12.4k
                         llvm::FCmpInst::FP, SIG); }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinLE(clang::BinaryOperator const*)
Line
Count
Source
825
15.7k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
15.7k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
15.7k
                         llvm::FCmpInst::FP, SIG); }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinGE(clang::BinaryOperator const*)
Line
Count
Source
825
5.67k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
5.67k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
5.67k
                         llvm::FCmpInst::FP, SIG); }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinEQ(clang::BinaryOperator const*)
Line
Count
Source
825
20.9k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
20.9k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
20.9k
                         llvm::FCmpInst::FP, SIG); }
CGExprScalar.cpp:(anonymous namespace)::ScalarExprEmitter::VisitBinNE(clang::BinaryOperator const*)
Line
Count
Source
825
4.67k
    Value *VisitBin##CODE(const BinaryOperator *E) { \
826
4.67k
      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
827
4.67k
                         llvm::FCmpInst::FP, SIG); }
828
  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
829
  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
830
  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
831
  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
832
  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
833
  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
834
#undef VISITCOMP
835
836
  Value *VisitBinAssign     (const BinaryOperator *E);
837
838
  Value *VisitBinLAnd       (const BinaryOperator *E);
839
  Value *VisitBinLOr        (const BinaryOperator *E);
840
  Value *VisitBinComma      (const BinaryOperator *E);
841
842
24
  Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
843
15
  Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
844
845
0
  Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
846
0
    return Visit(E->getSemanticForm());
847
0
  }
848
849
  // Other Operators.
850
  Value *VisitBlockExpr(const BlockExpr *BE);
851
  Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
852
  Value *VisitChooseExpr(ChooseExpr *CE);
853
  Value *VisitVAArgExpr(VAArgExpr *VE);
854
4.62k
  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
855
4.62k
    return CGF.EmitObjCStringLiteral(E);
856
4.62k
  }
857
730
  Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
858
730
    return CGF.EmitObjCBoxedExpr(E);
859
730
  }
860
119
  Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
861
119
    return CGF.EmitObjCArrayLiteral(E);
862
119
  }
863
107
  Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
864
107
    return CGF.EmitObjCDictionaryLiteral(E);
865
107
  }
866
  Value *VisitAsTypeExpr(AsTypeExpr *CE);
867
  Value *VisitAtomicExpr(AtomicExpr *AE);
868
};
869
}  // end anonymous namespace.
870
871
//===----------------------------------------------------------------------===//
872
//                                Utilities
873
//===----------------------------------------------------------------------===//
874
875
/// EmitConversionToBool - Convert the specified expression value to a
876
/// boolean (i1) truth value.  This is equivalent to "Val != 0".
877
7.93k
Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
878
7.93k
  assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
879
880
7.93k
  if (SrcType->isRealFloatingType())
881
43
    return EmitFloatToBoolConversion(Src);
882
883
7.88k
  if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
884
0
    return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
885
886
7.88k
  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
887
7.88k
         "Unknown scalar type to convert");
888
889
7.88k
  if (isa<llvm::IntegerType>(Src->getType()))
890
7.48k
    return EmitIntToBoolConversion(Src);
891
892
403
  assert(isa<llvm::PointerType>(Src->getType()));
893
0
  return EmitPointerToBoolConversion(Src, SrcType);
894
7.88k
}
895
896
void ScalarExprEmitter::EmitFloatConversionCheck(
897
    Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
898
14
    QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
899
14
  assert(SrcType->isFloatingType() && "not a conversion from floating point");
900
14
  if (!isa<llvm::IntegerType>(DstTy))
901
2
    return;
902
903
12
  CodeGenFunction::SanitizerScope SanScope(&CGF);
904
12
  using llvm::APFloat;
905
12
  using llvm::APSInt;
906
907
12
  llvm::Value *Check = nullptr;
908
12
  const llvm::fltSemantics &SrcSema =
909
12
    CGF.getContext().getFloatTypeSemantics(OrigSrcType);
910
911
  // Floating-point to integer. This has undefined behavior if the source is
912
  // +-Inf, NaN, or doesn't fit into the destination type (after truncation
913
  // to an integer).
914
12
  unsigned Width = CGF.getContext().getIntWidth(DstType);
915
12
  bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
916
917
12
  APSInt Min = APSInt::getMinValue(Width, Unsigned);
918
12
  APFloat MinSrc(SrcSema, APFloat::uninitialized);
919
12
  if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
920
12
      APFloat::opOverflow)
921
    // Don't need an overflow check for lower bound. Just check for
922
    // -Inf/NaN.
923
0
    MinSrc = APFloat::getInf(SrcSema, true);
924
12
  else
925
    // Find the largest value which is too small to represent (before
926
    // truncation toward zero).
927
12
    MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
928
929
12
  APSInt Max = APSInt::getMaxValue(Width, Unsigned);
930
12
  APFloat MaxSrc(SrcSema, APFloat::uninitialized);
931
12
  if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
932
12
      APFloat::opOverflow)
933
    // Don't need an overflow check for upper bound. Just check for
934
    // +Inf/NaN.
935
0
    MaxSrc = APFloat::getInf(SrcSema, false);
936
12
  else
937
    // Find the smallest value which is too large to represent (before
938
    // truncation toward zero).
939
12
    MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
940
941
  // If we're converting from __half, convert the range to float to match
942
  // the type of src.
943
12
  if (OrigSrcType->isHalfType()) {
944
2
    const llvm::fltSemantics &Sema =
945
2
      CGF.getContext().getFloatTypeSemantics(SrcType);
946
2
    bool IsInexact;
947
2
    MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
948
2
    MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
949
2
  }
950
951
12
  llvm::Value *GE =
952
12
    Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
953
12
  llvm::Value *LE =
954
12
    Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
955
12
  Check = Builder.CreateAnd(GE, LE);
956
957
12
  llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
958
12
                                  CGF.EmitCheckTypeDescriptor(OrigSrcType),
959
12
                                  CGF.EmitCheckTypeDescriptor(DstType)};
960
12
  CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
961
12
                SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
962
12
}
963
964
// Should be called within CodeGenFunction::SanitizerScope RAII scope.
965
// Returns 'i1 false' when the truncation Src -> Dst was lossy.
966
static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
967
                 std::pair<llvm::Value *, SanitizerMask>>
968
EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
969
662
                                 QualType DstType, CGBuilderTy &Builder) {
970
662
  llvm::Type *SrcTy = Src->getType();
971
662
  llvm::Type *DstTy = Dst->getType();
972
662
  (void)DstTy; // Only used in assert()
973
974
  // This should be truncation of integral types.
975
662
  assert(Src != Dst);
976
0
  assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
977
0
  assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
978
662
         "non-integer llvm type");
979
980
0
  bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
981
662
  bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
982
983
  // If both (src and dst) types are unsigned, then it's an unsigned truncation.
984
  // Else, it is a signed truncation.
985
662
  ScalarExprEmitter::ImplicitConversionCheckKind Kind;
986
662
  SanitizerMask Mask;
987
662
  if (!SrcSigned && 
!DstSigned150
) {
988
85
    Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
989
85
    Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
990
577
  } else {
991
577
    Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
992
577
    Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
993
577
  }
994
995
662
  llvm::Value *Check = nullptr;
996
  // 1. Extend the truncated value back to the same width as the Src.
997
662
  Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
998
  // 2. Equality-compare with the original source value
999
662
  Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
1000
  // If the comparison result is 'i1 false', then the truncation was lossy.
1001
662
  return std::make_pair(Kind, std::make_pair(Check, Mask));
1002
662
}
1003
1004
static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
1005
2.24k
    QualType SrcType, QualType DstType) {
1006
2.24k
  return SrcType->isIntegerType() && DstType->isIntegerType();
1007
2.24k
}
1008
1009
void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1010
                                                   Value *Dst, QualType DstType,
1011
942
                                                   SourceLocation Loc) {
1012
942
  if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
1013
0
    return;
1014
1015
  // We only care about int->int conversions here.
1016
  // We ignore conversions to/from pointer and/or bool.
1017
942
  if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1018
942
                                                                       DstType))
1019
0
    return;
1020
1021
942
  unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1022
942
  unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1023
  // This must be truncation. Else we do not care.
1024
942
  if (SrcBits <= DstBits)
1025
280
    return;
1026
1027
662
  assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1028
1029
  // If the integer sign change sanitizer is enabled,
1030
  // and we are truncating from larger unsigned type to smaller signed type,
1031
  // let that next sanitizer deal with it.
1032
0
  bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1033
662
  bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1034
662
  if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1035
662
      
(311
!SrcSigned311
&&
DstSigned64
))
1036
32
    return;
1037
1038
630
  CodeGenFunction::SanitizerScope SanScope(&CGF);
1039
1040
630
  std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1041
630
            std::pair<llvm::Value *, SanitizerMask>>
1042
630
      Check =
1043
630
          EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1044
  // If the comparison result is 'i1 false', then the truncation was lossy.
1045
1046
  // Do we care about this type of truncation?
1047
630
  if (!CGF.SanOpts.has(Check.second.second))
1048
31
    return;
1049
1050
599
  llvm::Constant *StaticArgs[] = {
1051
599
      CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1052
599
      CGF.EmitCheckTypeDescriptor(DstType),
1053
599
      llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1054
599
  CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1055
599
                {Src, Dst});
1056
599
}
1057
1058
// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1059
// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1060
static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1061
                 std::pair<llvm::Value *, SanitizerMask>>
1062
EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1063
358
                                 QualType DstType, CGBuilderTy &Builder) {
1064
358
  llvm::Type *SrcTy = Src->getType();
1065
358
  llvm::Type *DstTy = Dst->getType();
1066
1067
358
  assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1068
358
         "non-integer llvm type");
1069
1070
0
  bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1071
358
  bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1072
358
  (void)SrcSigned; // Only used in assert()
1073
358
  (void)DstSigned; // Only used in assert()
1074
358
  unsigned SrcBits = SrcTy->getScalarSizeInBits();
1075
358
  unsigned DstBits = DstTy->getScalarSizeInBits();
1076
358
  (void)SrcBits; // Only used in assert()
1077
358
  (void)DstBits; // Only used in assert()
1078
1079
358
  assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1080
358
         "either the widths should be different, or the signednesses.");
1081
1082
  // NOTE: zero value is considered to be non-negative.
1083
0
  auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1084
716
                                       const char *Name) -> Value * {
1085
    // Is this value a signed type?
1086
716
    bool VSigned = VType->isSignedIntegerOrEnumerationType();
1087
716
    llvm::Type *VTy = V->getType();
1088
716
    if (!VSigned) {
1089
      // If the value is unsigned, then it is never negative.
1090
      // FIXME: can we encounter non-scalar VTy here?
1091
238
      return llvm::ConstantInt::getFalse(VTy->getContext());
1092
238
    }
1093
    // Get the zero of the same type with which we will be comparing.
1094
478
    llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1095
    // %V.isnegative = icmp slt %V, 0
1096
    // I.e is %V *strictly* less than zero, does it have negative value?
1097
478
    return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1098
478
                              llvm::Twine(Name) + "." + V->getName() +
1099
478
                                  ".negativitycheck");
1100
716
  };
1101
1102
  // 1. Was the old Value negative?
1103
358
  llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1104
  // 2. Is the new Value negative?
1105
358
  llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1106
  // 3. Now, was the 'negativity status' preserved during the conversion?
1107
  //    NOTE: conversion from negative to zero is considered to change the sign.
1108
  //    (We want to get 'false' when the conversion changed the sign)
1109
  //    So we should just equality-compare the negativity statuses.
1110
358
  llvm::Value *Check = nullptr;
1111
358
  Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1112
  // If the comparison result is 'false', then the conversion changed the sign.
1113
358
  return std::make_pair(
1114
358
      ScalarExprEmitter::ICCK_IntegerSignChange,
1115
358
      std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1116
358
}
1117
1118
void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1119
                                                   Value *Dst, QualType DstType,
1120
922
                                                   SourceLocation Loc) {
1121
922
  if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1122
0
    return;
1123
1124
922
  llvm::Type *SrcTy = Src->getType();
1125
922
  llvm::Type *DstTy = Dst->getType();
1126
1127
  // We only care about int->int conversions here.
1128
  // We ignore conversions to/from pointer and/or bool.
1129
922
  if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1130
922
                                                                       DstType))
1131
0
    return;
1132
1133
922
  bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1134
922
  bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1135
922
  unsigned SrcBits = SrcTy->getScalarSizeInBits();
1136
922
  unsigned DstBits = DstTy->getScalarSizeInBits();
1137
1138
  // Now, we do not need to emit the check in *all* of the cases.
1139
  // We can avoid emitting it in some obvious cases where it would have been
1140
  // dropped by the opt passes (instcombine) always anyways.
1141
  // If it's a cast between effectively the same type, no check.
1142
  // NOTE: this is *not* equivalent to checking the canonical types.
1143
922
  if (SrcSigned == DstSigned && 
SrcBits == DstBits434
)
1144
4
    return;
1145
  // At least one of the values needs to have signed type.
1146
  // If both are unsigned, then obviously, neither of them can be negative.
1147
918
  if (!SrcSigned && 
!DstSigned275
)
1148
62
    return;
1149
  // If the conversion is to *larger* *signed* type, then no check is needed.
1150
  // Because either sign-extension happens (so the sign will remain),
1151
  // or zero-extension will happen (the sign bit will be zero.)
1152
856
  if ((DstBits > SrcBits) && 
DstSigned258
)
1153
251
    return;
1154
605
  if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1155
605
      
(SrcBits > DstBits)296
&&
SrcSigned279
) {
1156
    // If the signed integer truncation sanitizer is enabled,
1157
    // and this is a truncation from signed type, then no check is needed.
1158
    // Because here sign change check is interchangeable with truncation check.
1159
247
    return;
1160
247
  }
1161
  // That's it. We can't rule out any more cases with the data we have.
1162
1163
358
  CodeGenFunction::SanitizerScope SanScope(&CGF);
1164
1165
358
  std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1166
358
            std::pair<llvm::Value *, SanitizerMask>>
1167
358
      Check;
1168
1169
  // Each of these checks needs to return 'false' when an issue was detected.
1170
358
  ImplicitConversionCheckKind CheckKind;
1171
358
  llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1172
  // So we can 'and' all the checks together, and still get 'false',
1173
  // if at least one of the checks detected an issue.
1174
1175
358
  Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1176
358
  CheckKind = Check.first;
1177
358
  Checks.emplace_back(Check.second);
1178
1179
358
  if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1180
358
      
(SrcBits > DstBits)49
&&
!SrcSigned32
&&
DstSigned32
) {
1181
    // If the signed integer truncation sanitizer was enabled,
1182
    // and we are truncating from larger unsigned type to smaller signed type,
1183
    // let's handle the case we skipped in that check.
1184
32
    Check =
1185
32
        EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1186
32
    CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1187
32
    Checks.emplace_back(Check.second);
1188
    // If the comparison result is 'i1 false', then the truncation was lossy.
1189
32
  }
1190
1191
358
  llvm::Constant *StaticArgs[] = {
1192
358
      CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1193
358
      CGF.EmitCheckTypeDescriptor(DstType),
1194
358
      llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1195
  // EmitCheck() will 'and' all the checks together.
1196
358
  CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1197
358
                {Src, Dst});
1198
358
}
1199
1200
Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
1201
                                         QualType DstType, llvm::Type *SrcTy,
1202
                                         llvm::Type *DstTy,
1203
139k
                                         ScalarConversionOpts Opts) {
1204
  // The Element types determine the type of cast to perform.
1205
139k
  llvm::Type *SrcElementTy;
1206
139k
  llvm::Type *DstElementTy;
1207
139k
  QualType SrcElementType;
1208
139k
  QualType DstElementType;
1209
139k
  if (SrcType->isMatrixType() && 
DstType->isMatrixType()39
) {
1210
39
    SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1211
39
    DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
1212
39
    SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
1213
39
    DstElementType = DstType->castAs<MatrixType>()->getElementType();
1214
139k
  } else {
1215
139k
    assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
1216
139k
           "cannot cast between matrix and non-matrix types");
1217
0
    SrcElementTy = SrcTy;
1218
139k
    DstElementTy = DstTy;
1219
139k
    SrcElementType = SrcType;
1220
139k
    DstElementType = DstType;
1221
139k
  }
1222
1223
139k
  if (isa<llvm::IntegerType>(SrcElementTy)) {
1224
129k
    bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
1225
129k
    if (SrcElementType->isBooleanType() && 
Opts.TreatBooleanAsSigned5.67k
) {
1226
9
      InputSigned = true;
1227
9
    }
1228
1229
129k
    if (isa<llvm::IntegerType>(DstElementTy))
1230
120k
      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1231
8.75k
    if (InputSigned)
1232
8.42k
      return Builder.CreateSIToFP(Src, DstTy, "conv");
1233
333
    return Builder.CreateUIToFP(Src, DstTy, "conv");
1234
8.75k
  }
1235
1236
10.2k
  if (isa<llvm::IntegerType>(DstElementTy)) {
1237
1.79k
    assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
1238
1.79k
    if (DstElementType->isSignedIntegerOrEnumerationType())
1239
1.61k
      return Builder.CreateFPToSI(Src, DstTy, "conv");
1240
175
    return Builder.CreateFPToUI(Src, DstTy, "conv");
1241
1.79k
  }
1242
1243
8.43k
  if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
1244
3.15k
    return Builder.CreateFPTrunc(Src, DstTy, "conv");
1245
5.27k
  return Builder.CreateFPExt(Src, DstTy, "conv");
1246
8.43k
}
1247
1248
/// Emit a conversion from the specified type to the specified destination type,
1249
/// both of which are LLVM scalar types.
1250
Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1251
                                               QualType DstType,
1252
                                               SourceLocation Loc,
1253
546k
                                               ScalarConversionOpts Opts) {
1254
  // All conversions involving fixed point types should be handled by the
1255
  // EmitFixedPoint family functions. This is done to prevent bloating up this
1256
  // function more, and although fixed point numbers are represented by
1257
  // integers, we do not want to follow any logic that assumes they should be
1258
  // treated as integers.
1259
  // TODO(leonardchan): When necessary, add another if statement checking for
1260
  // conversions to fixed point types from other types.
1261
546k
  if (SrcType->isFixedPointType()) {
1262
240
    if (DstType->isBooleanType())
1263
      // It is important that we check this before checking if the dest type is
1264
      // an integer because booleans are technically integer types.
1265
      // We do not need to check the padding bit on unsigned types if unsigned
1266
      // padding is enabled because overflow into this bit is undefined
1267
      // behavior.
1268
30
      return Builder.CreateIsNotNull(Src, "tobool");
1269
210
    if (DstType->isFixedPointType() || 
DstType->isIntegerType()56
||
1270
210
        
DstType->isRealFloatingType()40
)
1271
210
      return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1272
1273
0
    llvm_unreachable(
1274
0
        "Unhandled scalar conversion from a fixed point type to another type.");
1275
546k
  } else if (DstType->isFixedPointType()) {
1276
78
    if (SrcType->isIntegerType() || 
SrcType->isRealFloatingType()60
)
1277
      // This also includes converting booleans and enums to fixed point types.
1278
78
      return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1279
1280
0
    llvm_unreachable(
1281
0
        "Unhandled scalar conversion to a fixed point type from another type.");
1282
0
  }
1283
1284
546k
  QualType NoncanonicalSrcType = SrcType;
1285
546k
  QualType NoncanonicalDstType = DstType;
1286
1287
546k
  SrcType = CGF.getContext().getCanonicalType(SrcType);
1288
546k
  DstType = CGF.getContext().getCanonicalType(DstType);
1289
546k
  if (SrcType == DstType) 
return Src281k
;
1290
1291
264k
  if (DstType->isVoidType()) 
return nullptr0
;
1292
1293
264k
  llvm::Value *OrigSrc = Src;
1294
264k
  QualType OrigSrcType = SrcType;
1295
264k
  llvm::Type *SrcTy = Src->getType();
1296
1297
  // Handle conversions to bool first, they are special: comparisons against 0.
1298
264k
  if (DstType->isBooleanType())
1299
7.93k
    return EmitConversionToBool(Src, SrcType);
1300
1301
256k
  llvm::Type *DstTy = ConvertType(DstType);
1302
1303
  // Cast from half through float if half isn't a native type.
1304
256k
  if (SrcType->isHalfType() && 
!CGF.getContext().getLangOpts().NativeHalfType1.46k
) {
1305
    // Cast to FP using the intrinsic if the half type itself isn't supported.
1306
1.17k
    if (DstTy->isFloatingPointTy()) {
1307
1.15k
      if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1308
7
        return Builder.CreateCall(
1309
7
            CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1310
7
            Src);
1311
1.15k
    } else {
1312
      // Cast to other types through float, using either the intrinsic or FPExt,
1313
      // depending on whether the half type itself is supported
1314
      // (as opposed to operations on half, available with NativeHalfType).
1315
23
      if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1316
0
        Src = Builder.CreateCall(
1317
0
            CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1318
0
                                 CGF.CGM.FloatTy),
1319
0
            Src);
1320
23
      } else {
1321
23
        Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1322
23
      }
1323
23
      SrcType = CGF.getContext().FloatTy;
1324
23
      SrcTy = CGF.FloatTy;
1325
23
    }
1326
1.17k
  }
1327
1328
  // Ignore conversions like int -> uint.
1329
256k
  if (SrcTy == DstTy) {
1330
98.5k
    if (Opts.EmitImplicitIntegerSignChangeChecks)
1331
49
      EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1332
49
                                 NoncanonicalDstType, Loc);
1333
1334
98.5k
    return Src;
1335
98.5k
  }
1336
1337
  // Handle pointer conversions next: pointers can only be converted to/from
1338
  // other pointers and integers. Check for pointer types in terms of LLVM, as
1339
  // some native types (like Obj-C id) may map to a pointer type.
1340
157k
  if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1341
    // The source value may be an integer, or a pointer.
1342
17.3k
    if (isa<llvm::PointerType>(SrcTy))
1343
17.1k
      return Builder.CreateBitCast(Src, DstTy, "conv");
1344
1345
127
    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1346
    // First, convert to the correct width so that we control the kind of
1347
    // extension.
1348
0
    llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1349
127
    bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1350
127
    llvm::Value* IntResult =
1351
127
        Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1352
    // Then, cast to pointer.
1353
127
    return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
1354
17.3k
  }
1355
1356
140k
  if (isa<llvm::PointerType>(SrcTy)) {
1357
    // Must be an ptr to int cast.
1358
25
    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1359
0
    return Builder.CreatePtrToInt(Src, DstTy, "conv");
1360
25
  }
1361
1362
  // A scalar can be splatted to an extended vector of the same element type
1363
140k
  if (DstType->isExtVectorType() && 
!SrcType->isVectorType()0
) {
1364
    // Sema should add casts to make sure that the source expression's type is
1365
    // the same as the vector's element type (sans qualifiers)
1366
0
    assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1367
0
               SrcType.getTypePtr() &&
1368
0
           "Splatted expr doesn't match with vector element type?");
1369
1370
    // Splat the element across to all elements
1371
0
    unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
1372
0
    return Builder.CreateVectorSplat(NumElements, Src, "splat");
1373
0
  }
1374
1375
140k
  if (SrcType->isMatrixType() && 
DstType->isMatrixType()39
)
1376
39
    return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1377
1378
140k
  if (isa<llvm::VectorType>(SrcTy) || 
isa<llvm::VectorType>(DstTy)140k
) {
1379
    // Allow bitcast from vector to integer/fp of the same size.
1380
156
    unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1381
156
    unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1382
156
    if (SrcSize == DstSize)
1383
0
      return Builder.CreateBitCast(Src, DstTy, "conv");
1384
1385
    // Conversions between vectors of different sizes are not allowed except
1386
    // when vectors of half are involved. Operations on storage-only half
1387
    // vectors require promoting half vector operands to float vectors and
1388
    // truncating the result, which is either an int or float vector, to a
1389
    // short or half vector.
1390
1391
    // Source and destination are both expected to be vectors.
1392
156
    llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1393
156
    llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
1394
156
    (void)DstElementTy;
1395
1396
156
    assert(((SrcElementTy->isIntegerTy() &&
1397
156
             DstElementTy->isIntegerTy()) ||
1398
156
            (SrcElementTy->isFloatingPointTy() &&
1399
156
             DstElementTy->isFloatingPointTy())) &&
1400
156
           "unexpected conversion between a floating-point vector and an "
1401
156
           "integer vector");
1402
1403
    // Truncate an i32 vector to an i16 vector.
1404
156
    if (SrcElementTy->isIntegerTy())
1405
18
      return Builder.CreateIntCast(Src, DstTy, false, "conv");
1406
1407
    // Truncate a float vector to a half vector.
1408
138
    if (SrcSize > DstSize)
1409
34
      return Builder.CreateFPTrunc(Src, DstTy, "conv");
1410
1411
    // Promote a half vector to a float vector.
1412
104
    return Builder.CreateFPExt(Src, DstTy, "conv");
1413
138
  }
1414
1415
  // Finally, we have the arithmetic types: real int/float.
1416
140k
  Value *Res = nullptr;
1417
140k
  llvm::Type *ResTy = DstTy;
1418
1419
  // An overflowing conversion has undefined behavior if either the source type
1420
  // or the destination type is a floating-point type. However, we consider the
1421
  // range of representable values for all floating-point types to be
1422
  // [-inf,+inf], so no overflow can ever happen when the destination type is a
1423
  // floating-point type.
1424
140k
  if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
1425
140k
      
OrigSrcType->isFloatingType()32
)
1426
14
    EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1427
14
                             Loc);
1428
1429
  // Cast to half through float if half isn't a native type.
1430
140k
  if (DstType->isHalfType() && 
!CGF.getContext().getLangOpts().NativeHalfType970
) {
1431
    // Make sure we cast in a single step if from another FP type.
1432
631
    if (SrcTy->isFloatingPointTy()) {
1433
      // Use the intrinsic if the half type itself isn't supported
1434
      // (as opposed to operations on half, available with NativeHalfType).
1435
584
      if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1436
2
        return Builder.CreateCall(
1437
2
            CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1438
      // If the half type is supported, just use an fptrunc.
1439
582
      return Builder.CreateFPTrunc(Src, DstTy);
1440
584
    }
1441
47
    DstTy = CGF.FloatTy;
1442
47
  }
1443
1444
139k
  Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1445
1446
139k
  if (DstTy != ResTy) {
1447
47
    if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1448
14
      assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1449
0
      Res = Builder.CreateCall(
1450
14
        CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1451
14
        Res);
1452
33
    } else {
1453
33
      Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1454
33
    }
1455
47
  }
1456
1457
139k
  if (Opts.EmitImplicitIntegerTruncationChecks)
1458
942
    EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1459
942
                               NoncanonicalDstType, Loc);
1460
1461
139k
  if (Opts.EmitImplicitIntegerSignChangeChecks)
1462
873
    EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1463
873
                               NoncanonicalDstType, Loc);
1464
1465
139k
  return Res;
1466
140k
}
1467
1468
Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1469
                                                   QualType DstTy,
1470
288
                                                   SourceLocation Loc) {
1471
288
  llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1472
288
  llvm::Value *Result;
1473
288
  if (SrcTy->isRealFloatingType())
1474
60
    Result = FPBuilder.CreateFloatingToFixed(Src,
1475
60
        CGF.getContext().getFixedPointSemantics(DstTy));
1476
228
  else if (DstTy->isRealFloatingType())
1477
40
    Result = FPBuilder.CreateFixedToFloating(Src,
1478
40
        CGF.getContext().getFixedPointSemantics(SrcTy),
1479
40
        ConvertType(DstTy));
1480
188
  else {
1481
188
    auto SrcFPSema = CGF.getContext().getFixedPointSemantics(SrcTy);
1482
188
    auto DstFPSema = CGF.getContext().getFixedPointSemantics(DstTy);
1483
1484
188
    if (DstTy->isIntegerType())
1485
16
      Result = FPBuilder.CreateFixedToInteger(Src, SrcFPSema,
1486
16
                                              DstFPSema.getWidth(),
1487
16
                                              DstFPSema.isSigned());
1488
172
    else if (SrcTy->isIntegerType())
1489
18
      Result =  FPBuilder.CreateIntegerToFixed(Src, SrcFPSema.isSigned(),
1490
18
                                               DstFPSema);
1491
154
    else
1492
154
      Result = FPBuilder.CreateFixedToFixed(Src, SrcFPSema, DstFPSema);
1493
188
  }
1494
288
  return Result;
1495
288
}
1496
1497
/// Emit a conversion from the specified complex type to the specified
1498
/// destination type, where the destination type is an LLVM scalar type.
1499
Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1500
    CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1501
29
    SourceLocation Loc) {
1502
  // Get the source element type.
1503
29
  SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1504
1505
  // Handle conversions to bool first, they are special: comparisons against 0.
1506
29
  if (DstTy->isBooleanType()) {
1507
    //  Complex != 0  -> (Real != 0) | (Imag != 0)
1508
21
    Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1509
21
    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1510
21
    return Builder.CreateOr(Src.first, Src.second, "tobool");
1511
21
  }
1512
1513
  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1514
  // the imaginary part of the complex value is discarded and the value of the
1515
  // real part is converted according to the conversion rules for the
1516
  // corresponding real type.
1517
8
  return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1518
29
}
1519
1520
10.8k
Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1521
10.8k
  return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1522
10.8k
}
1523
1524
/// Emit a sanitization check for the given "binary" operation (which
1525
/// might actually be a unary increment which has been lowered to a binary
1526
/// operation). The check passes if all values in \p Checks (which are \c i1),
1527
/// are \c true.
1528
void ScalarExprEmitter::EmitBinOpCheck(
1529
100
    ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1530
100
  assert(CGF.IsSanitizerScope);
1531
0
  SanitizerHandler Check;
1532
100
  SmallVector<llvm::Constant *, 4> StaticData;
1533
100
  SmallVector<llvm::Value *, 2> DynamicData;
1534
1535
100
  BinaryOperatorKind Opcode = Info.Opcode;
1536
100
  if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1537
4
    Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1538
1539
100
  StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1540
100
  const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1541
100
  if (UO && 
UO->getOpcode() == UO_Minus11
) {
1542
4
    Check = SanitizerHandler::NegateOverflow;
1543
4
    StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1544
4
    DynamicData.push_back(Info.RHS);
1545
96
  } else {
1546
96
    if (BinaryOperator::isShiftOp(Opcode)) {
1547
      // Shift LHS negative or too large, or RHS out of bounds.
1548
19
      Check = SanitizerHandler::ShiftOutOfBounds;
1549
19
      const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1550
19
      StaticData.push_back(
1551
19
        CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1552
19
      StaticData.push_back(
1553
19
        CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1554
77
    } else if (Opcode == BO_Div || 
Opcode == BO_Rem65
) {
1555
      // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1556
15
      Check = SanitizerHandler::DivremOverflow;
1557
15
      StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1558
62
    } else {
1559
      // Arithmetic overflow (+, -, *).
1560
62
      switch (Opcode) {
1561
39
      case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1562
7
      case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1563
16
      case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1564
0
      default: llvm_unreachable("unexpected opcode for bin op check");
1565
62
      }
1566
62
      StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1567
62
    }
1568
96
    DynamicData.push_back(Info.LHS);
1569
96
    DynamicData.push_back(Info.RHS);
1570
96
  }
1571
1572
100
  CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1573
100
}
1574
1575
//===----------------------------------------------------------------------===//
1576
//                            Visitor Methods
1577
//===----------------------------------------------------------------------===//
1578
1579
0
Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1580
0
  CGF.ErrorUnsupported(E, "scalar expression");
1581
0
  if (E->getType()->isVoidType())
1582
0
    return nullptr;
1583
0
  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1584
0
}
1585
1586
Value *
1587
24
ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
1588
24
  ASTContext &Context = CGF.getContext();
1589
24
  llvm::Optional<LangAS> GlobalAS =
1590
24
      Context.getTargetInfo().getConstantAddressSpace();
1591
24
  llvm::Constant *GlobalConstStr = Builder.CreateGlobalStringPtr(
1592
24
      E->ComputeName(Context), "__usn_str",
1593
24
      static_cast<unsigned>(GlobalAS.getValueOr(LangAS::Default)));
1594
1595
24
  unsigned ExprAS = Context.getTargetAddressSpace(E->getType());
1596
1597
24
  if (GlobalConstStr->getType()->getPointerAddressSpace() == ExprAS)
1598
3
    return GlobalConstStr;
1599
1600
21
  llvm::Type *EltTy = GlobalConstStr->getType()->getPointerElementType();
1601
21
  llvm::PointerType *NewPtrTy = llvm::PointerType::get(EltTy, ExprAS);
1602
21
  return Builder.CreateAddrSpaceCast(GlobalConstStr, NewPtrTy, "usn_addr_cast");
1603
24
}
1604
1605
1.00k
Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1606
  // Vector Mask Case
1607
1.00k
  if (E->getNumSubExprs() == 2) {
1608
1
    Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1609
1
    Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1610
1
    Value *Mask;
1611
1612
1
    auto *LTy = cast<llvm::FixedVectorType>(LHS->getType());
1613
1
    unsigned LHSElts = LTy->getNumElements();
1614
1615
1
    Mask = RHS;
1616
1617
1
    auto *MTy = cast<llvm::FixedVectorType>(Mask->getType());
1618
1619
    // Mask off the high bits of each shuffle index.
1620
1
    Value *MaskBits =
1621
1
        llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1622
1
    Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1623
1624
    // newv = undef
1625
    // mask = mask & maskbits
1626
    // for each elt
1627
    //   n = extract mask i
1628
    //   x = extract val n
1629
    //   newv = insert newv, x, i
1630
1
    auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
1631
1
                                           MTy->getNumElements());
1632
1
    Value* NewV = llvm::UndefValue::get(RTy);
1633
5
    for (unsigned i = 0, e = MTy->getNumElements(); i != e; 
++i4
) {
1634
4
      Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1635
4
      Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1636
1637
4
      Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1638
4
      NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1639
4
    }
1640
1
    return NewV;
1641
1
  }
1642
1643
1.00k
  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1644
1.00k
  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1645
1646
1.00k
  SmallVector<int, 32> Indices;
1647
8.45k
  for (unsigned i = 2; i < E->getNumSubExprs(); 
++i7.44k
) {
1648
7.44k
    llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1649
    // Check for -1 and output it as undef in the IR.
1650
7.44k
    if (Idx.isSigned() && Idx.isAllOnesValue())
1651
373
      Indices.push_back(-1);
1652
7.07k
    else
1653
7.07k
      Indices.push_back(Idx.getZExtValue());
1654
7.44k
  }
1655
1656
1.00k
  return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
1657
1.00k
}
1658
1659
373
Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1660
373
  QualType SrcType = E->getSrcExpr()->getType(),
1661
373
           DstType = E->getType();
1662
1663
373
  Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
1664
1665
373
  SrcType = CGF.getContext().getCanonicalType(SrcType);
1666
373
  DstType = CGF.getContext().getCanonicalType(DstType);
1667
373
  if (SrcType == DstType) 
return Src0
;
1668
1669
373
  assert(SrcType->isVectorType() &&
1670
373
         "ConvertVector source type must be a vector");
1671
0
  assert(DstType->isVectorType() &&
1672
373
         "ConvertVector destination type must be a vector");
1673
1674
0
  llvm::Type *SrcTy = Src->getType();
1675
373
  llvm::Type *DstTy = ConvertType(DstType);
1676
1677
  // Ignore conversions like int -> uint.
1678
373
  if (SrcTy == DstTy)
1679
0
    return Src;
1680
1681
373
  QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1682
373
           DstEltType = DstType->castAs<VectorType>()->getElementType();
1683
1684
373
  assert(SrcTy->isVectorTy() &&
1685
373
         "ConvertVector source IR type must be a vector");
1686
0
  assert(DstTy->isVectorTy() &&
1687
373
         "ConvertVector destination IR type must be a vector");
1688
1689
0
  llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
1690
373
             *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
1691
1692
373
  if (DstEltType->isBooleanType()) {
1693
0
    assert((SrcEltTy->isFloatingPointTy() ||
1694
0
            isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1695
1696
0
    llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1697
0
    if (SrcEltTy->isFloatingPointTy()) {
1698
0
      return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1699
0
    } else {
1700
0
      return Builder.CreateICmpNE(Src, Zero, "tobool");
1701
0
    }
1702
0
  }
1703
1704
  // We have the arithmetic types: real int/float.
1705
373
  Value *Res = nullptr;
1706
1707
373
  if (isa<llvm::IntegerType>(SrcEltTy)) {
1708
269
    bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1709
269
    if (isa<llvm::IntegerType>(DstEltTy))
1710
138
      Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1711
131
    else if (InputSigned)
1712
75
      Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1713
56
    else
1714
56
      Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1715
269
  } else 
if (104
isa<llvm::IntegerType>(DstEltTy)104
) {
1716
72
    assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1717
72
    if (DstEltType->isSignedIntegerOrEnumerationType())
1718
35
      Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1719
37
    else
1720
37
      Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1721
72
  } else {
1722
32
    assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1723
32
           "Unknown real conversion");
1724
32
    if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1725
11
      Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1726
21
    else
1727
21
      Res = Builder.CreateFPExt(Src, DstTy, "conv");
1728
32
  }
1729
1730
0
  return Res;
1731
373
}
1732
1733
110k
Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1734
110k
  if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1735
11
    CGF.EmitIgnoredExpr(E->getBase());
1736
11
    return CGF.emitScalarConstant(Constant, E);
1737
110k
  } else {
1738
110k
    Expr::EvalResult Result;
1739
110k
    if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1740
59
      llvm::APSInt Value = Result.Val.getInt();
1741
59
      CGF.EmitIgnoredExpr(E->getBase());
1742
59
      return Builder.getInt(Value);
1743
59
    }
1744
110k
  }
1745
1746
110k
  return EmitLoadOfLValue(E);
1747
110k
}
1748
1749
13.7k
Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1750
13.7k
  TestAndClearIgnoreResultAssign();
1751
1752
  // Emit subscript expressions in rvalue context's.  For most cases, this just
1753
  // loads the lvalue formed by the subscript expr.  However, we have to be
1754
  // careful, because the base of a vector subscript is occasionally an rvalue,
1755
  // so we can't get it as an lvalue.
1756
13.7k
  if (!E->getBase()->getType()->isVectorType())
1757
11.0k
    return EmitLoadOfLValue(E);
1758
1759
  // Handle the vector case.  The base must be a vector, the index must be an
1760
  // integer value.
1761
2.70k
  Value *Base = Visit(E->getBase());
1762
2.70k
  Value *Idx  = Visit(E->getIdx());
1763
2.70k
  QualType IdxTy = E->getIdx()->getType();
1764
1765
2.70k
  if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1766
1
    CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1767
1768
2.70k
  return Builder.CreateExtractElement(Base, Idx, "vecext");
1769
13.7k
}
1770
1771
13
Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
1772
13
  TestAndClearIgnoreResultAssign();
1773
1774
  // Handle the vector case.  The base must be a vector, the index must be an
1775
  // integer value.
1776
13
  Value *RowIdx = Visit(E->getRowIdx());
1777
13
  Value *ColumnIdx = Visit(E->getColumnIdx());
1778
13
  Value *Matrix = Visit(E->getBase());
1779
1780
  // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
1781
13
  llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
1782
13
  return MB.CreateExtractElement(
1783
13
      Matrix, RowIdx, ColumnIdx,
1784
13
      E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
1785
13
}
1786
1787
static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1788
0
                      unsigned Off) {
1789
0
  int MV = SVI->getMaskValue(Idx);
1790
0
  if (MV == -1)
1791
0
    return -1;
1792
0
  return Off + MV;
1793
0
}
1794
1795
1
static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1796
1
  assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
1797
1
         "Index operand too large for shufflevector mask!");
1798
0
  return C->getZExtValue();
1799
1
}
1800
1801
2.99k
Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1802
2.99k
  bool Ignore = TestAndClearIgnoreResultAssign();
1803
2.99k
  (void)Ignore;
1804
2.99k
  assert (Ignore == false && "init list ignored");
1805
0
  unsigned NumInitElements = E->getNumInits();
1806
1807
2.99k
  if (E->hadArrayRangeDesignator())
1808
0
    CGF.ErrorUnsupported(E, "GNU array range designator extension");
1809
1810
2.99k
  llvm::VectorType *VType =
1811
2.99k
    dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1812
1813
2.99k
  if (!VType) {
1814
269
    if (NumInitElements == 0) {
1815
      // C++11 value-initialization for the scalar.
1816
218
      return EmitNullValue(E->getType());
1817
218
    }
1818
    // We have a scalar in braces. Just use the first element.
1819
51
    return Visit(E->getInit(0));
1820
269
  }
1821
1822
2.72k
  unsigned ResElts = cast<llvm::FixedVectorType>(VType)->getNumElements();
1823
1824
  // Loop over initializers collecting the Value for each, and remembering
1825
  // whether the source was swizzle (ExtVectorElementExpr).  This will allow
1826
  // us to fold the shuffle for the swizzle into the shuffle for the vector
1827
  // initializer, since LLVM optimizers generally do not want to touch
1828
  // shuffles.
1829
2.72k
  unsigned CurIdx = 0;
1830
2.72k
  bool VIsUndefShuffle = false;
1831
2.72k
  llvm::Value *V = llvm::UndefValue::get(VType);
1832
24.1k
  for (unsigned i = 0; i != NumInitElements; 
++i21.4k
) {
1833
21.4k
    Expr *IE = E->getInit(i);
1834
21.4k
    Value *Init = Visit(IE);
1835
21.4k
    SmallVector<int, 16> Args;
1836
1837
21.4k
    llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1838
1839
    // Handle scalar elements.  If the scalar initializer is actually one
1840
    // element of a different vector of the same width, use shuffle instead of
1841
    // extract+insert.
1842
21.4k
    if (!VVT) {
1843
21.4k
      if (isa<ExtVectorElementExpr>(IE)) {
1844
1
        llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1845
1846
1
        if (cast<llvm::FixedVectorType>(EI->getVectorOperandType())
1847
1
                ->getNumElements() == ResElts) {
1848
1
          llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1849
1
          Value *LHS = nullptr, *RHS = nullptr;
1850
1
          if (CurIdx == 0) {
1851
            // insert into undef -> shuffle (src, undef)
1852
            // shufflemask must use an i32
1853
1
            Args.push_back(getAsInt32(C, CGF.Int32Ty));
1854
1
            Args.resize(ResElts, -1);
1855
1856
1
            LHS = EI->getVectorOperand();
1857
1
            RHS = V;
1858
1
            VIsUndefShuffle = true;
1859
1
          } else 
if (0
VIsUndefShuffle0
) {
1860
            // insert into undefshuffle && size match -> shuffle (v, src)
1861
0
            llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1862
0
            for (unsigned j = 0; j != CurIdx; ++j)
1863
0
              Args.push_back(getMaskElt(SVV, j, 0));
1864
0
            Args.push_back(ResElts + C->getZExtValue());
1865
0
            Args.resize(ResElts, -1);
1866
1867
0
            LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1868
0
            RHS = EI->getVectorOperand();
1869
0
            VIsUndefShuffle = false;
1870
0
          }
1871
1
          if (!Args.empty()) {
1872
1
            V = Builder.CreateShuffleVector(LHS, RHS, Args);
1873
1
            ++CurIdx;
1874
1
            continue;
1875
1
          }
1876
1
        }
1877
1
      }
1878
21.4k
      V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1879
21.4k
                                      "vecinit");
1880
21.4k
      VIsUndefShuffle = false;
1881
21.4k
      ++CurIdx;
1882
21.4k
      continue;
1883
21.4k
    }
1884
1885
26
    unsigned InitElts = cast<llvm::FixedVectorType>(VVT)->getNumElements();
1886
1887
    // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1888
    // input is the same width as the vector being constructed, generate an
1889
    // optimized shuffle of the swizzle input into the result.
1890
26
    unsigned Offset = (CurIdx == 0) ? 
011
:
ResElts15
;
1891
26
    if (isa<ExtVectorElementExpr>(IE)) {
1892
0
      llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1893
0
      Value *SVOp = SVI->getOperand(0);
1894
0
      auto *OpTy = cast<llvm::FixedVectorType>(SVOp->getType());
1895
1896
0
      if (OpTy->getNumElements() == ResElts) {
1897
0
        for (unsigned j = 0; j != CurIdx; ++j) {
1898
          // If the current vector initializer is a shuffle with undef, merge
1899
          // this shuffle directly into it.
1900
0
          if (VIsUndefShuffle) {
1901
0
            Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0));
1902
0
          } else {
1903
0
            Args.push_back(j);
1904
0
          }
1905
0
        }
1906
0
        for (unsigned j = 0, je = InitElts; j != je; ++j)
1907
0
          Args.push_back(getMaskElt(SVI, j, Offset));
1908
0
        Args.resize(ResElts, -1);
1909
1910
0
        if (VIsUndefShuffle)
1911
0
          V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1912
1913
0
        Init = SVOp;
1914
0
      }
1915
0
    }
1916
1917
    // Extend init to result vector length, and then shuffle its contribution
1918
    // to the vector initializer into V.
1919
26
    if (Args.empty()) {
1920
88
      for (unsigned j = 0; j != InitElts; 
++j62
)
1921
62
        Args.push_back(j);
1922
26
      Args.resize(ResElts, -1);
1923
26
      Init = Builder.CreateShuffleVector(Init, Args, "vext");
1924
1925
26
      Args.clear();
1926
56
      for (unsigned j = 0; j != CurIdx; 
++j30
)
1927
30
        Args.push_back(j);
1928
88
      for (unsigned j = 0; j != InitElts; 
++j62
)
1929
62
        Args.push_back(j + Offset);
1930
26
      Args.resize(ResElts, -1);
1931
26
    }
1932
1933
    // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1934
    // merging subsequent shuffles into this one.
1935
26
    if (CurIdx == 0)
1936
11
      std::swap(V, Init);
1937
26
    V = Builder.CreateShuffleVector(V, Init, Args, "vecinit");
1938
26
    VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1939
26
    CurIdx += InitElts;
1940
26
  }
1941
1942
  // FIXME: evaluate codegen vs. shuffling against constant null vector.
1943
  // Emit remaining default initializers.
1944
2.72k
  llvm::Type *EltTy = VType->getElementType();
1945
1946
  // Emit remaining default initializers
1947
4.22k
  for (/* Do not initialize i*/; CurIdx < ResElts; 
++CurIdx1.50k
) {
1948
1.50k
    Value *Idx = Builder.getInt32(CurIdx);
1949
1.50k
    llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1950
1.50k
    V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1951
1.50k
  }
1952
2.72k
  return V;
1953
2.99k
}
1954
1955
12.3k
bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
1956
12.3k
  const Expr *E = CE->getSubExpr();
1957
1958
12.3k
  if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1959
10.4k
    return false;
1960
1961
1.82k
  if (isa<CXXThisExpr>(E->IgnoreParens())) {
1962
    // We always assume that 'this' is never null.
1963
53
    return false;
1964
53
  }
1965
1966
1.77k
  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1967
    // And that glvalue casts are never null.
1968
1.12k
    if (ICE->isGLValue())
1969
0
      return false;
1970
1.12k
  }
1971
1972
1.77k
  return true;
1973
1.77k
}
1974
1975
// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1976
// have to handle a more broad range of conversions than explicit casts, as they
1977
// handle things like function to ptr-to-function decay etc.
1978
2.15M
Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1979
2.15M
  Expr *E = CE->getSubExpr();
1980
2.15M
  QualType DestTy = CE->getType();
1981
2.15M
  CastKind Kind = CE->getCastKind();
1982
1983
  // These cases are generally not written to ignore the result of
1984
  // evaluating their sub-expressions, so we clear this now.
1985
2.15M
  bool Ignored = TestAndClearIgnoreResultAssign();
1986
1987
  // Since almost all cast kinds apply to scalars, this switch doesn't have
1988
  // a default case, so the compiler will warn on a missing case.  The cases
1989
  // are in the same order as in the CastKind enum.
1990
2.15M
  switch (Kind) {
1991
0
  case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1992
0
  case CK_BuiltinFnToFnPtr:
1993
0
    llvm_unreachable("builtin functions are handled elsewhere");
1994
1995
19
  case CK_LValueBitCast:
1996
19
  case CK_ObjCObjectLValueCast: {
1997
19
    Address Addr = EmitLValue(E).getAddress(CGF);
1998
19
    Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
1999
19
    LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
2000
19
    return EmitLoadOfLValue(LV, CE->getExprLoc());
2001
19
  }
2002
2003
44
  case CK_LValueToRValueBitCast: {
2004
44
    LValue SourceLVal = CGF.EmitLValue(E);
2005
44
    Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
2006
44
                                                CGF.ConvertTypeForMem(DestTy));
2007
44
    LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2008
44
    DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2009
44
    return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2010
19
  }
2011
2012
5.53k
  case CK_CPointerToObjCPointerCast:
2013
5.54k
  case CK_BlockPointerToObjCPointerCast:
2014
5.55k
  case CK_AnyPointerToBlockPointerCast:
2015
162k
  case CK_BitCast: {
2016
162k
    Value *Src = Visit(const_cast<Expr*>(E));
2017
162k
    llvm::Type *SrcTy = Src->getType();
2018
162k
    llvm::Type *DstTy = ConvertType(DestTy);
2019
162k
    if (SrcTy->isPtrOrPtrVectorTy() && 
DstTy->isPtrOrPtrVectorTy()62.4k
&&
2020
162k
        
SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()62.4k
) {
2021
0
      llvm_unreachable("wrong cast for pointers in different address spaces"
2022
0
                       "(must be an address space cast)!");
2023
0
    }
2024
2025
162k
    if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2026
9
      if (auto PT = DestTy->getAs<PointerType>())
2027
9
        CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
2028
9
                                      /*MayBeNull=*/true,
2029
9
                                      CodeGenFunction::CFITCK_UnrelatedCast,
2030
9
                                      CE->getBeginLoc());
2031
9
    }
2032
2033
162k
    if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2034
13
      const QualType SrcType = E->getType();
2035
2036
13
      if (SrcType.mayBeNotDynamicClass() && 
DestTy.mayBeDynamicClass()10
) {
2037
        // Casting to pointer that could carry dynamic information (provided by
2038
        // invariant.group) requires launder.
2039
8
        Src = Builder.CreateLaunderInvariantGroup(Src);
2040
8
      } else 
if (5
SrcType.mayBeDynamicClass()5
&&
DestTy.mayBeNotDynamicClass()5
) {
2041
        // Casting to pointer that does not carry dynamic information (provided
2042
        // by invariant.group) requires stripping it.  Note that we don't do it
2043
        // if the source could not be dynamic type and destination could be
2044
        // dynamic because dynamic information is already laundered.  It is
2045
        // because launder(strip(src)) == launder(src), so there is no need to
2046
        // add extra strip before launder.
2047
5
        Src = Builder.CreateStripInvariantGroup(Src);
2048
5
      }
2049
13
    }
2050
2051
    // Update heapallocsite metadata when there is an explicit pointer cast.
2052
162k
    if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
2053
19.4k
      if (CI->getMetadata("heapallocsite") && 
isa<ExplicitCastExpr>(CE)3
) {
2054
2
        QualType PointeeType = DestTy->getPointeeType();
2055
2
        if (!PointeeType.isNull())
2056
2
          CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
2057
2
                                                       CE->getExprLoc());
2058
2
      }
2059
19.4k
    }
2060
2061
    // If Src is a fixed vector and Dst is a scalable vector, and both have the
2062
    // same element type, use the llvm.experimental.vector.insert intrinsic to
2063
    // perform the bitcast.
2064
162k
    if (const auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2065
99.8k
      if (const auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(DstTy)) {
2066
        // If we are casting a fixed i8 vector to a scalable 16 x i1 predicate
2067
        // vector, use a vector insert and bitcast the result.
2068
45
        bool NeedsBitCast = false;
2069
45
        auto PredType = llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
2070
45
        llvm::Type *OrigType = DstTy;
2071
45
        if (ScalableDst == PredType &&
2072
45
            
FixedSrc->getElementType() == Builder.getInt8Ty()13
) {
2073
13
          DstTy = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
2074
13
          ScalableDst = dyn_cast<llvm::ScalableVectorType>(DstTy);
2075
13
          NeedsBitCast = true;
2076
13
        }
2077
45
        if (FixedSrc->getElementType() == ScalableDst->getElementType()) {
2078
44
          llvm::Value *UndefVec = llvm::UndefValue::get(DstTy);
2079
44
          llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
2080
44
          llvm::Value *Result = Builder.CreateInsertVector(
2081
44
              DstTy, UndefVec, Src, Zero, "castScalableSve");
2082
44
          if (NeedsBitCast)
2083
13
            Result = Builder.CreateBitCast(Result, OrigType);
2084
44
          return Result;
2085
44
        }
2086
45
      }
2087
99.8k
    }
2088
2089
    // If Src is a scalable vector and Dst is a fixed vector, and both have the
2090
    // same element type, use the llvm.experimental.vector.extract intrinsic to
2091
    // perform the bitcast.
2092
162k
    if (const auto *ScalableSrc = dyn_cast<llvm::ScalableVectorType>(SrcTy)) {
2093
40
      if (const auto *FixedDst = dyn_cast<llvm::FixedVectorType>(DstTy)) {
2094
        // If we are casting a scalable 16 x i1 predicate vector to a fixed i8
2095
        // vector, bitcast the source and use a vector extract.
2096
40
        auto PredType = llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
2097
40
        if (ScalableSrc == PredType &&
2098
40
            
FixedDst->getElementType() == Builder.getInt8Ty()9
) {
2099
9
          SrcTy = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
2100
9
          ScalableSrc = dyn_cast<llvm::ScalableVectorType>(SrcTy);
2101
9
          Src = Builder.CreateBitCast(Src, SrcTy);
2102
9
        }
2103
40
        if (ScalableSrc->getElementType() == FixedDst->getElementType()) {
2104
40
          llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
2105
40
          return Builder.CreateExtractVector(DstTy, Src, Zero, "castFixedSve");
2106
40
        }
2107
40
      }
2108
40
    }
2109
2110
    // Perform VLAT <-> VLST bitcast through memory.
2111
    // TODO: since the llvm.experimental.vector.{insert,extract} intrinsics
2112
    //       require the element types of the vectors to be the same, we
2113
    //       need to keep this around for bitcasts between VLAT <-> VLST where
2114
    //       the element types of the vectors are not the same, until we figure
2115
    //       out a better way of doing these casts.
2116
162k
    if ((isa<llvm::FixedVectorType>(SrcTy) &&
2117
162k
         
isa<llvm::ScalableVectorType>(DstTy)99.7k
) ||
2118
162k
        
(162k
isa<llvm::ScalableVectorType>(SrcTy)162k
&&
2119
162k
         
isa<llvm::FixedVectorType>(DstTy)0
)) {
2120
1
      Address Addr = CGF.CreateDefaultAlignTempAlloca(SrcTy, "saved-value");
2121
1
      LValue LV = CGF.MakeAddrLValue(Addr, E->getType());
2122
1
      CGF.EmitStoreOfScalar(Src, LV);
2123
1
      Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy),
2124
1
                                          "castFixedSve");
2125
1
      LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2126
1
      DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2127
1
      return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2128
1
    }
2129
2130
162k
    return Builder.CreateBitCast(Src, DstTy);
2131
162k
  }
2132
313
  case CK_AddressSpaceConversion: {
2133
313
    Expr::EvalResult Result;
2134
313
    if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2135
313
        
Result.Val.isNullPointer()174
) {
2136
      // If E has side effect, it is emitted even if its final result is a
2137
      // null pointer. In that case, a DCE pass should be able to
2138
      // eliminate the useless instructions emitted during translating E.
2139
164
      if (Result.HasSideEffects)
2140
0
        Visit(E);
2141
164
      return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2142
164
          ConvertType(DestTy)), DestTy);
2143
164
    }
2144
    // Since target may map different address spaces in AST to the same address
2145
    // space, an address space conversion may end up as a bitcast.
2146
149
    return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2147
149
        CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2148
149
        DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2149
313
  }
2150
26
  case CK_AtomicToNonAtomic:
2151
71
  case CK_NonAtomicToAtomic:
2152
180k
  case CK_NoOp:
2153
181k
  case CK_UserDefinedConversion:
2154
181k
    return Visit(const_cast<Expr*>(E));
2155
2156
648
  case CK_BaseToDerived: {
2157
648
    const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2158
648
    assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2159
2160
0
    Address Base = CGF.EmitPointerWithAlignment(E);
2161
648
    Address Derived =
2162
648
      CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2163
648
                                   CE->path_begin(), CE->path_end(),
2164
648
                                   CGF.ShouldNullCheckClassCastValue(CE));
2165
2166
    // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2167
    // performed and the object is not of the derived type.
2168
648
    if (CGF.sanitizePerformTypeCheck())
2169
10
      CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2170
10
                        Derived.getPointer(), DestTy->getPointeeType());
2171
2172
648
    if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2173
3
      CGF.EmitVTablePtrCheckForCast(
2174
3
          DestTy->getPointeeType(), Derived.getPointer(),
2175
3
          /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2176
3
          CE->getBeginLoc());
2177
2178
648
    return Derived.getPointer();
2179
180k
  }
2180
145
  case CK_UncheckedDerivedToBase:
2181
1.29k
  case CK_DerivedToBase: {
2182
    // The EmitPointerWithAlignment path does this fine; just discard
2183
    // the alignment.
2184
1.29k
    return CGF.EmitPointerWithAlignment(CE).getPointer();
2185
145
  }
2186
2187
64
  case CK_Dynamic: {
2188
64
    Address V = CGF.EmitPointerWithAlignment(E);
2189
64
    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2190
64
    return CGF.EmitDynamicCast(V, DCE);
2191
145
  }
2192
2193
86.3k
  case CK_ArrayToPointerDecay:
2194
86.3k
    return CGF.EmitArrayToPointerDecay(E).getPointer();
2195
2.64k
  case CK_FunctionToPointerDecay:
2196
2.64k
    return EmitLValue(E).getPointer(CGF);
2197
2198
16.2k
  case CK_NullToPointer:
2199
16.2k
    if (MustVisitNullValue(E))
2200
6.46k
      CGF.EmitIgnoredExpr(E);
2201
2202
16.2k
    return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2203
16.2k
                              DestTy);
2204
2205
49
  case CK_NullToMemberPointer: {
2206
49
    if (MustVisitNullValue(E))
2207
13
      CGF.EmitIgnoredExpr(E);
2208
2209
49
    const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2210
49
    return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2211
145
  }
2212
2213
10
  case CK_ReinterpretMemberPointer:
2214
118
  case CK_BaseToDerivedMemberPointer:
2215
131
  case CK_DerivedToBaseMemberPointer: {
2216
131
    Value *Src = Visit(E);
2217
2218
    // Note that the AST doesn't distinguish between checked and
2219
    // unchecked member pointer conversions, so we always have to
2220
    // implement checked conversions here.  This is inefficient when
2221
    // actual control flow may be required in order to perform the
2222
    // check, which it is for data member pointers (but not member
2223
    // function pointers on Itanium and ARM).
2224
131
    return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2225
118
  }
2226
2227
197
  case CK_ARCProduceObject:
2228
197
    return CGF.EmitARCRetainScalarExpr(E);
2229
19
  case CK_ARCConsumeObject:
2230
19
    return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2231
104
  case CK_ARCReclaimReturnedObject:
2232
104
    return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2233
11
  case CK_ARCExtendBlockObject:
2234
11
    return CGF.EmitARCExtendBlockObject(E);
2235
2236
5
  case CK_CopyAndAutoreleaseBlockObject:
2237
5
    return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2238
2239
0
  case CK_FloatingRealToComplex:
2240
0
  case CK_FloatingComplexCast:
2241
0
  case CK_IntegralRealToComplex:
2242
0
  case CK_IntegralComplexCast:
2243
0
  case CK_IntegralComplexToFloatingComplex:
2244
0
  case CK_FloatingComplexToIntegralComplex:
2245
0
  case CK_ConstructorConversion:
2246
0
  case CK_ToUnion:
2247
0
    llvm_unreachable("scalar cast to non-scalar value");
2248
2249
1.40M
  case CK_LValueToRValue:
2250
1.40M
    assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2251
0
    assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2252
0
    return Visit(const_cast<Expr*>(E));
2253
2254
779
  case CK_IntegralToPointer: {
2255
779
    Value *Src = Visit(const_cast<Expr*>(E));
2256
2257
    // First, convert to the correct width so that we control the kind of
2258
    // extension.
2259
779
    auto DestLLVMTy = ConvertType(DestTy);
2260
779
    llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2261
779
    bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2262
779
    llvm::Value* IntResult =
2263
779
      Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2264
2265
779
    auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2266
2267
779
    if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2268
      // Going from integer to pointer that could be dynamic requires reloading
2269
      // dynamic information from invariant.group.
2270
5
      if (DestTy.mayBeDynamicClass())
2271
2
        IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2272
5
    }
2273
779
    return IntToPtr;
2274
0
  }
2275
199
  case CK_PointerToIntegral: {
2276
199
    assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2277
0
    auto *PtrExpr = Visit(E);
2278
2279
199
    if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2280
5
      const QualType SrcType = E->getType();
2281
2282
      // Casting to integer requires stripping dynamic information as it does
2283
      // not carries it.
2284
5
      if (SrcType.mayBeDynamicClass())
2285
2
        PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2286
5
    }
2287
2288
199
    return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2289
0
  }
2290
3.33k
  case CK_ToVoid: {
2291
3.33k
    CGF.EmitIgnoredExpr(E);
2292
3.33k
    return nullptr;
2293
0
  }
2294
39
  case CK_MatrixCast: {
2295
39
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2296
39
                                CE->getExprLoc());
2297
0
  }
2298
1.39k
  case CK_VectorSplat: {
2299
1.39k
    llvm::Type *DstTy = ConvertType(DestTy);
2300
1.39k
    Value *Elt = Visit(const_cast<Expr*>(E));
2301
    // Splat the element across to all elements
2302
1.39k
    unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
2303
1.39k
    return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2304
0
  }
2305
2306
70
  case CK_FixedPointCast:
2307
70
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2308
70
                                CE->getExprLoc());
2309
2310
20
  case CK_FixedPointToBoolean:
2311
20
    assert(E->getType()->isFixedPointType() &&
2312
20
           "Expected src type to be fixed point type");
2313
0
    assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2314
0
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2315
20
                                CE->getExprLoc());
2316
2317
4
  case CK_FixedPointToIntegral:
2318
4
    assert(E->getType()->isFixedPointType() &&
2319
4
           "Expected src type to be fixed point type");
2320
0
    assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2321
0
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2322
4
                                CE->getExprLoc());
2323
2324
18
  case CK_IntegralToFixedPoint:
2325
18
    assert(E->getType()->isIntegerType() &&
2326
18
           "Expected src type to be an integer");
2327
0
    assert(DestTy->isFixedPointType() &&
2328
18
           "Expected dest type to be fixed point type");
2329
0
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2330
18
                                CE->getExprLoc());
2331
2332
187k
  case CK_IntegralCast: {
2333
187k
    ScalarConversionOpts Opts;
2334
187k
    if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2335
184k
      if (!ICE->isPartOfExplicitCast())
2336
176k
        Opts = ScalarConversionOpts(CGF.SanOpts);
2337
184k
    }
2338
187k
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2339
187k
                                CE->getExprLoc(), Opts);
2340
0
  }
2341
8.55k
  case CK_IntegralToFloating:
2342
10.1k
  case CK_FloatingToIntegral:
2343
17.2k
  case CK_FloatingCast:
2344
17.2k
  case CK_FixedPointToFloating:
2345
17.3k
  case CK_FloatingToFixedPoint: {
2346
17.3k
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2347
17.3k
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2348
17.3k
                                CE->getExprLoc());
2349
17.2k
  }
2350
9
  case CK_BooleanToSignedIntegral: {
2351
9
    ScalarConversionOpts Opts;
2352
9
    Opts.TreatBooleanAsSigned = true;
2353
9
    return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2354
9
                                CE->getExprLoc(), Opts);
2355
17.2k
  }
2356
78.1k
  case CK_IntegralToBoolean:
2357
78.1k
    return EmitIntToBoolConversion(Visit(E));
2358
8.32k
  case CK_PointerToBoolean:
2359
8.32k
    return EmitPointerToBoolConversion(Visit(E), E->getType());
2360
88
  case CK_FloatingToBoolean: {
2361
88
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2362
88
    return EmitFloatToBoolConversion(Visit(E));
2363
17.2k
  }
2364
55
  case CK_MemberPointerToBoolean: {
2365
55
    llvm::Value *MemPtr = Visit(E);
2366
55
    const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2367
55
    return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2368
17.2k
  }
2369
2370
10
  case CK_FloatingComplexToReal:
2371
44
  case CK_IntegralComplexToReal:
2372
44
    return CGF.EmitComplexExpr(E, false, true).first;
2373
2374
0
  case CK_FloatingComplexToBoolean:
2375
20
  case CK_IntegralComplexToBoolean: {
2376
20
    CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2377
2378
    // TODO: kill this function off, inline appropriate case here
2379
20
    return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2380
20
                                         CE->getExprLoc());
2381
0
  }
2382
2383
24
  case CK_ZeroToOCLOpaqueType: {
2384
24
    assert((DestTy->isEventT() || DestTy->isQueueT() ||
2385
24
            DestTy->isOCLIntelSubgroupAVCType()) &&
2386
24
           "CK_ZeroToOCLEvent cast on non-event type");
2387
0
    return llvm::Constant::getNullValue(ConvertType(DestTy));
2388
0
  }
2389
2390
22
  case CK_IntToOCLSampler:
2391
22
    return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2392
2393
2.15M
  } // end of switch
2394
2395
0
  llvm_unreachable("unknown scalar cast");
2396
0
}
2397
2398
3.66k
Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2399
3.66k
  CodeGenFunction::StmtExprEvaluation eval(CGF);
2400
3.66k
  Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2401
3.66k
                                           !E->getType()->isVoidType());
2402
3.66k
  if (!RetAlloca.isValid())
2403
603
    return nullptr;
2404
3.06k
  return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2405
3.06k
                              E->getExprLoc());
2406
3.66k
}
2407
2408
8.22k
Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2409
8.22k
  CodeGenFunction::RunCleanupsScope Scope(CGF);
2410
8.22k
  Value *V = Visit(E->getSubExpr());
2411
  // Defend against dominance problems caused by jumps out of expression
2412
  // evaluation through the shared cleanup block.
2413
8.22k
  Scope.ForceCleanup({&V});
2414
8.22k
  return V;
2415
8.22k
}
2416
2417
//===----------------------------------------------------------------------===//
2418
//                             Unary Operators
2419
//===----------------------------------------------------------------------===//
2420
2421
static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2422
                                           llvm::Value *InVal, bool IsInc,
2423
13
                                           FPOptions FPFeatures) {
2424
13
  BinOpInfo BinOp;
2425
13
  BinOp.LHS = InVal;
2426
13
  BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2427
13
  BinOp.Ty = E->getType();
2428
13
  BinOp.Opcode = IsInc ? 
BO_Add10
:
BO_Sub3
;
2429
13
  BinOp.FPFeatures = FPFeatures;
2430
13
  BinOp.E = E;
2431
13
  return BinOp;
2432
13
}
2433
2434
llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2435
8.39k
    const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2436
8.39k
  llvm::Value *Amount =
2437
8.39k
      llvm::ConstantInt::get(InVal->getType(), IsInc ? 
18.10k
:
-1291
, true);
2438
8.39k
  StringRef Name = IsInc ? 
"inc"8.10k
:
"dec"291
;
2439
8.39k
  switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2440
2
  case LangOptions::SOB_Defined:
2441
2
    return Builder.CreateAdd(InVal, Amount, Name);
2442
8.39k
  case LangOptions::SOB_Undefined:
2443
8.39k
    if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2444
8.38k
      return Builder.CreateNSWAdd(InVal, Amount, Name);
2445
8.39k
    
LLVM_FALLTHROUGH2
;2
2446
8
  case LangOptions::SOB_Trapping:
2447
8
    if (!E->canOverflow())
2448
0
      return Builder.CreateNSWAdd(InVal, Amount, Name);
2449
8
    return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2450
8
        E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
2451
8.39k
  }
2452
0
  llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2453
0
}
2454
2455
namespace {
2456
/// Handles check and update for lastprivate conditional variables.
2457
class OMPLastprivateConditionalUpdateRAII {
2458
private:
2459
  CodeGenFunction &CGF;
2460
  const UnaryOperator *E;
2461
2462
public:
2463
  OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2464
                                      const UnaryOperator *E)
2465
30.6k
      : CGF(CGF), E(E) {}
2466
30.6k
  ~OMPLastprivateConditionalUpdateRAII() {
2467
30.6k
    if (CGF.getLangOpts().OpenMP)
2468
7.95k
      CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2469
7.95k
          CGF, E->getSubExpr());
2470
30.6k
  }
2471
};
2472
} // namespace
2473
2474
llvm::Value *
2475
ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2476
30.6k
                                           bool isInc, bool isPre) {
2477
30.6k
  OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
2478
30.6k
  QualType type = E->getSubExpr()->getType();
2479
30.6k
  llvm::PHINode *atomicPHI = nullptr;
2480
30.6k
  llvm::Value *value;
2481
30.6k
  llvm::Value *input;
2482
2483
30.6k
  int amount = (isInc ? 
128.9k
:
-11.61k
);
2484
30.6k
  bool isSubtraction = !isInc;
2485
2486
30.6k
  if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2487
26
    type = atomicTy->getValueType();
2488
26
    if (isInc && 
type->isBooleanType()13
) {
2489
2
      llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2490
2
      if (isPre) {
2491
1
        Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2492
1
            ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2493
1
        return Builder.getTrue();
2494
1
      }
2495
      // For atomic bool increment, we just store true and return it for
2496
      // preincrement, do an atomic swap with true for postincrement
2497
1
      return Builder.CreateAtomicRMW(
2498
1
          llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
2499
1
          llvm::AtomicOrdering::SequentiallyConsistent);
2500
2
    }
2501
    // Special case for atomic increment / decrement on integers, emit
2502
    // atomicrmw instructions.  We skip this if we want to be doing overflow
2503
    // checking, and fall into the slow path with the atomic cmpxchg loop.
2504
24
    if (!type->isBooleanType() && 
type->isIntegerType()22
&&
2505
24
        
!(14
type->isUnsignedIntegerType()14
&&
2506
14
          
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)1
) &&
2507
24
        CGF.getLangOpts().getSignedOverflowBehavior() !=
2508
13
            LangOptions::SOB_Trapping) {
2509
13
      llvm::AtomicRMWInst::BinOp aop = isInc ? 
llvm::AtomicRMWInst::Add6
:
2510
13
        
llvm::AtomicRMWInst::Sub7
;
2511
13
      llvm::Instruction::BinaryOps op = isInc ? 
llvm::Instruction::Add6
:
2512
13
        
llvm::Instruction::Sub7
;
2513
13
      llvm::Value *amt = CGF.EmitToMemory(
2514
13
          llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2515
13
      llvm::Value *old =
2516
13
          Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2517
13
                                  llvm::AtomicOrdering::SequentiallyConsistent);
2518
13
      return isPre ? 
Builder.CreateBinOp(op, old, amt)6
:
old7
;
2519
13
    }
2520
11
    value = EmitLoadOfLValue(LV, E->getExprLoc());
2521
11
    input = value;
2522
    // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2523
11
    llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2524
11
    llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2525
11
    value = CGF.EmitToMemory(value, type);
2526
11
    Builder.CreateBr(opBB);
2527
11
    Builder.SetInsertPoint(opBB);
2528
11
    atomicPHI = Builder.CreatePHI(value->getType(), 2);
2529
11
    atomicPHI->addIncoming(value, startBB);
2530
11
    value = atomicPHI;
2531
30.5k
  } else {
2532
30.5k
    value = EmitLoadOfLValue(LV, E->getExprLoc());
2533
30.5k
    input = value;
2534
30.5k
  }
2535
2536
  // Special case of integer increment that we have to check first: bool++.
2537
  // Due to promotion rules, we get:
2538
  //   bool++ -> bool = bool + 1
2539
  //          -> bool = (int)bool + 1
2540
  //          -> bool = ((int)bool + 1 != 0)
2541
  // An interesting aspect of this is that increment is always true.
2542
  // Decrement does not have this property.
2543
30.5k
  if (isInc && 
type->isBooleanType()28.9k
) {
2544
6
    value = Builder.getTrue();
2545
2546
  // Most common case by far: integer increment.
2547
30.5k
  } else if (type->isIntegerType()) {
2548
20.4k
    QualType promotedType;
2549
20.4k
    bool canPerformLossyDemotionCheck = false;
2550
20.4k
    if (type->isPromotableIntegerType()) {
2551
376
      promotedType = CGF.getContext().getPromotedIntegerType(type);
2552
376
      assert(promotedType != type && "Shouldn't promote to the same type.");
2553
0
      canPerformLossyDemotionCheck = true;
2554
376
      canPerformLossyDemotionCheck &=
2555
376
          CGF.getContext().getCanonicalType(type) !=
2556
376
          CGF.getContext().getCanonicalType(promotedType);
2557
376
      canPerformLossyDemotionCheck &=
2558
376
          PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2559
376
              type, promotedType);
2560
376
      assert((!canPerformLossyDemotionCheck ||
2561
376
              type->isSignedIntegerOrEnumerationType() ||
2562
376
              promotedType->isSignedIntegerOrEnumerationType() ||
2563
376
              ConvertType(type)->getScalarSizeInBits() ==
2564
376
                  ConvertType(promotedType)->getScalarSizeInBits()) &&
2565
376
             "The following check expects that if we do promotion to different "
2566
376
             "underlying canonical type, at least one of the types (either "
2567
376
             "base or promoted) will be signed, or the bitwidths will match.");
2568
376
    }
2569
20.4k
    if (CGF.SanOpts.hasOneOf(
2570
20.4k
            SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2571
20.4k
        
canPerformLossyDemotionCheck145
) {
2572
      // While `x += 1` (for `x` with width less than int) is modeled as
2573
      // promotion+arithmetics+demotion, and we can catch lossy demotion with
2574
      // ease; inc/dec with width less than int can't overflow because of
2575
      // promotion rules, so we omit promotion+demotion, which means that we can
2576
      // not catch lossy "demotion". Because we still want to catch these cases
2577
      // when the sanitizer is enabled, we perform the promotion, then perform
2578
      // the increment/decrement in the wider type, and finally
2579
      // perform the demotion. This will catch lossy demotions.
2580
2581
145
      value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2582
145
      Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2583
145
      value = Builder.CreateAdd(value, amt, isInc ? 
"inc"72
:
"dec"73
);
2584
      // Do pass non-default ScalarConversionOpts so that sanitizer check is
2585
      // emitted.
2586
145
      value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2587
145
                                   ScalarConversionOpts(CGF.SanOpts));
2588
2589
      // Note that signed integer inc/dec with width less than int can't
2590
      // overflow because of promotion rules; we're just eliding a few steps
2591
      // here.
2592
20.3k
    } else if (E->canOverflow() && 
type->isSignedIntegerOrEnumerationType()20.0k
) {
2593
8.39k
      value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2594
11.9k
    } else if (E->canOverflow() && 
type->isUnsignedIntegerType()11.7k
&&
2595
11.9k
               
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)11.7k
) {
2596
5
      value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2597
5
          E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
2598
11.9k
    } else {
2599
11.9k
      llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2600
11.9k
      value = Builder.CreateAdd(value, amt, isInc ? 
"inc"11.6k
:
"dec"249
);
2601
11.9k
    }
2602
2603
  // Next most common: pointer increment.
2604
20.4k
  } else 
if (const PointerType *10.1k
ptr10.1k
= type->getAs<PointerType>()) {
2605
9.00k
    QualType type = ptr->getPointeeType();
2606
2607
    // VLA types don't have constant size.
2608
9.00k
    if (const VariableArrayType *vla
2609
9.00k
          = CGF.getContext().getAsVariableArrayType(type)) {
2610
3
      llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
2611
3
      if (!isInc) 
numElts = Builder.CreateNSWNeg(numElts, "vla.negsize")0
;
2612
3
      if (CGF.getLangOpts().isSignedOverflowDefined())
2613
0
        value = Builder.CreateGEP(value->getType()->getPointerElementType(),
2614
0
                                  value, numElts, "vla.inc");
2615
3
      else
2616
3
        value = CGF.EmitCheckedInBoundsGEP(
2617
3
            value, numElts, /*SignedIndices=*/false, isSubtraction,
2618
3
            E->getExprLoc(), "vla.inc");
2619
2620
    // Arithmetic on function pointers (!) is just +-1.
2621
9.00k
    } else if (type->isFunctionType()) {
2622
4
      llvm::Value *amt = Builder.getInt32(amount);
2623
2624
4
      value = CGF.EmitCastToVoidPtr(value);
2625
4
      if (CGF.getLangOpts().isSignedOverflowDefined())
2626
0
        value = Builder.CreateGEP(CGF.Int8Ty, value, amt, "incdec.funcptr");
2627
4
      else
2628
4
        value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2629
4
                                           isSubtraction, E->getExprLoc(),
2630
4
                                           "incdec.funcptr");
2631
4
      value = Builder.CreateBitCast(value, input->getType());
2632
2633
    // For everything else, we can just do a simple increment.
2634
9.00k
    } else {
2635
9.00k
      llvm::Value *amt = Builder.getInt32(amount);
2636
9.00k
      if (CGF.getLangOpts().isSignedOverflowDefined())
2637
1
        value = Builder.CreateGEP(value->getType()->getPointerElementType(),
2638
1
                                  value, amt, "incdec.ptr");
2639
8.99k
      else
2640
8.99k
        value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2641
8.99k
                                           isSubtraction, E->getExprLoc(),
2642
8.99k
                                           "incdec.ptr");
2643
9.00k
    }
2644
2645
  // Vector increment/decrement.
2646
9.00k
  } else 
if (1.09k
type->isVectorType()1.09k
) {
2647
76
    if (type->hasIntegerRepresentation()) {
2648
56
      llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2649
2650
56
      value = Builder.CreateAdd(value, amt, isInc ? 
"inc"28
:
"dec"28
);
2651
56
    } else {
2652
20
      value = Builder.CreateFAdd(
2653
20
                  value,
2654
20
                  llvm::ConstantFP::get(value->getType(), amount),
2655
20
                  isInc ? 
"inc"16
:
"dec"4
);
2656
20
    }
2657
2658
  // Floating point.
2659
1.02k
  } else if (type->isRealFloatingType()) {
2660
    // Add the inc/dec to the real part.
2661
971
    llvm::Value *amt;
2662
971
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
2663
2664
971
    if (type->isHalfType() && 
!CGF.getContext().getLangOpts().NativeHalfType62
) {
2665
      // Another special case: half FP increment should be done via float
2666
40
      if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2667
0
        value = Builder.CreateCall(
2668
0
            CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2669
0
                                 CGF.CGM.FloatTy),
2670
0
            input, "incdec.conv");
2671
40
      } else {
2672
40
        value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2673
40
      }
2674
40
    }
2675
2676
971
    if (value->getType()->isFloatTy())
2677
184
      amt = llvm::ConstantFP::get(VMContext,
2678
184
                                  llvm::APFloat(static_cast<float>(amount)));
2679
787
    else if (value->getType()->isDoubleTy())
2680
736
      amt = llvm::ConstantFP::get(VMContext,
2681
736
                                  llvm::APFloat(static_cast<double>(amount)));
2682
51
    else {
2683
      // Remaining types are Half, LongDouble, __ibm128 or __float128. Convert
2684
      // from float.
2685
51
      llvm::APFloat F(static_cast<float>(amount));
2686
51
      bool ignored;
2687
51
      const llvm::fltSemantics *FS;
2688
      // Don't use getFloatTypeSemantics because Half isn't
2689
      // necessarily represented using the "half" LLVM type.
2690
51
      if (value->getType()->isFP128Ty())
2691
10
        FS = &CGF.getTarget().getFloat128Format();
2692
41
      else if (value->getType()->isHalfTy())
2693
23
        FS = &CGF.getTarget().getHalfFormat();
2694
18
      else if (value->getType()->isPPC_FP128Ty())
2695
0
        FS = &CGF.getTarget().getIbm128Format();
2696
18
      else
2697
18
        FS = &CGF.getTarget().getLongDoubleFormat();
2698
51
      F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
2699
51
      amt = llvm::ConstantFP::get(VMContext, F);
2700
51
    }
2701
971
    value = Builder.CreateFAdd(value, amt, isInc ? 
"inc"918
:
"dec"53
);
2702
2703
971
    if (type->isHalfType() && 
!CGF.getContext().getLangOpts().NativeHalfType62
) {
2704
40
      if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2705
0
        value = Builder.CreateCall(
2706
0
            CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2707
0
                                 CGF.CGM.FloatTy),
2708
0
            value, "incdec.conv");
2709
40
      } else {
2710
40
        value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2711
40
      }
2712
40
    }
2713
2714
  // Fixed-point types.
2715
971
  } else 
if (52
type->isFixedPointType()52
) {
2716
    // Fixed-point types are tricky. In some cases, it isn't possible to
2717
    // represent a 1 or a -1 in the type at all. Piggyback off of
2718
    // EmitFixedPointBinOp to avoid having to reimplement saturation.
2719
48
    BinOpInfo Info;
2720
48
    Info.E = E;
2721
48
    Info.Ty = E->getType();
2722
48
    Info.Opcode = isInc ? 
BO_Add24
:
BO_Sub24
;
2723
48
    Info.LHS = value;
2724
48
    Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2725
    // If the type is signed, it's better to represent this as +(-1) or -(-1),
2726
    // since -1 is guaranteed to be representable.
2727
48
    if (type->isSignedFixedPointType()) {
2728
24
      Info.Opcode = isInc ? 
BO_Sub12
:
BO_Add12
;
2729
24
      Info.RHS = Builder.CreateNeg(Info.RHS);
2730
24
    }
2731
    // Now, convert from our invented integer literal to the type of the unary
2732
    // op. This will upscale and saturate if necessary. This value can become
2733
    // undef in some cases.
2734
48
    llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
2735
48
    auto DstSema = CGF.getContext().getFixedPointSemantics(Info.Ty);
2736
48
    Info.RHS = FPBuilder.CreateIntegerToFixed(Info.RHS, true, DstSema);
2737
48
    value = EmitFixedPointBinOp(Info);
2738
2739
  // Objective-C pointer types.
2740
48
  } else {
2741
4
    const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2742
4
    value = CGF.EmitCastToVoidPtr(value);
2743
2744
4
    CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2745
4
    if (!isInc) 
size = -size2
;
2746
4
    llvm::Value *sizeValue =
2747
4
      llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2748
2749
4
    if (CGF.getLangOpts().isSignedOverflowDefined())
2750
0
      value = Builder.CreateGEP(CGF.Int8Ty, value, sizeValue, "incdec.objptr");
2751
4
    else
2752
4
      value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2753
4
                                         /*SignedIndices=*/false, isSubtraction,
2754
4
                                         E->getExprLoc(), "incdec.objptr");
2755
4
    value = Builder.CreateBitCast(value, input->getType());
2756
4
  }
2757
2758
30.5k
  if (atomicPHI) {
2759
11
    llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
2760
11
    llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2761
11
    auto Pair = CGF.EmitAtomicCompareExchange(
2762
11
        LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2763
11
    llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2764
11
    llvm::Value *success = Pair.second;
2765
11
    atomicPHI->addIncoming(old, curBlock);
2766
11
    Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
2767
11
    Builder.SetInsertPoint(contBB);
2768
11
    return isPre ? 
value5
:
input6
;
2769
11
  }
2770
2771
  // Store the updated result through the lvalue.
2772
30.5k
  if (LV.isBitField())
2773
191
    CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
2774
30.3k
  else
2775
30.3k
    CGF.EmitStoreThroughLValue(RValue::get(value), LV);
2776
2777
  // If this is a postinc, return the value read from memory, otherwise use the
2778
  // updated value.
2779
30.5k
  return isPre ? 
value24.6k
:
input5.88k
;
2780
30.5k
}
2781
2782
2783
2784
11.9k
Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
2785
11.9k
  TestAndClearIgnoreResultAssign();
2786
11.9k
  Value *Op = Visit(E->getSubExpr());
2787
2788
  // Generate a unary FNeg for FP ops.
2789
11.9k
  if (Op->getType()->isFPOrFPVectorTy())
2790
1.06k
    return Builder.CreateFNeg(Op, "fneg");
2791
2792
  // Emit unary minus with EmitSub so we handle overflow cases etc.
2793
10.8k
  BinOpInfo BinOp;
2794
10.8k
  BinOp.RHS = Op;
2795
10.8k
  BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2796
10.8k
  BinOp.Ty = E->getType();
2797
10.8k
  BinOp.Opcode = BO_Sub;
2798
10.8k
  BinOp.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
2799
10.8k
  BinOp.E = E;
2800
10.8k
  return EmitSub(BinOp);
2801
11.9k
}
2802
2803
2.13k
Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2804
2.13k
  TestAndClearIgnoreResultAssign();
2805
2.13k
  Value *Op = Visit(E->getSubExpr());
2806
2.13k
  return Builder.CreateNot(Op, "neg");
2807
2.13k
}
2808
2809
620
Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2810
  // Perform vector logical not on comparison with zero vector.
2811
620
  if (E->getType()->isVectorType() &&
2812
620
      E->getType()->castAs<VectorType>()->getVectorKind() ==
2813
16
          VectorType::GenericVector) {
2814
16
    Value *Oper = Visit(E->getSubExpr());
2815
16
    Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2816
16
    Value *Result;
2817
16
    if (Oper->getType()->isFPOrFPVectorTy()) {
2818
13
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
2819
13
          CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
2820
13
      Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2821
13
    } else
2822
3
      Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2823
16
    return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2824
16
  }
2825
2826
  // Compare operand to zero.
2827
604
  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2828
2829
  // Invert value.
2830
  // TODO: Could dynamically modify easy computations here.  For example, if
2831
  // the operand is an icmp ne, turn into icmp eq.
2832
604
  BoolVal = Builder.CreateNot(BoolVal, "lnot");
2833
2834
  // ZExt result to the expr type.
2835
604
  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2836
620
}
2837
2838
36
Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2839
  // Try folding the offsetof to a constant.
2840
36
  Expr::EvalResult EVResult;
2841
36
  if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2842
35
    llvm::APSInt Value = EVResult.Val.getInt();
2843
35
    return Builder.getInt(Value);
2844
35
  }
2845
2846
  // Loop over the components of the offsetof to compute the value.
2847
1
  unsigned n = E->getNumComponents();
2848
1
  llvm::Type* ResultType = ConvertType(E->getType());
2849
1
  llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2850
1
  QualType CurrentType = E->getTypeSourceInfo()->getType();
2851
3
  for (unsigned i = 0; i != n; 
++i2
) {
2852
2
    OffsetOfNode ON = E->getComponent(i);
2853
2
    llvm::Value *Offset = nullptr;
2854
2
    switch (ON.getKind()) {
2855
1
    case OffsetOfNode::Array: {
2856
      // Compute the index
2857
1
      Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2858
1
      llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2859
1
      bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2860
1
      Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2861
2862
      // Save the element type
2863
1
      CurrentType =
2864
1
          CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2865
2866
      // Compute the element size
2867
1
      llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2868
1
          CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2869
2870
      // Multiply out to compute the result
2871
1
      Offset = Builder.CreateMul(Idx, ElemSize);
2872
1
      break;
2873
0
    }
2874
2875
1
    case OffsetOfNode::Field: {
2876
1
      FieldDecl *MemberDecl = ON.getField();
2877
1
      RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2878
1
      const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2879
2880
      // Compute the index of the field in its parent.
2881
1
      unsigned i = 0;
2882
      // FIXME: It would be nice if we didn't have to loop here!
2883
1
      for (RecordDecl::field_iterator Field = RD->field_begin(),
2884
1
                                      FieldEnd = RD->field_end();
2885
2
           Field != FieldEnd; 
++Field, ++i1
) {
2886
2
        if (*Field == MemberDecl)
2887
1
          break;
2888
2
      }
2889
1
      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2890
2891
      // Compute the offset to the field
2892
0
      int64_t OffsetInt = RL.getFieldOffset(i) /
2893
1
                          CGF.getContext().getCharWidth();
2894
1
      Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2895
2896
      // Save the element type.
2897
1
      CurrentType = MemberDecl->getType();
2898
1
      break;
2899
0
    }
2900
2901
0
    case OffsetOfNode::Identifier:
2902
0
      llvm_unreachable("dependent __builtin_offsetof");
2903
2904
0
    case OffsetOfNode::Base: {
2905
0
      if (ON.getBase()->isVirtual()) {
2906
0
        CGF.ErrorUnsupported(E, "virtual base in offsetof");
2907
0
        continue;
2908
0
      }
2909
2910
0
      RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2911
0
      const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2912
2913
      // Save the element type.
2914
0
      CurrentType = ON.getBase()->getType();
2915
2916
      // Compute the offset to the base.
2917
0
      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2918
0
      CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2919
0
      CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2920
0
      Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2921
0
      break;
2922
0
    }
2923
2
    }
2924
2
    Result = Builder.CreateAdd(Result, Offset);
2925
2
  }
2926
1
  return Result;
2927
1
}
2928
2929
/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2930
/// argument of the sizeof expression as an integer.
2931
Value *
2932
ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2933
10.0k
                              const UnaryExprOrTypeTraitExpr *E) {
2934
10.0k
  QualType TypeToSize = E->getTypeOfArgument();
2935
10.0k
  if (E->getKind() == UETT_SizeOf) {
2936
8.71k
    if (const VariableArrayType *VAT =
2937
8.71k
          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2938
30
      if (E->isArgumentType()) {
2939
        // sizeof(type) - make sure to emit the VLA size.
2940
14
        CGF.EmitVariablyModifiedType(TypeToSize);
2941
16
      } else {
2942
        // C99 6.5.3.4p2: If the argument is an expression of type
2943
        // VLA, it is evaluated.
2944
16
        CGF.EmitIgnoredExpr(E->getArgumentExpr());
2945
16
      }
2946
2947
30
      auto VlaSize = CGF.getVLASize(VAT);
2948
30
      llvm::Value *size = VlaSize.NumElts;
2949
2950
      // Scale the number of non-VLA elements by the non-VLA element size.
2951
30
      CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2952
30
      if (!eltSize.isOne())
2953
27
        size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2954
2955
30
      return size;
2956
30
    }
2957
8.71k
  } else 
if (1.38k
E->getKind() == UETT_OpenMPRequiredSimdAlign1.38k
) {
2958
1
    auto Alignment =
2959
1
        CGF.getContext()
2960
1
            .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2961
1
                E->getTypeOfArgument()->getPointeeType()))
2962
1
            .getQuantity();
2963
1
    return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2964
1
  }
2965
2966
  // If this isn't sizeof(vla), the result must be constant; use the constant
2967
  // folding logic so we don't have to duplicate it here.
2968
10.0k
  return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2969
10.0k
}
2970
2971
98
Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2972
98
  Expr *Op = E->getSubExpr();
2973
98
  if (Op->getType()->isAnyComplexType()) {
2974
    // If it's an l-value, load through the appropriate subobject l-value.
2975
    // Note that we have to ask E because Op might be an l-value that
2976
    // this won't work for, e.g. an Obj-C property.
2977
87
    if (E->isGLValue())
2978
69
      return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2979
69
                                  E->getExprLoc()).getScalarVal();
2980
2981
    // Otherwise, calculate and project.
2982
18
    return CGF.EmitComplexExpr(Op, false, true).first;
2983
87
  }
2984
2985
11
  return Visit(Op);
2986
98
}
2987
2988
78
Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2989
78
  Expr *Op = E->getSubExpr();
2990
78
  if (Op->getType()->isAnyComplexType()) {
2991
    // If it's an l-value, load through the appropriate subobject l-value.
2992
    // Note that we have to ask E because Op might be an l-value that
2993
    // this won't work for, e.g. an Obj-C property.
2994
63
    if (Op->isGLValue())
2995
63
      return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2996
63
                                  E->getExprLoc()).getScalarVal();
2997
2998
    // Otherwise, calculate and project.
2999
0
    return CGF.EmitComplexExpr(Op, true, false).second;
3000
63
  }
3001
3002
  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
3003
  // effects are evaluated, but not the actual value.
3004
15
  if (Op->isGLValue())
3005
4
    CGF.EmitLValue(Op);
3006
11
  else
3007
11
    CGF.EmitScalarExpr(Op, true);
3008
15
  return llvm::Constant::getNullValue(ConvertType(E->getType()));
3009
78
}
3010
3011
//===----------------------------------------------------------------------===//
3012
//                           Binary Operators
3013
//===----------------------------------------------------------------------===//
3014
3015
449k
BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
3016
449k
  TestAndClearIgnoreResultAssign();
3017
449k
  BinOpInfo Result;
3018
449k
  Result.LHS = Visit(E->getLHS());
3019
449k
  Result.RHS = Visit(E->getRHS());
3020
449k
  Result.Ty  = E->getType();
3021
449k
  Result.Opcode = E->getOpcode();
3022
449k
  Result.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
3023
449k
  Result.E = E;
3024
449k
  return Result;
3025
449k
}
3026
3027
LValue ScalarExprEmitter::EmitCompoundAssignLValue(
3028
                                              const CompoundAssignOperator *E,
3029
                        Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
3030
22.0k
                                                   Value *&Result) {
3031
22.0k
  QualType LHSTy = E->getLHS()->getType();
3032
22.0k
  BinOpInfo OpInfo;
3033
3034
22.0k
  if (E->getComputationResultType()->isAnyComplexType())
3035
4
    return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
3036
3037
  // Emit the RHS first.  __block variables need to have the rhs evaluated
3038
  // first, plus this should improve codegen a little.
3039
22.0k
  OpInfo.RHS = Visit(E->getRHS());
3040
22.0k
  OpInfo.Ty = E->getComputationResultType();
3041
22.0k
  OpInfo.Opcode = E->getOpcode();
3042
22.0k
  OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
3043
22.0k
  OpInfo.E = E;
3044
  // Load/convert the LHS.
3045
22.0k
  LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3046
3047
22.0k
  llvm::PHINode *atomicPHI = nullptr;
3048
22.0k
  if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
3049
44
    QualType type = atomicTy->getValueType();
3050
44
    if (!type->isBooleanType() && 
type->isIntegerType()39
&&
3051
44
        
!(35
type->isUnsignedIntegerType()35
&&
3052
35
          
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)1
) &&
3053
44
        CGF.getLangOpts().getSignedOverflowBehavior() !=
3054
34
            LangOptions::SOB_Trapping) {
3055
34
      llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
3056
34
      llvm::Instruction::BinaryOps Op;
3057
34
      switch (OpInfo.Opcode) {
3058
        // We don't have atomicrmw operands for *, %, /, <<, >>
3059
8
        
case BO_MulAssign: 4
case BO_DivAssign:
3060
8
        case BO_RemAssign:
3061
8
        case BO_ShlAssign:
3062
8
        case BO_ShrAssign:
3063
8
          break;
3064
5
        case BO_AddAssign:
3065
5
          AtomicOp = llvm::AtomicRMWInst::Add;
3066
5
          Op = llvm::Instruction::Add;
3067
5
          break;
3068
5
        case BO_SubAssign:
3069
5
          AtomicOp = llvm::AtomicRMWInst::Sub;
3070
5
          Op = llvm::Instruction::Sub;
3071
5
          break;
3072
6
        case BO_AndAssign:
3073
6
          AtomicOp = llvm::AtomicRMWInst::And;
3074
6
          Op = llvm::Instruction::And;
3075
6
          break;
3076
5
        case BO_XorAssign:
3077
5
          AtomicOp = llvm::AtomicRMWInst::Xor;
3078
5
          Op = llvm::Instruction::Xor;
3079
5
          break;
3080
5
        case BO_OrAssign:
3081
5
          AtomicOp = llvm::AtomicRMWInst::Or;
3082
5
          Op = llvm::Instruction::Or;
3083
5
          break;
3084
0
        default:
3085
0
          llvm_unreachable("Invalid compound assignment type");
3086
34
      }
3087
34
      if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
3088
26
        llvm::Value *Amt = CGF.EmitToMemory(
3089
26
            EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3090
26
                                 E->getExprLoc()),
3091
26
            LHSTy);
3092
26
        Value *OldVal = Builder.CreateAtomicRMW(
3093
26
            AtomicOp, LHSLV.getPointer(CGF), Amt,
3094
26
            llvm::AtomicOrdering::SequentiallyConsistent);
3095
3096
        // Since operation is atomic, the result type is guaranteed to be the
3097
        // same as the input in LLVM terms.
3098
26
        Result = Builder.CreateBinOp(Op, OldVal, Amt);
3099
26
        return LHSLV;
3100
26
      }
3101
34
    }
3102
    // FIXME: For floating point types, we should be saving and restoring the
3103
    // floating point environment in the loop.
3104
18
    llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3105
18
    llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
3106
18
    OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3107
18
    OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
3108
18
    Builder.CreateBr(opBB);
3109
18
    Builder.SetInsertPoint(opBB);
3110
18
    atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3111
18
    atomicPHI->addIncoming(OpInfo.LHS, startBB);
3112
18
    OpInfo.LHS = atomicPHI;
3113
18
  }
3114
21.9k
  else
3115
21.9k
    OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3116
3117
22.0k
  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
3118
22.0k
  SourceLocation Loc = E->getExprLoc();
3119
22.0k
  OpInfo.LHS =
3120
22.0k
      EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
3121
3122
  // Expand the binary operator.
3123
22.0k
  Result = (this->*Func)(OpInfo);
3124
3125
  // Convert the result back to the LHS type,
3126
  // potentially with Implicit Conversion sanitizer check.
3127
22.0k
  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3128
22.0k
                                Loc, ScalarConversionOpts(CGF.SanOpts));
3129
3130
22.0k
  if (atomicPHI) {
3131
18
    llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3132
18
    llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3133
18
    auto Pair = CGF.EmitAtomicCompareExchange(
3134
18
        LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3135
18
    llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3136
18
    llvm::Value *success = Pair.second;
3137
18
    atomicPHI->addIncoming(old, curBlock);
3138
18
    Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3139
18
    Builder.SetInsertPoint(contBB);
3140
18
    return LHSLV;
3141
18
  }
3142
3143
  // Store the result value into the LHS lvalue. Bit-fields are handled
3144
  // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3145
  // 'An assignment expression has the value of the left operand after the
3146
  // assignment...'.
3147
21.9k
  if (LHSLV.isBitField())
3148
81
    CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
3149
21.9k
  else
3150
21.9k
    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
3151
3152
21.9k
  if (CGF.getLangOpts().OpenMP)
3153
17.7k
    CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3154
17.7k
                                                                  E->getLHS());
3155
21.9k
  return LHSLV;
3156
22.0k
}
3157
3158
Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3159
2.58k
                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3160
2.58k
  bool Ignore = TestAndClearIgnoreResultAssign();
3161
2.58k
  Value *RHS = nullptr;
3162
2.58k
  LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3163
3164
  // If the result is clearly ignored, return now.
3165
2.58k
  if (Ignore)
3166
2.49k
    return nullptr;
3167
3168
  // The result of an assignment in C is the assigned r-value.
3169
86
  if (!CGF.getLangOpts().CPlusPlus)
3170
78
    return RHS;
3171
3172
  // If the lvalue is non-volatile, return the computed value of the assignment.
3173
8
  if (!LHS.isVolatileQualified())
3174
4
    return RHS;
3175
3176
  // Otherwise, reload the value.
3177
4
  return EmitLoadOfLValue(LHS, E->getExprLoc());
3178
8
}
3179
3180
void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
3181
19
    const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
3182
19
  SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
3183
3184
19
  if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
3185
8
    Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3186
8
                                    SanitizerKind::IntegerDivideByZero));
3187
8
  }
3188
3189
19
  const auto *BO = cast<BinaryOperator>(Ops.E);
3190
19
  if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
3191
19
      Ops.Ty->hasSignedIntegerRepresentation() &&
3192
19
      !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3193
19
      
Ops.mayHaveIntegerOverflow()13
) {
3194
11
    llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3195
3196
11
    llvm::Value *IntMin =
3197
11
      Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
3198
11
    llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
3199
3200
11
    llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3201
11
    llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
3202
11
    llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3203
11
    Checks.push_back(
3204
11
        std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
3205
11
  }
3206
3207
19
  if (Checks.size() > 0)
3208
13
    EmitBinOpCheck(Checks, Ops);
3209
19
}
3210
3211
56.3k
Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
3212
56.3k
  {
3213
56.3k
    CodeGenFunction::SanitizerScope SanScope(&CGF);
3214
56.3k
    if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3215
56.3k
         
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)56.3k
) &&
3216
56.3k
        
Ops.Ty->isIntegerType()18
&&
3217
56.3k
        
(17
Ops.mayHaveIntegerDivisionByZero()17
||
Ops.mayHaveIntegerOverflow()5
)) {
3218
13
      llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3219
13
      EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
3220
56.3k
    } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
3221
56.3k
               
Ops.Ty->isRealFloatingType()6
&&
3222
56.3k
               
Ops.mayHaveFloatDivisionByZero()2
) {
3223
2
      llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3224
2
      llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3225
2
      EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3226
2
                     Ops);
3227
2
    }
3228
56.3k
  }
3229
3230
56.3k
  if (Ops.Ty->isConstantMatrixType()) {
3231
10
    llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3232
    // We need to check the types of the operands of the operator to get the
3233
    // correct matrix dimensions.
3234
10
    auto *BO = cast<BinaryOperator>(Ops.E);
3235
10
    (void)BO;
3236
10
    assert(
3237
10
        isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
3238
10
        "first operand must be a matrix");
3239
0
    assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
3240
10
           "second operand must be an arithmetic type");
3241
0
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
3242
10
    return MB.CreateScalarDiv(Ops.LHS, Ops.RHS,
3243
10
                              Ops.Ty->hasUnsignedIntegerRepresentation());
3244
10
  }
3245
3246
56.3k
  if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3247
560
    llvm::Value *Val;
3248
560
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
3249
560
    Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3250
560
    if ((CGF.getLangOpts().OpenCL &&
3251
560
         
!CGF.CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt23
) ||
3252
560
        
(540
CGF.getLangOpts().HIP540
&&
CGF.getLangOpts().CUDAIsDevice6
&&
3253
540
         
!CGF.CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt6
)) {
3254
      // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3255
      // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3256
      // build option allows an application to specify that single precision
3257
      // floating-point divide (x/y and 1/x) and sqrt used in the program
3258
      // source are correctly rounded.
3259
23
      llvm::Type *ValTy = Val->getType();
3260
23
      if (ValTy->isFloatTy() ||
3261
23
          
(7
isa<llvm::VectorType>(ValTy)7
&&
3262
7
           
cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()4
))
3263
20
        CGF.SetFPAccuracy(Val, 2.5);
3264
23
    }
3265
560
    return Val;
3266
560
  }
3267
55.7k
  else if (Ops.isFixedPointOp())
3268
72
    return EmitFixedPointBinOp(Ops);
3269
55.7k
  else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3270
9.97k
    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3271
45.7k
  else
3272
45.7k
    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3273
56.3k
}
3274
3275
798
Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3276
  // Rem in C can't be a floating point type: C99 6.5.5p2.
3277
798
  if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3278
798
       
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)792
) &&
3279
798
      
Ops.Ty->isIntegerType()11
&&
3280
798
      
(10
Ops.mayHaveIntegerDivisionByZero()10
||
Ops.mayHaveIntegerOverflow()5
)) {
3281
6
    CodeGenFunction::SanitizerScope SanScope(&CGF);
3282
6
    llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3283
6
    EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3284
6
  }
3285
3286
798
  if (Ops.Ty->hasUnsignedIntegerRepresentation())
3287
489
    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3288
309
  else
3289
309
    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3290
798
}
3291
3292
85
Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3293
85
  unsigned IID;
3294
85
  unsigned OpID = 0;
3295
85
  SanitizerHandler OverflowKind;
3296
3297
85
  bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3298
85
  switch (Ops.Opcode) {
3299
47
  case BO_Add:
3300
50
  case BO_AddAssign:
3301
50
    OpID = 1;
3302
50
    IID = isSigned ? 
llvm::Intrinsic::sadd_with_overflow28
:
3303
50
                     
llvm::Intrinsic::uadd_with_overflow22
;
3304
50
    OverflowKind = SanitizerHandler::AddOverflow;
3305
50
    break;
3306
17
  case BO_Sub:
3307
17
  case BO_SubAssign:
3308
17
    OpID = 2;
3309
17
    IID = isSigned ? 
llvm::Intrinsic::ssub_with_overflow14
:
3310
17
                     
llvm::Intrinsic::usub_with_overflow3
;
3311
17
    OverflowKind = SanitizerHandler::SubOverflow;
3312
17
    break;
3313
18
  case BO_Mul:
3314
18
  case BO_MulAssign:
3315
18
    OpID = 3;
3316
18
    IID = isSigned ? 
llvm::Intrinsic::smul_with_overflow13
:
3317
18
                     
llvm::Intrinsic::umul_with_overflow5
;
3318
18
    OverflowKind = SanitizerHandler::MulOverflow;
3319
18
    break;
3320
0
  default:
3321
0
    llvm_unreachable("Unsupported operation for overflow detection");
3322
85
  }
3323
85
  OpID <<= 1;
3324
85
  if (isSigned)
3325
55
    OpID |= 1;
3326
3327
85
  CodeGenFunction::SanitizerScope SanScope(&CGF);
3328
85
  llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3329
3330
85
  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3331
3332
85
  Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3333
85
  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3334
85
  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3335
3336
  // Handle overflow with llvm.trap if no custom handler has been specified.
3337
85
  const std::string *handlerName =
3338
85
    &CGF.getLangOpts().OverflowHandler;
3339
85
  if (handlerName->empty()) {
3340
    // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3341
    // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3342
79
    if (!isSigned || 
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)49
) {
3343
66
      llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3344
66
      SanitizerMask Kind = isSigned ? 
SanitizerKind::SignedIntegerOverflow36
3345
66
                              : 
SanitizerKind::UnsignedIntegerOverflow30
;
3346
66
      EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3347
66
    } else
3348
13
      CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
3349
79
    return result;
3350
79
  }
3351
3352
  // Branch in case of overflow.
3353
6
  llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3354
6
  llvm::BasicBlock *continueBB =
3355
6
      CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3356
6
  llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3357
3358
6
  Builder.CreateCondBr(overflow, overflowBB, continueBB);
3359
3360
  // If an overflow handler is set, then we want to call it and then use its
3361
  // result, if it returns.
3362
6
  Builder.SetInsertPoint(overflowBB);
3363
3364
  // Get the overflow handler.
3365
6
  llvm::Type *Int8Ty = CGF.Int8Ty;
3366
6
  llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3367
6
  llvm::FunctionType *handlerTy =
3368
6
      llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3369
6
  llvm::FunctionCallee handler =
3370
6
      CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3371
3372
  // Sign extend the args to 64-bit, so that we can use the same handler for
3373
  // all types of overflow.
3374
6
  llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3375
6
  llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3376
3377
  // Call the handler with the two arguments, the operation, and the size of
3378
  // the result.
3379
6
  llvm::Value *handlerArgs[] = {
3380
6
    lhs,
3381
6
    rhs,
3382
6
    Builder.getInt8(OpID),
3383
6
    Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3384
6
  };
3385
6
  llvm::Value *handlerResult =
3386
6
    CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3387
3388
  // Truncate the result back to the desired size.
3389
6
  handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3390
6
  Builder.CreateBr(continueBB);
3391
3392
6
  Builder.SetInsertPoint(continueBB);
3393
6
  llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3394
6
  phi->addIncoming(result, initialBB);
3395
6
  phi->addIncoming(handlerResult, overflowBB);
3396
3397
6
  return phi;
3398
85
}
3399
3400
/// Emit pointer + index arithmetic.
3401
static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3402
                                    const BinOpInfo &op,
3403
19.4k
                                    bool isSubtraction) {
3404
  // Must have binary (not unary) expr here.  Unary pointer
3405
  // increment/decrement doesn't use this path.
3406
19.4k
  const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3407
3408
19.4k
  Value *pointer = op.LHS;
3409
19.4k
  Expr *pointerOperand = expr->getLHS();
3410
19.4k
  Value *index = op.RHS;
3411
19.4k
  Expr *indexOperand = expr->getRHS();
3412
3413
  // In a subtraction, the LHS is always the pointer.
3414
19.4k
  if (!isSubtraction && 
!pointer->getType()->isPointerTy()18.6k
) {
3415
93
    std::swap(pointer, index);
3416
93
    std::swap(pointerOperand, indexOperand);
3417
93
  }
3418
3419
19.4k
  bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3420
3421
19.4k
  unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3422
19.4k
  auto &DL = CGF.CGM.getDataLayout();
3423
19.4k
  auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3424
3425
  // Some versions of glibc and gcc use idioms (particularly in their malloc
3426
  // routines) that add a pointer-sized integer (known to be a pointer value)
3427
  // to a null pointer in order to cast the value back to an integer or as
3428
  // part of a pointer alignment algorithm.  This is undefined behavior, but
3429
  // we'd like to be able to compile programs that use it.
3430
  //
3431
  // Normally, we'd generate a GEP with a null-pointer base here in response
3432
  // to that code, but it's also UB to dereference a pointer created that
3433
  // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
3434
  // generate a direct cast of the integer value to a pointer.
3435
  //
3436
  // The idiom (p = nullptr + N) is not met if any of the following are true:
3437
  //
3438
  //   The operation is subtraction.
3439
  //   The index is not pointer-sized.
3440
  //   The pointer type is not byte-sized.
3441
  //
3442
19.4k
  if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3443
19.4k
                                                       op.Opcode,
3444
19.4k
                                                       expr->getLHS(),
3445
19.4k
                                                       expr->getRHS()))
3446
6
    return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3447
3448
19.4k
  if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
3449
    // Zero-extend or sign-extend the pointer value according to
3450
    // whether the index is signed or not.
3451
11.7k
    index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
3452
11.7k
                                      "idx.ext");
3453
11.7k
  }
3454
3455
  // If this is subtraction, negate the index.
3456
19.4k
  if (isSubtraction)
3457
760
    index = CGF.Builder.CreateNeg(index, "idx.neg");
3458
3459
19.4k
  if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3460
2
    CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3461
2
                        /*Accessed*/ false);
3462
3463
19.4k
  const PointerType *pointerType
3464
19.4k
    = pointerOperand->getType()->getAs<PointerType>();
3465
19.4k
  if (!pointerType) {
3466
2
    QualType objectType = pointerOperand->getType()
3467
2
                                        ->castAs<ObjCObjectPointerType>()
3468
2
                                        ->getPointeeType();
3469
2
    llvm::Value *objectSize
3470
2
      = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3471
3472
2
    index = CGF.Builder.CreateMul(index, objectSize);
3473
3474
2
    Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3475
2
    result = CGF.Builder.CreateGEP(CGF.Int8Ty, result, index, "add.ptr");
3476
2
    return CGF.Builder.CreateBitCast(result, pointer->getType());
3477
2
  }
3478
3479
19.3k
  QualType elementType = pointerType->getPointeeType();
3480
19.3k
  if (const VariableArrayType *vla
3481
19.3k
        = CGF.getContext().getAsVariableArrayType(elementType)) {
3482
    // The element count here is the total number of non-VLA elements.
3483
9
    llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3484
3485
    // Effectively, the multiply by the VLA size is part of the GEP.
3486
    // GEP indexes are signed, and scaling an index isn't permitted to
3487
    // signed-overflow, so we use the same semantics for our explicit
3488
    // multiply.  We suppress this if overflow is not undefined behavior.
3489
9
    if (CGF.getLangOpts().isSignedOverflowDefined()) {
3490
0
      index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3491
0
      pointer = CGF.Builder.CreateGEP(
3492
0
          pointer->getType()->getPointerElementType(), pointer, index,
3493
0
          "add.ptr");
3494
9
    } else {
3495
9
      index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3496
9
      pointer =
3497
9
          CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3498
9
                                     op.E->getExprLoc(), "add.ptr");
3499
9
    }
3500
9
    return pointer;
3501
9
  }
3502
3503
  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3504
  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3505
  // future proof.
3506
19.3k
  if (elementType->isVoidType() || 
elementType->isFunctionType()19.3k
) {
3507
23
    Value *result = CGF.EmitCastToVoidPtr(pointer);
3508
23
    result = CGF.Builder.CreateGEP(CGF.Int8Ty, result, index, "add.ptr");
3509
23
    return CGF.Builder.CreateBitCast(result, pointer->getType());
3510
23
  }
3511
3512
19.3k
  if (CGF.getLangOpts().isSignedOverflowDefined())
3513
0
    return CGF.Builder.CreateGEP(
3514
0
        pointer->getType()->getPointerElementType(), pointer, index, "add.ptr");
3515
3516
19.3k
  return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3517
19.3k
                                    op.E->getExprLoc(), "add.ptr");
3518
19.3k
}
3519
3520
// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3521
// Addend. Use negMul and negAdd to negate the first operand of the Mul or
3522
// the add operand respectively. This allows fmuladd to represent a*b-c, or
3523
// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3524
// efficient operations.
3525
static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
3526
                           const CodeGenFunction &CGF, CGBuilderTy &Builder,
3527
71
                           bool negMul, bool negAdd) {
3528
71
  assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3529
3530
0
  Value *MulOp0 = MulOp->getOperand(0);
3531
71
  Value *MulOp1 = MulOp->getOperand(1);
3532
71
  if (negMul)
3533
1
    MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3534
71
  if (negAdd)
3535
2
    Addend = Builder.CreateFNeg(Addend, "neg");
3536
3537
71
  Value *FMulAdd = nullptr;
3538
71
  if (Builder.getIsFPConstrained()) {
3539
13
    assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3540
13
           "Only constrained operation should be created when Builder is in FP "
3541
13
           "constrained mode");
3542
0
    FMulAdd = Builder.CreateConstrainedFPCall(
3543
13
        CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3544
13
                             Addend->getType()),
3545
13
        {MulOp0, MulOp1, Addend});
3546
58
  } else {
3547
58
    FMulAdd = Builder.CreateCall(
3548
58
        CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3549
58
        {MulOp0, MulOp1, Addend});
3550
58
  }
3551
0
  MulOp->eraseFromParent();
3552
3553
71
  return FMulAdd;
3554
71
}
3555
3556
// Check whether it would be legal to emit an fmuladd intrinsic call to
3557
// represent op and if so, build the fmuladd.
3558
//
3559
// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3560
// Does NOT check the type of the operation - it's assumed that this function
3561
// will be called from contexts where it's known that the type is contractable.
3562
static Value* tryEmitFMulAdd(const BinOpInfo &op,
3563
                         const CodeGenFunction &CGF, CGBuilderTy &Builder,
3564
6.19k
                         bool isSub=false) {
3565
3566
6.19k
  assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3567
6.19k
          op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3568
6.19k
         "Only fadd/fsub can be the root of an fmuladd.");
3569
3570
  // Check whether this op is marked as fusable.
3571
6.19k
  if (!op.FPFeatures.allowFPContractWithinStatement())
3572
6.04k
    return nullptr;
3573
3574
  // We have a potentially fusable op. Look for a mul on one of the operands.
3575
  // Also, make sure that the mul result isn't used directly. In that case,
3576
  // there's no point creating a muladd operation.
3577
146
  if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3578
47
    if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3579
47
        LHSBinOp->use_empty())
3580
45
      return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3581
47
  }
3582
101
  if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3583
17
    if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3584
17
        
RHSBinOp->use_empty()13
)
3585
13
      return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3586
17
  }
3587
3588
88
  if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3589
13
    if (LHSBinOp->getIntrinsicID() ==
3590
13
            llvm::Intrinsic::experimental_constrained_fmul &&
3591
13
        
LHSBinOp->use_empty()9
)
3592
9
      return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3593
13
  }
3594
79
  if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3595
6
    if (RHSBinOp->getIntrinsicID() ==
3596
6
            llvm::Intrinsic::experimental_constrained_fmul &&
3597
6
        
RHSBinOp->use_empty()4
)
3598
4
      return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3599
6
  }
3600
3601
75
  return nullptr;
3602
79
}
3603
3604
150k
Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3605
150k
  if (op.LHS->getType()->isPointerTy() ||
3606
150k
      
op.RHS->getType()->isPointerTy()132k
)
3607
18.6k
    return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3608
3609
132k
  if (op.Ty->isSignedIntegerOrEnumerationType()) {
3610
105k
    switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3611
1
    case LangOptions::SOB_Defined:
3612
1
      return Builder.CreateAdd(op.LHS, op.RHS, "add");
3613
105k
    case LangOptions::SOB_Undefined:
3614
105k
      if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3615
105k
        return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3616
105k
      
LLVM_FALLTHROUGH23
;23
3617
30
    case LangOptions::SOB_Trapping:
3618
30
      if (CanElideOverflowCheck(CGF.getContext(), op))
3619
7
        return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3620
23
      return EmitOverflowCheckedBinOp(op);
3621
105k
    }
3622
105k
  }
3623
3624
27.0k
  if (op.Ty->isConstantMatrixType()) {
3625
57
    llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3626
57
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
3627
57
    return MB.CreateAdd(op.LHS, op.RHS);
3628
57
  }
3629
3630
27.0k
  if (op.Ty->isUnsignedIntegerType() &&
3631
27.0k
      
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)20.7k
&&
3632
27.0k
      
!CanElideOverflowCheck(CGF.getContext(), op)19
)
3633
17
    return EmitOverflowCheckedBinOp(op);
3634
3635
27.0k
  if (op.LHS->getType()->isFPOrFPVectorTy()) {
3636
5.53k
    CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
3637
    // Try to form an fmuladd.
3638
5.53k
    if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3639
68
      return FMulAdd;
3640
3641
5.46k
    return Builder.CreateFAdd(op.LHS, op.RHS, "add");
3642
5.53k
  }
3643
3644
21.4k
  if (op.isFixedPointOp())
3645
90
    return EmitFixedPointBinOp(op);
3646
3647
21.3k
  return Builder.CreateAdd(op.LHS, op.RHS, "add");
3648
21.4k
}
3649
3650
/// The resulting value must be calculated with exact precision, so the operands
3651
/// may not be the same type.
3652
524
Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3653
524
  using llvm::APSInt;
3654
524
  using llvm::ConstantInt;
3655
3656
  // This is either a binary operation where at least one of the operands is
3657
  // a fixed-point type, or a unary operation where the operand is a fixed-point
3658
  // type. The result type of a binary operation is determined by
3659
  // Sema::handleFixedPointConversions().
3660
524
  QualType ResultTy = op.Ty;
3661
524
  QualType LHSTy, RHSTy;
3662
524
  if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
3663
448
    RHSTy = BinOp->getRHS()->getType();
3664
448
    if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3665
      // For compound assignment, the effective type of the LHS at this point
3666
      // is the computation LHS type, not the actual LHS type, and the final
3667
      // result type is not the type of the expression but rather the
3668
      // computation result type.
3669
54
      LHSTy = CAO->getComputationLHSType();
3670
54
      ResultTy = CAO->getComputationResultType();
3671
54
    } else
3672
394
      LHSTy = BinOp->getLHS()->getType();
3673
448
  } else 
if (const auto *76
UnOp76
= dyn_cast<UnaryOperator>(op.E)) {
3674
76
    LHSTy = UnOp->getSubExpr()->getType();
3675
76
    RHSTy = UnOp->getSubExpr()->getType();
3676
76
  }
3677
524
  ASTContext &Ctx = CGF.getContext();
3678
524
  Value *LHS = op.LHS;
3679
524
  Value *RHS = op.RHS;
3680
3681
524
  auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3682
524
  auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3683
524
  auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3684
524
  auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3685
3686
  // Perform the actual operation.
3687
524
  Value *Result;
3688
524
  llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3689
524
  switch (op.Opcode) {
3690
30
  case BO_AddAssign:
3691
114
  case BO_Add:
3692
114
    Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
3693
114
    break;
3694
6
  case BO_SubAssign:
3695
118
  case BO_Sub:
3696
118
    Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
3697
118
    break;
3698
6
  case BO_MulAssign:
3699
72
  case BO_Mul:
3700
72
    Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
3701
72
    break;
3702
6
  case BO_DivAssign:
3703
72
  case BO_Div:
3704
72
    Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
3705
72
    break;
3706
4
  case BO_ShlAssign:
3707
52
  case BO_Shl:
3708
52
    Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
3709
52
    break;
3710
2
  case BO_ShrAssign:
3711
34
  case BO_Shr:
3712
34
    Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
3713
34
    break;
3714
8
  case BO_LT:
3715
8
    return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
3716
8
  case BO_GT:
3717
8
    return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
3718
8
  case BO_LE:
3719
8
    return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
3720
8
  case BO_GE:
3721
8
    return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
3722
26
  case BO_EQ:
3723
    // For equality operations, we assume any padding bits on unsigned types are
3724
    // zero'd out. They could be overwritten through non-saturating operations
3725
    // that cause overflow, but this leads to undefined behavior.
3726
26
    return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
3727
4
  case BO_NE:
3728
4
    return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
3729
0
  case BO_Cmp:
3730
0
  case BO_LAnd:
3731
0
  case BO_LOr:
3732
0
    llvm_unreachable("Found unimplemented fixed point binary operation");
3733
0
  case BO_PtrMemD:
3734
0
  case BO_PtrMemI:
3735
0
  case BO_Rem:
3736
0
  case BO_Xor:
3737
0
  case BO_And:
3738
0
  case BO_Or:
3739
0
  case BO_Assign:
3740
0
  case BO_RemAssign:
3741
0
  case BO_AndAssign:
3742
0
  case BO_XorAssign:
3743
0
  case BO_OrAssign:
3744
0
  case BO_Comma:
3745
0
    llvm_unreachable("Found unsupported binary operation for fixed point types.");
3746
524
  }
3747
3748
462
  bool IsShift = BinaryOperator::isShiftOp(op.Opcode) ||
3749
462
                 
BinaryOperator::isShiftAssignOp(op.Opcode)382
;
3750
  // Convert to the result type.
3751
462
  return FPBuilder.CreateFixedToFixed(Result, IsShift ? 
LHSFixedSema86
3752
462
                                                      : 
CommonFixedSema376
,
3753
462
                                      ResultFixedSema);
3754
524
}
3755
3756
141k
Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3757
  // The LHS is always a pointer if either side is.
3758
141k
  if (!op.LHS->getType()->isPointerTy()) {
3759
138k
    if (op.Ty->isSignedIntegerOrEnumerationType()) {
3760
128k
      switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3761
2
      case LangOptions::SOB_Defined:
3762
2
        return Builder.CreateSub(op.LHS, op.RHS, "sub");
3763
128k
      case LangOptions::SOB_Undefined:
3764
128k
        if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3765
128k
          return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3766
128k
        
LLVM_FALLTHROUGH15
;15
3767
19
      case LangOptions::SOB_Trapping:
3768
19
        if (CanElideOverflowCheck(CGF.getContext(), op))
3769
8
          return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3770
11
        return EmitOverflowCheckedBinOp(op);
3771
128k
      }
3772
128k
    }
3773
3774
10.0k
    if (op.Ty->isConstantMatrixType()) {
3775
23
      llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3776
23
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
3777
23
      return MB.CreateSub(op.LHS, op.RHS);
3778
23
    }
3779
3780
10.0k
    if (op.Ty->isUnsignedIntegerType() &&
3781
10.0k
        
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)8.73k
&&
3782
10.0k
        
!CanElideOverflowCheck(CGF.getContext(), op)5
)
3783
3
      return EmitOverflowCheckedBinOp(op);
3784
3785
10.0k
    if (op.LHS->getType()->isFPOrFPVectorTy()) {
3786
661
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
3787
      // Try to form an fmuladd.
3788
661
      if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3789
3
        return FMulAdd;
3790
658
      return Builder.CreateFSub(op.LHS, op.RHS, "sub");
3791
661
    }
3792
3793
9.39k
    if (op.isFixedPointOp())
3794
94
      return EmitFixedPointBinOp(op);
3795
3796
9.29k
    return Builder.CreateSub(op.LHS, op.RHS, "sub");
3797
9.39k
  }
3798
3799
  // If the RHS is not a pointer, then we have normal pointer
3800
  // arithmetic.
3801
3.16k
  if (!op.RHS->getType()->isPointerTy())
3802
760
    return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3803
3804
  // Otherwise, this is a pointer subtraction.
3805
3806
  // Do the raw subtraction part.
3807
2.40k
  llvm::Value *LHS
3808
2.40k
    = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3809
2.40k
  llvm::Value *RHS
3810
2.40k
    = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3811
2.40k
  Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3812
3813
  // Okay, figure out the element size.
3814
2.40k
  const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3815
2.40k
  QualType elementType = expr->getLHS()->getType()->getPointeeType();
3816
3817
2.40k
  llvm::Value *divisor = nullptr;
3818
3819
  // For a variable-length array, this is going to be non-constant.
3820
2.40k
  if (const VariableArrayType *vla
3821
2.40k
        = CGF.getContext().getAsVariableArrayType(elementType)) {
3822
2
    auto VlaSize = CGF.getVLASize(vla);
3823
2
    elementType = VlaSize.Type;
3824
2
    divisor = VlaSize.NumElts;
3825
3826
    // Scale the number of non-VLA elements by the non-VLA element size.
3827
2
    CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3828
2
    if (!eltSize.isOne())
3829
2
      divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3830
3831
  // For everything elese, we can just compute it, safe in the
3832
  // assumption that Sema won't let anything through that we can't
3833
  // safely compute the size of.
3834
2.40k
  } else {
3835
2.40k
    CharUnits elementSize;
3836
    // Handle GCC extension for pointer arithmetic on void* and
3837
    // function pointer types.
3838
2.40k
    if (elementType->isVoidType() || 
elementType->isFunctionType()2.40k
)
3839
3
      elementSize = CharUnits::One();
3840
2.39k
    else
3841
2.39k
      elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3842
3843
    // Don't even emit the divide for element size of 1.
3844
2.40k
    if (elementSize.isOne())
3845
597
      return diffInChars;
3846
3847
1.80k
    divisor = CGF.CGM.getSize(elementSize);
3848
1.80k
  }
3849
3850
  // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3851
  // pointer difference in C is only defined in the case where both operands
3852
  // are pointing to elements of an array.
3853
1.80k
  return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3854
2.40k
}
3855
3856
42
Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3857
42
  llvm::IntegerType *Ty;
3858
42
  if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3859
8
    Ty = cast<llvm::IntegerType>(VT->getElementType());
3860
34
  else
3861
34
    Ty = cast<llvm::IntegerType>(LHS->getType());
3862
42
  return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3863
42
}
3864
3865
Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
3866
22
                                              const Twine &Name) {
3867
22
  llvm::IntegerType *Ty;
3868
22
  if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3869
8
    Ty = cast<llvm::IntegerType>(VT->getElementType());
3870
14
  else
3871
14
    Ty = cast<llvm::IntegerType>(LHS->getType());
3872
3873
22
  if (llvm::isPowerOf2_64(Ty->getBitWidth()))
3874
20
        return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
3875
3876
2
  return Builder.CreateURem(
3877
2
      RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
3878
22
}
3879
3880
7.20k
Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3881
  // TODO: This misses out on the sanitizer check below.
3882
7.20k
  if (Ops.isFixedPointOp())
3883
52
    return EmitFixedPointBinOp(Ops);
3884
3885
  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3886
  // RHS to the same size as the LHS.
3887
7.15k
  Value *RHS = Ops.RHS;
3888
7.15k
  if (Ops.LHS->getType() != RHS->getType())
3889
531
    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3890
3891
7.15k
  bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3892
7.15k
                            
Ops.Ty->hasSignedIntegerRepresentation()16
&&
3893
7.15k
                            
!CGF.getLangOpts().isSignedOverflowDefined()12
&&
3894
7.15k
                            
!CGF.getLangOpts().CPlusPlus2011
;
3895
7.15k
  bool SanitizeUnsignedBase =
3896
7.15k
      CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
3897
7.15k
      
Ops.Ty->hasUnsignedIntegerRepresentation()1
;
3898
7.15k
  bool SanitizeBase = SanitizeSignedBase || 
SanitizeUnsignedBase7.14k
;
3899
7.15k
  bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3900
  // OpenCL 6.3j: shift values are effectively % word size of LHS.
3901
7.15k
  if (CGF.getLangOpts().OpenCL)
3902
18
    RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
3903
7.13k
  else if ((SanitizeBase || 
SanitizeExponent7.12k
) &&
3904
7.13k
           
isa<llvm::IntegerType>(Ops.LHS->getType())16
) {
3905
16
    CodeGenFunction::SanitizerScope SanScope(&CGF);
3906
16
    SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3907
16
    llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3908
16
    llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3909
3910
16
    if (SanitizeExponent) {
3911
16
      Checks.push_back(
3912
16
          std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3913
16
    }
3914
3915
16
    if (SanitizeBase) {
3916
      // Check whether we are shifting any non-zero bits off the top of the
3917
      // integer. We only emit this check if exponent is valid - otherwise
3918
      // instructions below will have undefined behavior themselves.
3919
11
      llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3920
11
      llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3921
11
      llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3922
11
      Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3923
11
      llvm::Value *PromotedWidthMinusOne =
3924
11
          (RHS == Ops.RHS) ? 
WidthMinusOne8
3925
11
                           : 
GetWidthMinusOneValue(Ops.LHS, RHS)3
;
3926
11
      CGF.EmitBlock(CheckShiftBase);
3927
11
      llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3928
11
          Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3929
11
                                     /*NUW*/ true, /*NSW*/ true),
3930
11
          "shl.check");
3931
11
      if (SanitizeUnsignedBase || 
CGF.getLangOpts().CPlusPlus10
) {
3932
        // In C99, we are not permitted to shift a 1 bit into the sign bit.
3933
        // Under C++11's rules, shifting a 1 bit into the sign bit is
3934
        // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3935
        // define signed left shifts, so we use the C99 and C++11 rules there).
3936
        // Unsigned shifts can always shift into the top bit.
3937
3
        llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3938
3
        BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3939
3
      }
3940
11
      llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3941
11
      llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3942
11
      CGF.EmitBlock(Cont);
3943
11
      llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3944
11
      BaseCheck->addIncoming(Builder.getTrue(), Orig);
3945
11
      BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3946
11
      Checks.push_back(std::make_pair(
3947
11
          BaseCheck, SanitizeSignedBase ? 
SanitizerKind::ShiftBase10
3948
11
                                        : 
SanitizerKind::UnsignedShiftBase1
));
3949
11
    }
3950
3951
16
    assert(!Checks.empty());
3952
0
    EmitBinOpCheck(Checks, Ops);
3953
16
  }
3954
3955
0
  return Builder.CreateShl(Ops.LHS, RHS, "shl");
3956
7.20k
}
3957
3958
943
Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3959
  // TODO: This misses out on the sanitizer check below.
3960
943
  if (Ops.isFixedPointOp())
3961
34
    return EmitFixedPointBinOp(Ops);
3962
3963
  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3964
  // RHS to the same size as the LHS.
3965
909
  Value *RHS = Ops.RHS;
3966
909
  if (Ops.LHS->getType() != RHS->getType())
3967
381
    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3968
3969
  // OpenCL 6.3j: shift values are effectively % word size of LHS.
3970
909
  if (CGF.getLangOpts().OpenCL)
3971
4
    RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
3972
905
  else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3973
905
           
isa<llvm::IntegerType>(Ops.LHS->getType())3
) {
3974
3
    CodeGenFunction::SanitizerScope SanScope(&CGF);
3975
3
    llvm::Value *Valid =
3976
3
        Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3977
3
    EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3978
3
  }
3979
3980
909
  if (Ops.Ty->hasUnsignedIntegerRepresentation())
3981
510
    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3982
399
  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3983
909
}
3984
3985
enum IntrinsicType { VCMPEQ, VCMPGT };
3986
// return corresponding comparison intrinsic for given vector type
3987
static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3988
217
                                        BuiltinType::Kind ElemKind) {
3989
217
  switch (ElemKind) {
3990
0
  default: llvm_unreachable("unexpected element type");
3991
0
  case BuiltinType::Char_U:
3992
31
  case BuiltinType::UChar:
3993
31
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpequb_p15
:
3994
31
                            
llvm::Intrinsic::ppc_altivec_vcmpgtub_p16
;
3995
0
  case BuiltinType::Char_S:
3996
28
  case BuiltinType::SChar:
3997
28
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpequb_p12
:
3998
28
                            
llvm::Intrinsic::ppc_altivec_vcmpgtsb_p16
;
3999
35
  case BuiltinType::UShort:
4000
35
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpequh_p19
:
4001
35
                            
llvm::Intrinsic::ppc_altivec_vcmpgtuh_p16
;
4002
28
  case BuiltinType::Short:
4003
28
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpequh_p12
:
4004
28
                            
llvm::Intrinsic::ppc_altivec_vcmpgtsh_p16
;
4005
31
  case BuiltinType::UInt:
4006
31
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpequw_p15
:
4007
31
                            
llvm::Intrinsic::ppc_altivec_vcmpgtuw_p16
;
4008
28
  case BuiltinType::Int:
4009
28
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpequw_p12
:
4010
28
                            
llvm::Intrinsic::ppc_altivec_vcmpgtsw_p16
;
4011
1
  case BuiltinType::ULong:
4012
5
  case BuiltinType::ULongLong:
4013
5
    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
4014
5
                            
llvm::Intrinsic::ppc_altivec_vcmpgtud_p0
;
4015
1
  case BuiltinType::Long:
4016
6
  case BuiltinType::LongLong:
4017
6
    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
4018
6
                            
llvm::Intrinsic::ppc_altivec_vcmpgtsd_p0
;
4019
20
  case BuiltinType::Float:
4020
20
    return (IT == VCMPEQ) ? 
llvm::Intrinsic::ppc_altivec_vcmpeqfp_p12
:
4021
20
                            
llvm::Intrinsic::ppc_altivec_vcmpgtfp_p8
;
4022
5
  case BuiltinType::Double:
4023
5
    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
4024
5
                            
llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p0
;
4025
0
  case BuiltinType::UInt128:
4026
0
    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
4027
0
                          : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
4028
0
  case BuiltinType::Int128:
4029
0
    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
4030
0
                          : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
4031
217
  }
4032
217
}
4033
4034
Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
4035
                                      llvm::CmpInst::Predicate UICmpOpc,
4036
                                      llvm::CmpInst::Predicate SICmpOpc,
4037
                                      llvm::CmpInst::Predicate FCmpOpc,
4038
82.0k
                                      bool IsSignaling) {
4039
82.0k
  TestAndClearIgnoreResultAssign();
4040
82.0k
  Value *Result;
4041
82.0k
  QualType LHSTy = E->getLHS()->getType();
4042
82.0k
  QualType RHSTy = E->getRHS()->getType();
4043
82.0k
  if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
4044
23
    assert(E->getOpcode() == BO_EQ ||
4045
23
           E->getOpcode() == BO_NE);
4046
0
    Value *LHS = CGF.EmitScalarExpr(E->getLHS());
4047
23
    Value *RHS = CGF.EmitScalarExpr(E->getRHS());
4048
23
    Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
4049
23
                   CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
4050
82.0k
  } else if (!LHSTy->isAnyComplexType() && 
!RHSTy->isAnyComplexType()81.9k
) {
4051
81.9k
    BinOpInfo BOInfo = EmitBinOps(E);
4052
81.9k
    Value *LHS = BOInfo.LHS;
4053
81.9k
    Value *RHS = BOInfo.RHS;
4054
4055
    // If AltiVec, the comparison results in a numeric type, so we use
4056
    // intrinsics comparing vectors and giving 0 or 1 as a result
4057
81.9k
    if (LHSTy->isVectorType() && 
!E->getType()->isVectorType()899
) {
4058
      // constants for mapping CR6 register bits to predicate result
4059
225
      enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
4060
4061
225
      llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
4062
4063
      // in several cases vector arguments order will be reversed
4064
225
      Value *FirstVecArg = LHS,
4065
225
            *SecondVecArg = RHS;
4066
4067
225
      QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
4068
225
      BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
4069
4070
225
      switch(E->getOpcode()) {
4071
0
      default: llvm_unreachable("is not a comparison operation");
4072
85
      case BO_EQ:
4073
85
        CR6 = CR6_LT;
4074
85
        ID = GetIntrinsic(VCMPEQ, ElementKind);
4075
85
        break;
4076
28
      case BO_NE:
4077
28
        CR6 = CR6_EQ;
4078
28
        ID = GetIntrinsic(VCMPEQ, ElementKind);
4079
28
        break;
4080
28
      case BO_LT:
4081
28
        CR6 = CR6_LT;
4082
28
        ID = GetIntrinsic(VCMPGT, ElementKind);
4083
28
        std::swap(FirstVecArg, SecondVecArg);
4084
28
        break;
4085
28
      case BO_GT:
4086
28
        CR6 = CR6_LT;
4087
28
        ID = GetIntrinsic(VCMPGT, ElementKind);
4088
28
        break;
4089
28
      case BO_LE:
4090
28
        if (ElementKind == BuiltinType::Float) {
4091
4
          CR6 = CR6_LT;
4092
4
          ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4093
4
          std::swap(FirstVecArg, SecondVecArg);
4094
4
        }
4095
24
        else {
4096
24
          CR6 = CR6_EQ;
4097
24
          ID = GetIntrinsic(VCMPGT, ElementKind);
4098
24
        }
4099
28
        break;
4100
28
      case BO_GE:
4101
28
        if (ElementKind == BuiltinType::Float) {
4102
4
          CR6 = CR6_LT;
4103
4
          ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4104
4
        }
4105
24
        else {
4106
24
          CR6 = CR6_EQ;
4107
24
          ID = GetIntrinsic(VCMPGT, ElementKind);
4108
24
          std::swap(FirstVecArg, SecondVecArg);
4109
24
        }
4110
28
        break;
4111
225
      }
4112
4113
225
      Value *CR6Param = Builder.getInt32(CR6);
4114
225
      llvm::Function *F = CGF.CGM.getIntrinsic(ID);
4115
225
      Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
4116
4117
      // The result type of intrinsic may not be same as E->getType().
4118
      // If E->getType() is not BoolTy, EmitScalarConversion will do the
4119
      // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
4120
      // do nothing, if ResultTy is not i1 at the same time, it will cause
4121
      // crash later.
4122
225
      llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
4123
225
      if (ResultTy->getBitWidth() > 1 &&
4124
225
          E->getType() == CGF.getContext().BoolTy)
4125
6
        Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
4126
225
      return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4127
225
                                  E->getExprLoc());
4128
225
    }
4129
4130
81.7k
    if (BOInfo.isFixedPointOp()) {
4131
62
      Result = EmitFixedPointBinOp(BOInfo);
4132
81.6k
    } else if (LHS->getType()->isFPOrFPVectorTy()) {
4133
1.48k
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
4134
1.48k
      if (!IsSignaling)
4135
484
        Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4136
1.00k
      else
4137
1.00k
        Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
4138
80.2k
    } else if (LHSTy->hasSignedIntegerRepresentation()) {
4139
42.0k
      Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
4140
42.0k
    } else {
4141
      // Unsigned integers and pointers.
4142
4143
38.1k
      if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4144
38.1k
          
!isa<llvm::ConstantPointerNull>(LHS)8
&&
4145
38.1k
          
!isa<llvm::ConstantPointerNull>(RHS)8
) {
4146
4147
        // Dynamic information is required to be stripped for comparisons,
4148
        // because it could leak the dynamic information.  Based on comparisons
4149
        // of pointers to dynamic objects, the optimizer can replace one pointer
4150
        // with another, which might be incorrect in presence of invariant
4151
        // groups. Comparison with null is safe because null does not carry any
4152
        // dynamic information.
4153
6
        if (LHSTy.mayBeDynamicClass())
4154
3
          LHS = Builder.CreateStripInvariantGroup(LHS);
4155
6
        if (RHSTy.mayBeDynamicClass())
4156
3
          RHS = Builder.CreateStripInvariantGroup(RHS);
4157
6
      }
4158
4159
38.1k
      Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
4160
38.1k
    }
4161
4162
    // If this is a vector comparison, sign extend the result to the appropriate
4163
    // vector integer type and return it (don't convert to bool).
4164
81.7k
    if (LHSTy->isVectorType())
4165
674
      return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
4166
4167
81.7k
  } else {
4168
    // Complex Comparison: can only be an equality comparison.
4169
64
    CodeGenFunction::ComplexPairTy LHS, RHS;
4170
64
    QualType CETy;
4171
64
    if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4172
46
      LHS = CGF.EmitComplexExpr(E->getLHS());
4173
46
      CETy = CTy->getElementType();
4174
46
    } else {
4175
18
      LHS.first = Visit(E->getLHS());
4176
18
      LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4177
18
      CETy = LHSTy;
4178
18
    }
4179
64
    if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4180
46
      RHS = CGF.EmitComplexExpr(E->getRHS());
4181
46
      assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4182
46
                                                     CTy->getElementType()) &&
4183
46
             "The element types must always match.");
4184
0
      (void)CTy;
4185
46
    } else {
4186
18
      RHS.first = Visit(E->getRHS());
4187
18
      RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4188
18
      assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4189
18
             "The element types must always match.");
4190
18
    }
4191
4192
0
    Value *ResultR, *ResultI;
4193
64
    if (CETy->isRealFloatingType()) {
4194
      // As complex comparisons can only be equality comparisons, they
4195
      // are never signaling comparisons.
4196
63
      ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4197
63
      ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
4198
63
    } else {
4199
      // Complex comparisons can only be equality comparisons.  As such, signed
4200
      // and unsigned opcodes are the same.
4201
1
      ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4202
1
      ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
4203
1
    }
4204
4205
64
    if (E->getOpcode() == BO_EQ) {
4206
28
      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4207
36
    } else {
4208
36
      assert(E->getOpcode() == BO_NE &&
4209
36
             "Complex comparison other than == or != ?");
4210
0
      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4211
36
    }
4212
64
  }
4213
4214
81.1k
  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4215
81.1k
                              E->getExprLoc());
4216
82.0k
}
4217
4218
36.5k
Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4219
36.5k
  bool Ignore = TestAndClearIgnoreResultAssign();
4220
4221
36.5k
  Value *RHS;
4222
36.5k
  LValue LHS;
4223
4224
36.5k
  switch (E->getLHS()->getType().getObjCLifetime()) {
4225
118
  case Qualifiers::OCL_Strong:
4226
118
    std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
4227
118
    break;
4228
4229
4
  case Qualifiers::OCL_Autoreleasing:
4230
4
    std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
4231
4
    break;
4232
4233
29
  case Qualifiers::OCL_ExplicitNone:
4234
29
    std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4235
29
    break;
4236
4237
31
  case Qualifiers::OCL_Weak:
4238
31
    RHS = Visit(E->getRHS());
4239
31
    LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4240
31
    RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
4241
31
    break;
4242
4243
36.3k
  case Qualifiers::OCL_None:
4244
    // __block variables need to have the rhs evaluated first, plus
4245
    // this should improve codegen just a little.
4246
36.3k
    RHS = Visit(E->getRHS());
4247
36.3k
    LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4248
4249
    // Store the value into the LHS.  Bit-fields are handled specially
4250
    // because the result is altered by the store, i.e., [C99 6.5.16p1]
4251
    // 'An assignment expression has the value of the left operand after
4252
    // the assignment...'.
4253
36.3k
    if (LHS.isBitField()) {
4254
451
      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
4255
35.8k
    } else {
4256
35.8k
      CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
4257
35.8k
      CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
4258
35.8k
    }
4259
36.5k
  }
4260
4261
  // If the result is clearly ignored, return now.
4262
36.5k
  if (Ignore)
4263
35.7k
    return nullptr;
4264
4265
  // The result of an assignment in C is the assigned r-value.
4266
751
  if (!CGF.getLangOpts().CPlusPlus)
4267
279
    return RHS;
4268
4269
  // If the lvalue is non-volatile, return the computed value of the assignment.
4270
472
  if (!LHS.isVolatileQualified())
4271
452
    return RHS;
4272
4273
  // Otherwise, reload the value.
4274
20
  return EmitLoadOfLValue(LHS, E->getExprLoc());
4275
472
}
4276
4277
364
Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
4278
  // Perform vector logical and on comparisons with zero vectors.
4279
364
  if (E->getType()->isVectorType()) {
4280
10
    CGF.incrementProfileCounter(E);
4281
4282
10
    Value *LHS = Visit(E->getLHS());
4283
10
    Value *RHS = Visit(E->getRHS());
4284
10
    Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4285
10
    if (LHS->getType()->isFPOrFPVectorTy()) {
4286
8
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4287
8
          CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
4288
8
      LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4289
8
      RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4290
8
    } else {
4291
2
      LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4292
2
      RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4293
2
    }
4294
10
    Value *And = Builder.CreateAnd(LHS, RHS);
4295
10
    return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
4296
10
  }
4297
4298
354
  bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
4299
354
  llvm::Type *ResTy = ConvertType(E->getType());
4300
4301
  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4302
  // If we have 1 && X, just emit X without inserting the control flow.
4303
354
  bool LHSCondVal;
4304
354
  if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4305
8
    if (LHSCondVal) { // If we have 1 && X, just emit X.
4306
4
      CGF.incrementProfileCounter(E);
4307
4308
4
      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4309
4310
      // If we're generating for profiling or coverage, generate a branch to a
4311
      // block that increments the RHS counter needed to track branch condition
4312
      // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
4313
      // "FalseBlock" after the increment is done.
4314
4
      if (InstrumentRegions &&
4315
4
          
CodeGenFunction::isInstrumentedCondition(E->getRHS())2
) {
4316
2
        llvm::BasicBlock *FBlock = CGF.createBasicBlock("land.end");
4317
2
        llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
4318
2
        Builder.CreateCondBr(RHSCond, RHSBlockCnt, FBlock);
4319
2
        CGF.EmitBlock(RHSBlockCnt);
4320
2
        CGF.incrementProfileCounter(E->getRHS());
4321
2
        CGF.EmitBranch(FBlock);
4322
2
        CGF.EmitBlock(FBlock);
4323
2
      }
4324
4325
      // ZExt result to int or bool.
4326
4
      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
4327
4
    }
4328
4329
    // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
4330
4
    if (!CGF.ContainsLabel(E->getRHS()))
4331
3
      return llvm::Constant::getNullValue(ResTy);
4332
4
  }
4333
4334
347
  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4335
347
  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
4336
4337
347
  CodeGenFunction::ConditionalEvaluation eval(CGF);
4338
4339
  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
4340
347
  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4341
347
                           CGF.getProfileCount(E->getRHS()));
4342
4343
  // Any edges into the ContBlock are now from an (indeterminate number of)
4344
  // edges from this first condition.  All of these values will be false.  Start
4345
  // setting up the PHI node in the Cont Block for this.
4346
347
  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4347
347
                                            "", ContBlock);
4348
347
  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4349
763
       PI != PE; 
++PI416
)
4350
416
    PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
4351
4352
347
  eval.begin(CGF);
4353
347
  CGF.EmitBlock(RHSBlock);
4354
347
  CGF.incrementProfileCounter(E);
4355
347
  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4356
347
  eval.end(CGF);
4357
4358
  // Reaquire the RHS block, as there may be subblocks inserted.
4359
347
  RHSBlock = Builder.GetInsertBlock();
4360
4361
  // If we're generating for profiling or coverage, generate a branch on the
4362
  // RHS to a block that increments the RHS true counter needed to track branch
4363
  // condition coverage.
4364
347
  if (InstrumentRegions &&
4365
347
      
CodeGenFunction::isInstrumentedCondition(E->getRHS())28
) {
4366
24
    llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
4367
24
    Builder.CreateCondBr(RHSCond, RHSBlockCnt, ContBlock);
4368
24
    CGF.EmitBlock(RHSBlockCnt);
4369
24
    CGF.incrementProfileCounter(E->getRHS());
4370
24
    CGF.EmitBranch(ContBlock);
4371
24
    PN->addIncoming(RHSCond, RHSBlockCnt);
4372
24
  }
4373
4374
  // Emit an unconditional branch from this block to ContBlock.
4375
347
  {
4376
    // There is no need to emit line number for unconditional branch.
4377
347
    auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4378
347
    CGF.EmitBlock(ContBlock);
4379
347
  }
4380
  // Insert an entry into the phi node for the edge with the value of RHSCond.
4381
347
  PN->addIncoming(RHSCond, RHSBlock);
4382
4383
  // Artificial location to preserve the scope information
4384
347
  {
4385
347
    auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4386
347
    PN->setDebugLoc(Builder.getCurrentDebugLocation());
4387
347
  }
4388
4389
  // ZExt result to int.
4390
347
  return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4391
354
}
4392
4393
121
Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4394
  // Perform vector logical or on comparisons with zero vectors.
4395
121
  if (E->getType()->isVectorType()) {
4396
10
    CGF.incrementProfileCounter(E);
4397
4398
10
    Value *LHS = Visit(E->getLHS());
4399
10
    Value *RHS = Visit(E->getRHS());
4400
10
    Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4401
10
    if (LHS->getType()->isFPOrFPVectorTy()) {
4402
8
      CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4403
8
          CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
4404
8
      LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4405
8
      RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4406
8
    } else {
4407
2
      LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4408
2
      RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4409
2
    }
4410
10
    Value *Or = Builder.CreateOr(LHS, RHS);
4411
10
    return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4412
10
  }
4413
4414
111
  bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
4415
111
  llvm::Type *ResTy = ConvertType(E->getType());
4416
4417
  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4418
  // If we have 0 || X, just emit X without inserting the control flow.
4419
111
  bool LHSCondVal;
4420
111
  if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4421
6
    if (!LHSCondVal) { // If we have 0 || X, just emit X.
4422
2
      CGF.incrementProfileCounter(E);
4423
4424
2
      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4425
4426
      // If we're generating for profiling or coverage, generate a branch to a
4427
      // block that increments the RHS counter need to track branch condition
4428
      // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
4429
      // "FalseBlock" after the increment is done.
4430
2
      if (InstrumentRegions &&
4431
2
          CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
4432
2
        llvm::BasicBlock *FBlock = CGF.createBasicBlock("lor.end");
4433
2
        llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
4434
2
        Builder.CreateCondBr(RHSCond, FBlock, RHSBlockCnt);
4435
2
        CGF.EmitBlock(RHSBlockCnt);
4436
2
        CGF.incrementProfileCounter(E->getRHS());
4437
2
        CGF.EmitBranch(FBlock);
4438
2
        CGF.EmitBlock(FBlock);
4439
2
      }
4440
4441
      // ZExt result to int or bool.
4442
2
      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4443
2
    }
4444
4445
    // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4446
4
    if (!CGF.ContainsLabel(E->getRHS()))
4447
4
      return llvm::ConstantInt::get(ResTy, 1);
4448
4
  }
4449
4450
105
  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4451
105
  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4452
4453
105
  CodeGenFunction::ConditionalEvaluation eval(CGF);
4454
4455
  // Branch on the LHS first.  If it is true, go to the success (cont) block.
4456
105
  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4457
105
                           CGF.getCurrentProfileCount() -
4458
105
                               CGF.getProfileCount(E->getRHS()));
4459
4460
  // Any edges into the ContBlock are now from an (indeterminate number of)
4461
  // edges from this first condition.  All of these values will be true.  Start
4462
  // setting up the PHI node in the Cont Block for this.
4463
105
  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4464
105
                                            "", ContBlock);
4465
105
  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4466
292
       PI != PE; 
++PI187
)
4467
187
    PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4468
4469
105
  eval.begin(CGF);
4470
4471
  // Emit the RHS condition as a bool value.
4472
105
  CGF.EmitBlock(RHSBlock);
4473
105
  CGF.incrementProfileCounter(E);
4474
105
  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4475
4476
105
  eval.end(CGF);
4477
4478
  // Reaquire the RHS block, as there may be subblocks inserted.
4479
105
  RHSBlock = Builder.GetInsertBlock();
4480
4481
  // If we're generating for profiling or coverage, generate a branch on the
4482
  // RHS to a block that increments the RHS true counter needed to track branch
4483
  // condition coverage.
4484
105
  if (InstrumentRegions &&
4485
105
      
CodeGenFunction::isInstrumentedCondition(E->getRHS())22
) {
4486
20
    llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
4487
20
    Builder.CreateCondBr(RHSCond, ContBlock, RHSBlockCnt);
4488
20
    CGF.EmitBlock(RHSBlockCnt);
4489
20
    CGF.incrementProfileCounter(E->getRHS());
4490
20
    CGF.EmitBranch(ContBlock);
4491
20
    PN->addIncoming(RHSCond, RHSBlockCnt);
4492
20
  }
4493
4494
  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
4495
  // into the phi node for the edge with the value of RHSCond.
4496
105
  CGF.EmitBlock(ContBlock);
4497
105
  PN->addIncoming(RHSCond, RHSBlock);
4498
4499
  // ZExt result to int.
4500
105
  return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4501
111
}
4502
4503
358
Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4504
358
  CGF.EmitIgnoredExpr(E->getLHS());
4505
358
  CGF.EnsureInsertPoint();
4506
358
  return Visit(E->getRHS());
4507
358
}
4508
4509
//===----------------------------------------------------------------------===//
4510
//                             Other Operators
4511
//===----------------------------------------------------------------------===//
4512
4513
/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4514
/// expression is cheap enough and side-effect-free enough to evaluate
4515
/// unconditionally instead of conditionally.  This is used to convert control
4516
/// flow into selects in some cases.
4517
static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4518
18.3k
                                                   CodeGenFunction &CGF) {
4519
  // Anything that is an integer or floating point constant is fine.
4520
18.3k
  return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4521
4522
  // Even non-volatile automatic variables can't be evaluated unconditionally.
4523
  // Referencing a thread_local may cause non-trivial initialization work to
4524
  // occur. If we're inside a lambda and one of the variables is from the scope
4525
  // outside the lambda, that function may have returned already. Reading its
4526
  // locals is a bad idea. Also, these reads may introduce races there didn't
4527
  // exist in the source-level program.
4528
18.3k
}
4529
4530
4531
Value *ScalarExprEmitter::
4532
10.8k
VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4533
10.8k
  TestAndClearIgnoreResultAssign();
4534
4535
  // Bind the common expression if necessary.
4536
10.8k
  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4537
4538
10.8k
  Expr *condExpr = E->getCond();
4539
10.8k
  Expr *lhsExpr = E->getTrueExpr();
4540
10.8k
  Expr *rhsExpr = E->getFalseExpr();
4541
4542
  // If the condition constant folds and can be elided, try to avoid emitting
4543
  // the condition and the dead arm.
4544
10.8k
  bool CondExprBool;
4545
10.8k
  if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4546
98
    Expr *live = lhsExpr, *dead = rhsExpr;
4547
98
    if (!CondExprBool) 
std::swap(live, dead)45
;
4548
4549
    // If the dead side doesn't have labels we need, just emit the Live part.
4550
98
    if (!CGF.ContainsLabel(dead)) {
4551
98
      if (CondExprBool)
4552
53
        CGF.incrementProfileCounter(E);
4553
98
      Value *Result = Visit(live);
4554
4555
      // If the live part is a throw expression, it acts like it has a void
4556
      // type, so evaluating it returns a null Value*.  However, a conditional
4557
      // with non-void type must return a non-null Value*.
4558
98
      if (!Result && 
!E->getType()->isVoidType()9
)
4559
1
        Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4560
4561
98
      return Result;
4562
98
    }
4563
98
  }
4564
4565
  // OpenCL: If the condition is a vector, we can treat this condition like
4566
  // the select function.
4567
10.7k
  if ((CGF.getLangOpts().OpenCL && 
condExpr->getType()->isVectorType()20
) ||
4568
10.7k
      condExpr->getType()->isExtVectorType()) {
4569
16
    CGF.incrementProfileCounter(E);
4570
4571
16
    llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4572
16
    llvm::Value *LHS = Visit(lhsExpr);
4573
16
    llvm::Value *RHS = Visit(rhsExpr);
4574
4575
16
    llvm::Type *condType = ConvertType(condExpr->getType());
4576
16
    auto *vecTy = cast<llvm::FixedVectorType>(condType);
4577
4578
16
    unsigned numElem = vecTy->getNumElements();
4579
16
    llvm::Type *elemType = vecTy->getElementType();
4580
4581
16
    llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4582
16
    llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4583
16
    llvm::Value *tmp = Builder.CreateSExt(
4584
16
        TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
4585
16
    llvm::Value *tmp2 = Builder.CreateNot(tmp);
4586
4587
    // Cast float to int to perform ANDs if necessary.
4588
16
    llvm::Value *RHSTmp = RHS;
4589
16
    llvm::Value *LHSTmp = LHS;
4590
16
    bool wasCast = false;
4591
16
    llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4592
16
    if (rhsVTy->getElementType()->isFloatingPointTy()) {
4593
6
      RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4594
6
      LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4595
6
      wasCast = true;
4596
6
    }
4597
4598
16
    llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4599
16
    llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4600
16
    llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4601
16
    if (wasCast)
4602
6
      tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4603
4604
16
    return tmp5;
4605
16
  }
4606
4607
10.7k
  if (condExpr->getType()->isVectorType()) {
4608
21
    CGF.incrementProfileCounter(E);
4609
4610
21
    llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4611
21
    llvm::Value *LHS = Visit(lhsExpr);
4612
21
    llvm::Value *RHS = Visit(rhsExpr);
4613
4614
21
    llvm::Type *CondType = ConvertType(condExpr->getType());
4615
21
    auto *VecTy = cast<llvm::VectorType>(CondType);
4616
21
    llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4617
4618
21
    CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4619
21
    return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4620
21
  }
4621
4622
  // If this is a really simple expression (like x ? 4 : 5), emit this as a
4623
  // select instead of as control flow.  We can only do this if it is cheap and
4624
  // safe to evaluate the LHS and RHS unconditionally.
4625
10.6k
  if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4626
10.6k
      
isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)7.64k
) {
4627
290
    llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4628
290
    llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4629
4630
290
    CGF.incrementProfileCounter(E, StepV);
4631
4632
290
    llvm::Value *LHS = Visit(lhsExpr);
4633
290
    llvm::Value *RHS = Visit(rhsExpr);
4634
290
    if (!LHS) {
4635
      // If the conditional has void type, make sure we return a null Value*.
4636
0
      assert(!RHS && "LHS and RHS types must match");
4637
0
      return nullptr;
4638
0
    }
4639
290
    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4640
290
  }
4641
4642
10.3k
  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4643
10.3k
  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4644
10.3k
  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4645
4646
10.3k
  CodeGenFunction::ConditionalEvaluation eval(CGF);
4647
10.3k
  CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4648
10.3k
                           CGF.getProfileCount(lhsExpr));
4649
4650
10.3k
  CGF.EmitBlock(LHSBlock);
4651
10.3k
  CGF.incrementProfileCounter(E);
4652
10.3k
  eval.begin(CGF);
4653
10.3k
  Value *LHS = Visit(lhsExpr);
4654
10.3k
  eval.end(CGF);
4655
4656
10.3k
  LHSBlock = Builder.GetInsertBlock();
4657
10.3k
  Builder.CreateBr(ContBlock);
4658
4659
10.3k
  CGF.EmitBlock(RHSBlock);
4660
10.3k
  eval.begin(CGF);
4661
10.3k
  Value *RHS = Visit(rhsExpr);
4662
10.3k
  eval.end(CGF);
4663
4664
10.3k
  RHSBlock = Builder.GetInsertBlock();
4665
10.3k
  CGF.EmitBlock(ContBlock);
4666
4667
  // If the LHS or RHS is a throw expression, it will be legitimately null.
4668
10.3k
  if (!LHS)
4669
144
    return RHS;
4670
10.2k
  if (!RHS)
4671
2
    return LHS;
4672
4673
  // Create a PHI node for the real part.
4674
10.2k
  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4675
10.2k
  PN->addIncoming(LHS, LHSBlock);
4676
10.2k
  PN->addIncoming(RHS, RHSBlock);
4677
10.2k
  return PN;
4678
10.2k
}
4679
4680
3
Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4681
3
  return Visit(E->getChosenSubExpr());
4682
3
}
4683
4684
454
Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4685
454
  QualType Ty = VE->getType();
4686
4687
454
  if (Ty->isVariablyModifiedType())
4688
1
    CGF.EmitVariablyModifiedType(Ty);
4689
4690
454
  Address ArgValue = Address::invalid();
4691
454
  Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4692
4693
454
  llvm::Type *ArgTy = ConvertType(VE->getType());
4694
4695
  // If EmitVAArg fails, emit an error.
4696
454
  if (!ArgPtr.isValid()) {
4697
0
    CGF.ErrorUnsupported(VE, "va_arg expression");
4698
0
    return llvm::UndefValue::get(ArgTy);
4699
0
  }
4700
4701
  // FIXME Volatility.
4702
454
  llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4703
4704
  // If EmitVAArg promoted the type, we must truncate it.
4705
454
  if (ArgTy != Val->getType()) {
4706
0
    if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4707
0
      Val = Builder.CreateIntToPtr(Val, ArgTy);
4708
0
    else
4709
0
      Val = Builder.CreateTrunc(Val, ArgTy);
4710
0
  }
4711
4712
454
  return Val;
4713
454
}
4714
4715
1.06k
Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4716
1.06k
  return CGF.EmitBlockLiteral(block);
4717
1.06k
}
4718
4719
// Convert a vec3 to vec4, or vice versa.
4720
static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4721
12
                                 Value *Src, unsigned NumElementsDst) {
4722
12
  static constexpr int Mask[] = {0, 1, 2, -1};
4723
12
  return Builder.CreateShuffleVector(Src,
4724
12
                                     llvm::makeArrayRef(Mask, NumElementsDst));
4725
12
}
4726
4727
// Create cast instructions for converting LLVM value \p Src to LLVM type \p
4728
// DstTy. \p Src has the same size as \p DstTy. Both are single value types
4729
// but could be scalar or vectors of different lengths, and either can be
4730
// pointer.
4731
// There are 4 cases:
4732
// 1. non-pointer -> non-pointer  : needs 1 bitcast
4733
// 2. pointer -> pointer          : needs 1 bitcast or addrspacecast
4734
// 3. pointer -> non-pointer
4735
//   a) pointer -> intptr_t       : needs 1 ptrtoint
4736
//   b) pointer -> non-intptr_t   : needs 1 ptrtoint then 1 bitcast
4737
// 4. non-pointer -> pointer
4738
//   a) intptr_t -> pointer       : needs 1 inttoptr
4739
//   b) non-intptr_t -> pointer   : needs 1 bitcast then 1 inttoptr
4740
// Note: for cases 3b and 4b two casts are required since LLVM casts do not
4741
// allow casting directly between pointer types and non-integer non-pointer
4742
// types.
4743
static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4744
                                           const llvm::DataLayout &DL,
4745
                                           Value *Src, llvm::Type *DstTy,
4746
19
                                           StringRef Name = "") {
4747
19
  auto SrcTy = Src->getType();
4748
4749
  // Case 1.
4750
19
  if (!SrcTy->isPointerTy() && 
!DstTy->isPointerTy()14
)
4751
12
    return Builder.CreateBitCast(Src, DstTy, Name);
4752
4753
  // Case 2.
4754
7
  if (SrcTy->isPointerTy() && 
DstTy->isPointerTy()5
)
4755
3
    return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4756
4757
  // Case 3.
4758
4
  if (SrcTy->isPointerTy() && 
!DstTy->isPointerTy()2
) {
4759
    // Case 3b.
4760
2
    if (!DstTy->isIntegerTy())
4761
1
      Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4762
    // Cases 3a and 3b.
4763
2
    return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4764
2
  }
4765
4766
  // Case 4b.
4767
2
  if (!SrcTy->isIntegerTy())
4768
1
    Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4769
  // Cases 4a and 4b.
4770
2
  return Builder.CreateIntToPtr(Src, DstTy, Name);
4771
4
}
4772
4773
20
Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4774
20
  Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
4775
20
  llvm::Type *DstTy = ConvertType(E->getType());
4776
4777
20
  llvm::Type *SrcTy = Src->getType();
4778
20
  unsigned NumElementsSrc =
4779
20
      isa<llvm::VectorType>(SrcTy)
4780
20
          ? 
cast<llvm::FixedVectorType>(SrcTy)->getNumElements()12
4781
20
          : 
08
;
4782
20
  unsigned NumElementsDst =
4783
20
      isa<llvm::VectorType>(DstTy)
4784
20
          ? 
cast<llvm::FixedVectorType>(DstTy)->getNumElements()10
4785
20
          : 
010
;
4786
4787
  // Going from vec3 to non-vec3 is a special case and requires a shuffle
4788
  // vector to get a vec4, then a bitcast if the target type is different.
4789
20
  if (NumElementsSrc == 3 && 
NumElementsDst != 38
) {
4790
7
    Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4791
7
    Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4792
7
                                       DstTy);
4793
4794
7
    Src->setName("astype");
4795
7
    return Src;
4796
7
  }
4797
4798
  // Going from non-vec3 to vec3 is a special case and requires a bitcast
4799
  // to vec4 if the original type is not vec4, then a shuffle vector to
4800
  // get a vec3.
4801
13
  if (NumElementsSrc != 3 && 
NumElementsDst == 312
) {
4802
5
    if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4803
4
      auto *Vec4Ty = llvm::FixedVectorType::get(
4804
4
          cast<llvm::VectorType>(DstTy)->getElementType(), 4);
4805
4
      Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4806
4
                                         Vec4Ty);
4807
4
    }
4808
4809
5
    Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4810
5
    Src->setName("astype");
4811
5
    return Src;
4812
5
  }
4813
4814
8
  return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4815
8
                                      Src, DstTy, "astype");
4816
13
}
4817
4818
1.04k
Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4819
1.04k
  return CGF.EmitAtomicExpr(E).getScalarVal();
4820
1.04k
}
4821
4822
//===----------------------------------------------------------------------===//
4823
//                         Entry Point into this File
4824
//===----------------------------------------------------------------------===//
4825
4826
/// Emit the computation of the specified expression of scalar type, ignoring
4827
/// the result.
4828
2.10M
Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4829
2.10M
  assert(E && hasScalarEvaluationKind(E->getType()) &&
4830
2.10M
         "Invalid scalar expression to emit");
4831
4832
0
  return ScalarExprEmitter(*this, IgnoreResultAssign)
4833
2.10M
      .Visit(const_cast<Expr *>(E));
4834
2.10M
}
4835
4836
/// Emit a conversion from the specified type to the specified destination type,
4837
/// both of which are LLVM scalar types.
4838
Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4839
                                             QualType DstTy,
4840
215k
                                             SourceLocation Loc) {
4841
215k
  assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4842
215k
         "Invalid scalar expression to emit");
4843
0
  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4844
215k
}
4845
4846
/// Emit a conversion from the specified complex type to the specified
4847
/// destination type, where the destination type is an LLVM scalar type.
4848
Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4849
                                                      QualType SrcTy,
4850
                                                      QualType DstTy,
4851
9
                                                      SourceLocation Loc) {
4852
9
  assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4853
9
         "Invalid complex -> scalar conversion");
4854
0
  return ScalarExprEmitter(*this)
4855
9
      .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4856
9
}
4857
4858
4859
llvm::Value *CodeGenFunction::
4860
EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4861
16.5k
                        bool isInc, bool isPre) {
4862
16.5k
  return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4863
16.5k
}
4864
4865
24
LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4866
  // object->isa or (*object).isa
4867
  // Generate code as for: *(Class*)object
4868
4869
24
  Expr *BaseExpr = E->getBase();
4870
24
  Address Addr = Address::invalid();
4871
24
  if (BaseExpr->isPRValue()) {
4872
16
    Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4873
16
  } else {
4874
8
    Addr = EmitLValue(BaseExpr).getAddress(*this);
4875
8
  }
4876
4877
  // Cast the address to Class*.
4878
24
  Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4879
24
  return MakeAddrLValue(Addr, E->getType());
4880
24
}
4881
4882
4883
LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4884
19.4k
                                            const CompoundAssignOperator *E) {
4885
19.4k
  ScalarExprEmitter Scalar(*this);
4886
19.4k
  Value *Result = nullptr;
4887
19.4k
  switch (E->getOpcode()) {
4888
0
#define COMPOUND_OP(Op)                                                       \
4889
19.4k
    case BO_##Op##Assign:                                                     \
4890
19.4k
      return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4891
19.4k
                                             Result)
4892
98
  COMPOUND_OP
(Mul)0
;
4893
150
  COMPOUND_OP
(Div)0
;
4894
7
  COMPOUND_OP
(Rem)0
;
4895
18.2k
  COMPOUND_OP
(Add)0
;
4896
633
  COMPOUND_OP
(Sub)0
;
4897
33
  COMPOUND_OP
(Shl)0
;
4898
3
  COMPOUND_OP
(Shr)0
;
4899
116
  COMPOUND_OP
(And)0
;
4900
26
  COMPOUND_OP
(Xor)0
;
4901
155
  COMPOUND_OP
(Or)0
;
4902
0
#undef COMPOUND_OP
4903
4904
0
  case BO_PtrMemD:
4905
0
  case BO_PtrMemI:
4906
0
  case BO_Mul:
4907
0
  case BO_Div:
4908
0
  case BO_Rem:
4909
0
  case BO_Add:
4910
0
  case BO_Sub:
4911
0
  case BO_Shl:
4912
0
  case BO_Shr:
4913
0
  case BO_LT:
4914
0
  case BO_GT:
4915
0
  case BO_LE:
4916
0
  case BO_GE:
4917
0
  case BO_EQ:
4918
0
  case BO_NE:
4919
0
  case BO_Cmp:
4920
0
  case BO_And:
4921
0
  case BO_Xor:
4922
0
  case BO_Or:
4923
0
  case BO_LAnd:
4924
0
  case BO_LOr:
4925
0
  case BO_Assign:
4926
0
  case BO_Comma:
4927
0
    llvm_unreachable("Not valid compound assignment operators");
4928
19.4k
  }
4929
4930
0
  llvm_unreachable("Unhandled compound assignment operator");
4931
0
}
4932
4933
struct GEPOffsetAndOverflow {
4934
  // The total (signed) byte offset for the GEP.
4935
  llvm::Value *TotalOffset;
4936
  // The offset overflow flag - true if the total offset overflows.
4937
  llvm::Value *OffsetOverflows;
4938
};
4939
4940
/// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
4941
/// and compute the total offset it applies from it's base pointer BasePtr.
4942
/// Returns offset in bytes and a boolean flag whether an overflow happened
4943
/// during evaluation.
4944
static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4945
                                                 llvm::LLVMContext &VMContext,
4946
                                                 CodeGenModule &CGM,
4947
205
                                                 CGBuilderTy &Builder) {
4948
205
  const auto &DL = CGM.getDataLayout();
4949
4950
  // The total (signed) byte offset for the GEP.
4951
205
  llvm::Value *TotalOffset = nullptr;
4952
4953
  // Was the GEP already reduced to a constant?
4954
205
  if (isa<llvm::Constant>(GEPVal)) {
4955
    // Compute the offset by casting both pointers to integers and subtracting:
4956
    // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4957
54
    Value *BasePtr_int =
4958
54
        Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4959
54
    Value *GEPVal_int =
4960
54
        Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4961
54
    TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4962
54
    return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4963
54
  }
4964
4965
151
  auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4966
151
  assert(G