Coverage Report

Created: 2020-09-22 08:39

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