Coverage Report

Created: 2022-07-16 07:03

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