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