Coverage Report

Created: 2021-01-23 06:44

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