blob: 6b33d807a7bd23dfc05fae46e5a91a8c1475bba4 [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner2da04b32007-08-24 05:35:26 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Leonard Chan99bda372018-10-15 16:07:02 +000014#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Fariborz Jahanian07ca7272009-10-10 20:07:56 +000016#include "CGObjCRuntime.h"
Alexey Bataeva58da1a2019-12-27 09:44:43 -050017#include "CGOpenMPRuntime.h"
Leonard Chan99bda372018-10-15 16:07:02 +000018#include "CodeGenFunction.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000019#include "CodeGenModule.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000020#include "ConstantEmitter.h"
Alexey Bataev00396512015-07-02 03:40:19 +000021#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080023#include "clang/AST/Attr.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000024#include "clang/AST/DeclObjC.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000025#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000026#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000027#include "clang/AST/StmtVisitor.h"
Richard Trieu63688182018-12-11 03:18:39 +000028#include "clang/Basic/CodeGenOptions.h"
Leonard Chan99bda372018-10-15 16:07:02 +000029#include "clang/Basic/FixedPoint.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000030#include "clang/Basic/TargetInfo.h"
Vedant Kumar82ee16b2017-02-25 00:43:36 +000031#include "llvm/ADT/Optional.h"
Chandler Carruth735e6d82014-03-04 11:46:22 +000032#include "llvm/IR/CFG.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/Function.h"
Vedant Kumara125eb52017-06-01 19:22:18 +000036#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000037#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Intrinsics.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080039#include "llvm/IR/IntrinsicsPowerPC.h"
Florian Hahn6f6e91d2020-05-29 20:42:22 +010040#include "llvm/IR/MatrixBuilder.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000041#include "llvm/IR/Module.h"
Chris Lattner1800c182008-01-03 07:05:49 +000042#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000043
Chris Lattner2da04b32007-08-24 05:35:26 +000044using namespace clang;
45using namespace CodeGen;
46using llvm::Value;
47
48//===----------------------------------------------------------------------===//
49// Scalar Expression Emitter
50//===----------------------------------------------------------------------===//
51
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000052namespace {
Vedant Kumara125eb52017-06-01 19:22:18 +000053
54/// Determine whether the given binary operation may overflow.
55/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
56/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
57/// the returned overflow check is precise. The returned value is 'true' for
58/// all other opcodes, to be conservative.
59bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
60 BinaryOperator::Opcode Opcode, bool Signed,
61 llvm::APInt &Result) {
62 // Assume overflow is possible, unless we can prove otherwise.
63 bool Overflow = true;
64 const auto &LHSAP = LHS->getValue();
65 const auto &RHSAP = RHS->getValue();
66 if (Opcode == BO_Add) {
67 if (Signed)
68 Result = LHSAP.sadd_ov(RHSAP, Overflow);
69 else
70 Result = LHSAP.uadd_ov(RHSAP, Overflow);
71 } else if (Opcode == BO_Sub) {
72 if (Signed)
73 Result = LHSAP.ssub_ov(RHSAP, Overflow);
74 else
75 Result = LHSAP.usub_ov(RHSAP, Overflow);
76 } else if (Opcode == BO_Mul) {
77 if (Signed)
78 Result = LHSAP.smul_ov(RHSAP, Overflow);
79 else
80 Result = LHSAP.umul_ov(RHSAP, Overflow);
81 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
82 if (Signed && !RHS->isZero())
83 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
84 else
85 return false;
86 }
87 return Overflow;
88}
89
Chris Lattner2da04b32007-08-24 05:35:26 +000090struct BinOpInfo {
91 Value *LHS;
92 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000093 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-06-26 21:48:21 +000094 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Adam Nemet484aa452017-03-27 19:17:25 +000095 FPOptions FPFeatures;
Chris Lattner0bf27622010-06-26 21:48:21 +000096 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Vedant Kumard9191152017-05-02 23:46:56 +000097
98 /// Check if the binop can result in integer overflow.
99 bool mayHaveIntegerOverflow() const {
100 // Without constant input, we can't rule out overflow.
Vedant Kumara125eb52017-06-01 19:22:18 +0000101 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
102 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
Vedant Kumard9191152017-05-02 23:46:56 +0000103 if (!LHSCI || !RHSCI)
104 return true;
105
Vedant Kumara125eb52017-06-01 19:22:18 +0000106 llvm::APInt Result;
107 return ::mayHaveIntegerOverflow(
108 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
Vedant Kumard9191152017-05-02 23:46:56 +0000109 }
110
111 /// Check if the binop computes a division or a remainder.
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000112 bool isDivremOp() const {
Vedant Kumard9191152017-05-02 23:46:56 +0000113 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
114 Opcode == BO_RemAssign;
115 }
116
117 /// Check if the binop can result in an integer division by zero.
118 bool mayHaveIntegerDivisionByZero() const {
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000119 if (isDivremOp())
Vedant Kumard9191152017-05-02 23:46:56 +0000120 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
121 return CI->isZero();
122 return true;
123 }
124
125 /// Check if the binop can result in a float division by zero.
126 bool mayHaveFloatDivisionByZero() const {
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000127 if (isDivremOp())
Vedant Kumard9191152017-05-02 23:46:56 +0000128 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
129 return CFP->isZero();
130 return true;
131 }
Leonard Chan2044ac82019-01-16 18:13:59 +0000132
Bevin Hansson39baaab2020-01-08 11:12:55 +0100133 /// Check if at least one operand is a fixed point type. In such cases, this
134 /// operation did not follow usual arithmetic conversion and both operands
135 /// might not be of the same type.
136 bool isFixedPointOp() const {
Leonard Chance1d4f12019-02-21 20:50:09 +0000137 // We cannot simply check the result type since comparison operations return
138 // an int.
139 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
140 QualType LHSType = BinOp->getLHS()->getType();
141 QualType RHSType = BinOp->getRHS()->getType();
142 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
143 }
Bevin Hansson39baaab2020-01-08 11:12:55 +0100144 if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
145 return UnOp->getSubExpr()->getType()->isFixedPointType();
Leonard Chance1d4f12019-02-21 20:50:09 +0000146 return false;
Leonard Chan2044ac82019-01-16 18:13:59 +0000147 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000148};
149
John McCalle84af4e2010-11-13 01:35:44 +0000150static bool MustVisitNullValue(const Expr *E) {
151 // If a null pointer expression's type is the C++0x nullptr_t, then
152 // it's not necessarily a simple constant and it must be evaluated
153 // for its potential side effects.
154 return E->getType()->isNullPtrType();
155}
156
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000157/// If \p E is a widened promoted integer, get its base (unpromoted) type.
158static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
159 const Expr *E) {
160 const Expr *Base = E->IgnoreImpCasts();
161 if (E == Base)
162 return llvm::None;
163
164 QualType BaseTy = Base->getType();
165 if (!BaseTy->isPromotableIntegerType() ||
166 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
167 return llvm::None;
168
169 return BaseTy;
170}
171
172/// Check if \p E is a widened promoted integer.
173static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
174 return getUnwidenedIntegerType(Ctx, E).hasValue();
175}
176
177/// Check if we can skip the overflow check for \p Op.
178static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
Vedant Kumar66c00cc2017-02-25 06:47:00 +0000179 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
180 "Expected a unary or binary operator");
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000181
Vedant Kumard9191152017-05-02 23:46:56 +0000182 // If the binop has constant inputs and we can prove there is no overflow,
183 // we can elide the overflow check.
184 if (!Op.mayHaveIntegerOverflow())
185 return true;
Malcolm Parsonsfab36802018-04-16 08:31:08 +0000186
187 // If a unary op has a widened operand, the op cannot overflow.
188 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
189 return !UO->canOverflow();
190
191 // We usually don't need overflow checks for binops with widened operands.
192 // Multiplication with promoted unsigned operands is a special case.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000193 const auto *BO = cast<BinaryOperator>(Op.E);
194 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
195 if (!OptionalLHSTy)
196 return false;
197
198 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
199 if (!OptionalRHSTy)
200 return false;
201
202 QualType LHSTy = *OptionalLHSTy;
203 QualType RHSTy = *OptionalRHSTy;
204
Vedant Kumard9191152017-05-02 23:46:56 +0000205 // This is the simple case: binops without unsigned multiplication, and with
206 // widened operands. No overflow check is needed here.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000207 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
208 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
209 return true;
210
Vedant Kumard9191152017-05-02 23:46:56 +0000211 // For unsigned multiplication the overflow check can be elided if either one
212 // of the unpromoted types are less than half the size of the promoted type.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000213 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
214 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
215 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
216}
217
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000218class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +0000219 : public StmtVisitor<ScalarExprEmitter, Value*> {
220 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +0000221 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +0000222 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +0000223 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +0000224public:
225
Mike Stumpdf0fe272009-05-29 15:46:01 +0000226 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +0000227 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +0000228 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +0000229 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000230
Chris Lattner2da04b32007-08-24 05:35:26 +0000231 //===--------------------------------------------------------------------===//
232 // Utilities
233 //===--------------------------------------------------------------------===//
234
Mike Stumpdf0fe272009-05-29 15:46:01 +0000235 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +0000236 bool I = IgnoreResultAssign;
237 IgnoreResultAssign = false;
238 return I;
239 }
Mike Stumpdf0fe272009-05-29 15:46:01 +0000240
Chris Lattner2192fe52011-07-18 04:24:23 +0000241 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +0000242 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith4d1458e2012-09-08 02:08:36 +0000243 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
244 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith69d0d262012-08-24 00:54:33 +0000245 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000246
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000247 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000248 const BinOpInfo &Info);
Richard Smithe30752c2012-10-09 19:52:38 +0000249
Nick Lewycky2d84e842013-10-02 02:29:49 +0000250 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
251 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000252 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000253
Hal Finkel64567a82014-10-04 15:26:49 +0000254 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
255 const AlignValueAttr *AVAttr = nullptr;
256 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
257 const ValueDecl *VD = DRE->getDecl();
258
259 if (VD->getType()->isReferenceType()) {
260 if (const auto *TTy =
261 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
262 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
263 } else {
264 // Assumptions for function parameters are emitted at the start of the
Roman Lebedevbd1c0872019-01-15 09:44:25 +0000265 // function, so there is no need to repeat that here,
266 // unless the alignment-assumption sanitizer is enabled,
267 // then we prefer the assumption over alignment attribute
268 // on IR function param.
269 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
Hal Finkel64567a82014-10-04 15:26:49 +0000270 return;
271
272 AVAttr = VD->getAttr<AlignValueAttr>();
273 }
274 }
275
276 if (!AVAttr)
277 if (const auto *TTy =
278 dyn_cast<TypedefType>(E->getType()))
279 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
280
281 if (!AVAttr)
282 return;
283
284 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
285 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
Fangrui Song1d49eb02020-02-13 16:36:27 -0800286 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
Hal Finkel64567a82014-10-04 15:26:49 +0000287 }
288
Chris Lattner2da04b32007-08-24 05:35:26 +0000289 /// EmitLoadOfLValue - Given an expression with complex type that represents a
290 /// value l-value, this method emits the address of the l-value, then loads
291 /// and returns the result.
292 Value *EmitLoadOfLValue(const Expr *E) {
Hal Finkel64567a82014-10-04 15:26:49 +0000293 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
294 E->getExprLoc());
295
296 EmitLValueAlignmentAssumption(E, V);
297 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000298 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000299
Chris Lattnere0044382007-08-26 16:42:57 +0000300 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000301 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000302 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000303
Richard Smith9e52c432019-07-06 21:05:52 +0000304 /// Emit a check that a conversion from a floating-point type does not
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000305 /// overflow.
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000306 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000307 Value *Src, QualType SrcType, QualType DstType,
308 llvm::Type *DstTy, SourceLocation Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000309
Roman Lebedevb69ba222018-07-30 18:58:30 +0000310 /// Known implicit conversion check kinds.
311 /// Keep in sync with the enum of the same name in ubsan_handlers.h
312 enum ImplicitConversionCheckKind : unsigned char {
Roman Lebedevdd403572018-10-11 09:09:50 +0000313 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
314 ICCK_UnsignedIntegerTruncation = 1,
315 ICCK_SignedIntegerTruncation = 2,
Roman Lebedev62debd802018-10-30 21:58:56 +0000316 ICCK_IntegerSignChange = 3,
317 ICCK_SignedIntegerTruncationOrSignChange = 4,
Roman Lebedevb69ba222018-07-30 18:58:30 +0000318 };
319
320 /// Emit a check that an [implicit] truncation of an integer does not
321 /// discard any bits. It is not UB, so we use the value after truncation.
322 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
323 QualType DstType, SourceLocation Loc);
324
Roman Lebedev62debd802018-10-30 21:58:56 +0000325 /// Emit a check that an [implicit] conversion of an integer does not change
326 /// the sign of the value. It is not UB, so we use the value after conversion.
327 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
328 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
329 QualType DstType, SourceLocation Loc);
330
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000331 /// Emit a conversion from the specified type to the specified destination
332 /// type, both of which are LLVM scalar types.
Roman Lebedevb69ba222018-07-30 18:58:30 +0000333 struct ScalarConversionOpts {
334 bool TreatBooleanAsSigned;
335 bool EmitImplicitIntegerTruncationChecks;
Roman Lebedev62debd802018-10-30 21:58:56 +0000336 bool EmitImplicitIntegerSignChangeChecks;
Chris Lattner42e6b812007-08-26 16:34:22 +0000337
Roman Lebedevb69ba222018-07-30 18:58:30 +0000338 ScalarConversionOpts()
339 : TreatBooleanAsSigned(false),
Roman Lebedev62debd802018-10-30 21:58:56 +0000340 EmitImplicitIntegerTruncationChecks(false),
341 EmitImplicitIntegerSignChangeChecks(false) {}
Roman Lebedevd677c3f2018-11-19 19:56:43 +0000342
343 ScalarConversionOpts(clang::SanitizerSet SanOpts)
344 : TreatBooleanAsSigned(false),
345 EmitImplicitIntegerTruncationChecks(
346 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
347 EmitImplicitIntegerSignChangeChecks(
348 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
Roman Lebedevb69ba222018-07-30 18:58:30 +0000349 };
350 Value *
351 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
352 SourceLocation Loc,
353 ScalarConversionOpts Opts = ScalarConversionOpts());
Anastasia Stulovab02e7832015-10-05 11:27:41 +0000354
Leonard Chan8f7caae2019-03-06 00:28:43 +0000355 /// Convert between either a fixed point and other fixed point or fixed point
356 /// and an integer.
Leonard Chan99bda372018-10-15 16:07:02 +0000357 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
358 SourceLocation Loc);
Leonard Chan2044ac82019-01-16 18:13:59 +0000359 Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
360 FixedPointSemantics &DstFixedSema,
Leonard Chan8f7caae2019-03-06 00:28:43 +0000361 SourceLocation Loc,
362 bool DstIsInteger = false);
Leonard Chan99bda372018-10-15 16:07:02 +0000363
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000364 /// Emit a conversion from the specified complex type to the specified
365 /// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000366 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000367 QualType SrcTy, QualType DstTy,
368 SourceLocation Loc);
Mike Stumpab3afd82009-02-12 18:29:15 +0000369
Anders Carlsson5b944432010-05-22 17:45:10 +0000370 /// EmitNullValue - Emit a value that corresponds to null for the given type.
371 Value *EmitNullValue(QualType Ty);
372
John McCall8cb679e2010-11-15 09:13:47 +0000373 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
374 Value *EmitFloatToBoolConversion(Value *V) {
375 // Compare against 0.0 for fp scalars.
376 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
377 return Builder.CreateFCmpUNE(V, Zero, "tobool");
378 }
379
380 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
Yaxun Liu402804b2016-12-15 08:09:08 +0000381 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
382 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
383
John McCall8cb679e2010-11-15 09:13:47 +0000384 return Builder.CreateICmpNE(V, Zero, "tobool");
385 }
386
387 Value *EmitIntToBoolConversion(Value *V) {
388 // Because of the type rules of C, we often end up computing a
389 // logical value, then zero extending it to int, then wanting it
390 // as a logical value again. Optimize this common case.
391 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
392 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
393 Value *Result = ZI->getOperand(0);
394 // If there aren't any more uses, zap the instruction to save space.
395 // Note that there can be more uses, for example if this
396 // is the result of an assignment.
397 if (ZI->use_empty())
398 ZI->eraseFromParent();
399 return Result;
400 }
401 }
402
Chris Lattner2531eb42011-04-19 22:55:03 +0000403 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000404 }
405
Chris Lattner2da04b32007-08-24 05:35:26 +0000406 //===--------------------------------------------------------------------===//
407 // Visitor Methods
408 //===--------------------------------------------------------------------===//
409
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000410 Value *Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000411 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000412 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
413 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000414
Chris Lattner2da04b32007-08-24 05:35:26 +0000415 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000416 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000417 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000418 }
419 Value *VisitExpr(Expr *S);
Craig Toppera97d7e72013-07-26 06:16:11 +0000420
Bill Wendling8003edc2018-11-09 00:41:36 +0000421 Value *VisitConstantExpr(ConstantExpr *E) {
422 return Visit(E->getSubExpr());
423 }
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000424 Value *VisitParenExpr(ParenExpr *PE) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000425 return Visit(PE->getSubExpr());
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000426 }
John McCall7c454bb2011-07-15 05:09:51 +0000427 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000428 return Visit(E->getReplacement());
John McCall7c454bb2011-07-15 05:09:51 +0000429 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000430 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
431 return Visit(GE->getResultExpr());
432 }
Gor Nishanov5eb58582017-03-26 02:18:05 +0000433 Value *VisitCoawaitExpr(CoawaitExpr *S) {
434 return CGF.EmitCoawaitExpr(*S).getScalarVal();
435 }
436 Value *VisitCoyieldExpr(CoyieldExpr *S) {
437 return CGF.EmitCoyieldExpr(*S).getScalarVal();
438 }
439 Value *VisitUnaryCoawait(const UnaryOperator *E) {
440 return Visit(E->getSubExpr());
441 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000442
443 // Leaves.
444 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000445 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000446 }
Leonard Chandb01c3a2018-06-20 17:19:40 +0000447 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
448 return Builder.getInt(E->getValue());
449 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000450 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000451 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000452 }
453 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000454 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000455 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000456 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
457 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
458 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000459 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000460 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000461 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000462 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000463 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000464 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000465 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000466 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000467 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000468 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000469 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000470 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000471 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
472 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000473 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000474
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000475 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000476 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000477 }
John McCall1bf58462011-02-16 08:02:54 +0000478
John McCallfe96e0b2011-11-06 09:01:30 +0000479 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
480 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
481 }
482
John McCall1bf58462011-02-16 08:02:54 +0000483 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000484 if (E->isGLValue())
Akira Hatanaka797afe32018-03-20 01:47:58 +0000485 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
486 E->getExprLoc());
John McCall1bf58462011-02-16 08:02:54 +0000487
488 // Otherwise, assume the mapping is the scalar directly.
Akira Hatanaka797afe32018-03-20 01:47:58 +0000489 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000490 }
John McCall71335052012-03-10 03:05:10 +0000491
Chris Lattner2da04b32007-08-24 05:35:26 +0000492 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000493 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +0000494 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +0000495 return CGF.emitScalarConstant(Constant, E);
John McCall113bee02012-03-10 09:33:50 +0000496 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000497 }
498
Mike Stump4a3999f2009-09-09 13:00:44 +0000499 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
500 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000501 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000502 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
503 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000504 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000505 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000506 return EmitLoadOfLValue(E);
507 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000508 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000509 if (E->getMethodDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +0000510 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanianff989032011-03-02 20:09:49 +0000511 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000512 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000513 }
514
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000515 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000516 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000517 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000518 return V;
519 }
520
Erik Pilkington9c42a8d2017-02-23 21:08:08 +0000521 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
522 VersionTuple Version = E->getVersion();
523
524 // If we're checking for a platform older than our minimum deployment
525 // target, we can fold the check away.
526 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
527 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
528
529 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
530 llvm::Value *Args[] = {
531 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
532 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
533 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
534 };
535
536 return CGF.EmitBuiltinAvailable(Args);
537 }
538
Chris Lattner2da04b32007-08-24 05:35:26 +0000539 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Florian Hahn8f3f88d2020-06-01 19:42:03 +0100540 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000541 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkelc4d7c822013-09-18 03:29:45 +0000542 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000543 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000544 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000545 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Akira Hatanaka40568fe2020-03-10 14:06:25 -0700546 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
547 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
548 // literals aren't l-values in C++. We do so simply because that's the
549 // cleanest way to handle compound literals in C++.
550 // See the discussion here: https://reviews.llvm.org/D64464
Chris Lattner084bc322008-10-26 23:53:12 +0000551 return EmitLoadOfLValue(E);
552 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000553
Nate Begeman19351632009-10-18 20:10:40 +0000554 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000555
Richard Smith410306b2016-12-12 02:53:20 +0000556 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
557 assert(CGF.getArrayInitIndex() &&
558 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
559 return CGF.getArrayInitIndex();
560 }
561
Douglas Gregor0202cb42009-01-29 17:44:32 +0000562 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000563 return EmitNullValue(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000564 }
John McCall23c29fe2011-06-24 21:55:10 +0000565 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000566 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
John McCall23c29fe2011-06-24 21:55:10 +0000567 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000568 }
John McCall23c29fe2011-06-24 21:55:10 +0000569 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000570
571 Value *VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000572 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000573 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000574
Hal Finkel64567a82014-10-04 15:26:49 +0000575 Value *V = CGF.EmitCallExpr(E).getScalarVal();
576
577 EmitLValueAlignmentAssumption(E, V);
578 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000579 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000580
Chris Lattner04a913b2007-08-31 22:09:40 +0000581 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000582
Chris Lattner2da04b32007-08-24 05:35:26 +0000583 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000584 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000585 LValue LV = EmitLValue(E->getSubExpr());
586 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000587 }
588 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000589 LValue LV = EmitLValue(E->getSubExpr());
590 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000591 }
592 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000593 LValue LV = EmitLValue(E->getSubExpr());
594 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000595 }
596 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000597 LValue LV = EmitLValue(E->getSubExpr());
598 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000599 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000600
Alexey Samsonovf6246502015-04-23 01:50:45 +0000601 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
602 llvm::Value *InVal,
603 bool IsInc);
Anton Yartsev85129b82011-02-07 02:17:30 +0000604
Chris Lattner05dc78c2010-06-26 22:09:34 +0000605 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
606 bool isInc, bool isPre);
607
Craig Toppera97d7e72013-07-26 06:16:11 +0000608
Chris Lattner2da04b32007-08-24 05:35:26 +0000609 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000610 if (isa<MemberPointerType>(E->getType())) // never sugared
611 return CGF.CGM.getMemberPointerConstant(E);
612
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800613 return EmitLValue(E->getSubExpr()).getPointer(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +0000614 }
John McCall59482722010-12-04 12:43:24 +0000615 Value *VisitUnaryDeref(const UnaryOperator *E) {
616 if (E->getType()->isVoidType())
617 return Visit(E->getSubExpr()); // the actual value should be unused
618 return EmitLoadOfLValue(E);
619 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000620 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000621 // This differs from gcc, though, most likely due to a bug in gcc.
622 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000623 return Visit(E->getSubExpr());
624 }
625 Value *VisitUnaryMinus (const UnaryOperator *E);
626 Value *VisitUnaryNot (const UnaryOperator *E);
627 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000628 Value *VisitUnaryReal (const UnaryOperator *E);
629 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000630 Value *VisitUnaryExtension(const UnaryOperator *E) {
631 return Visit(E->getSubExpr());
632 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000633
Anders Carlssona5d077d2009-04-14 16:58:56 +0000634 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000635 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000636 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000637 }
Eric Fiselier708afb52019-05-16 21:04:15 +0000638 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
639 auto &Ctx = CGF.getContext();
640 APValue Evaluated =
641 SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
Johannes Altmanninger1ac700c2019-11-15 02:12:58 +0100642 return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
643 SLE->getType());
Eric Fiselier708afb52019-05-16 21:04:15 +0000644 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000645
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000646 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000647 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000648 return Visit(DAE->getExpr());
649 }
Richard Smith852c9db2013-04-20 22:23:05 +0000650 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000651 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
Richard Smith852c9db2013-04-20 22:23:05 +0000652 return Visit(DIE->getExpr());
653 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000654 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
655 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000656 }
657
Reid Kleckner092d0652017-03-06 22:18:34 +0000658 Value *VisitExprWithCleanups(ExprWithCleanups *E);
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000659 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
660 return CGF.EmitCXXNewExpr(E);
661 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000662 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
663 CGF.EmitCXXDeleteExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000664 return nullptr;
Anders Carlsson81f0df92009-08-16 21:13:42 +0000665 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000666
Alp Tokercbb90342013-12-13 20:49:58 +0000667 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000668 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000669 }
670
Saar Raz5d98ba62019-10-15 15:24:26 +0000671 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
672 return Builder.getInt1(E->isSatisfied());
673 }
674
Saar Raza0f50d72020-01-18 09:11:43 +0200675 Value *VisitRequiresExpr(const RequiresExpr *E) {
676 return Builder.getInt1(E->isSatisfied());
677 }
678
John Wiegley6242b6a2011-04-28 00:16:57 +0000679 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
680 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
681 }
682
John Wiegleyf9f65842011-04-25 06:54:41 +0000683 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
684 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
685 }
686
Douglas Gregorad8a3362009-09-04 17:36:40 +0000687 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
688 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000689 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000690 // operator (), and the result of such a call has type void. The only
691 // effect is the evaluation of the postfix-expression before the dot or
692 // arrow.
693 CGF.EmitScalarExpr(E->getBase());
Craig Topper8a13c412014-05-21 05:09:00 +0000694 return nullptr;
Douglas Gregorad8a3362009-09-04 17:36:40 +0000695 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000696
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000697 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000698 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000699 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000700
701 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
702 CGF.EmitCXXThrowExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000703 return nullptr;
Anders Carlsson4b08db72009-10-30 01:42:31 +0000704 }
705
Sebastian Redlb67655f2010-09-10 21:04:00 +0000706 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000707 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000708 }
709
Chris Lattner2da04b32007-08-24 05:35:26 +0000710 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000711 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000712 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000713 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000714 case LangOptions::SOB_Defined:
715 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000716 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000717 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +0000718 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000719 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +0000720 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000721 if (CanElideOverflowCheck(CGF.getContext(), Ops))
722 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner51924e512010-06-26 21:25:03 +0000723 return EmitOverflowCheckedBinOp(Ops);
724 }
725 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000726
Florian Hahn4affc442020-06-07 11:11:27 +0100727 if (Ops.Ty->isConstantMatrixType()) {
728 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
729 // We need to check the types of the operands of the operator to get the
730 // correct matrix dimensions.
731 auto *BO = cast<BinaryOperator>(Ops.E);
732 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
733 BO->getLHS()->getType().getCanonicalType());
734 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
735 BO->getRHS()->getType().getCanonicalType());
736 if (LHSMatTy && RHSMatTy)
737 return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
738 LHSMatTy->getNumColumns(),
739 RHSMatTy->getNumColumns());
740 return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
741 }
742
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000743 if (Ops.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000744 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
745 !CanElideOverflowCheck(CGF.getContext(), Ops))
Will Dietz1897cb32012-11-27 15:01:55 +0000746 return EmitOverflowCheckedBinOp(Ops);
747
Adam Nemet370d0872017-04-04 21:18:30 +0000748 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
Melanie Blowerf5360d42020-05-01 10:32:06 -0700749 // Preserve the old values
John McCall7fac1ac2020-06-11 18:09:36 -0400750 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
John McCall8a8d7032020-06-01 21:02:02 -0400751 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Adam Nemet370d0872017-04-04 21:18:30 +0000752 }
Bevin Hansson39baaab2020-01-08 11:12:55 +0100753 if (Ops.isFixedPointOp())
Bevin Hansson0b9922e2019-11-19 13:15:06 +0100754 return EmitFixedPointBinOp(Ops);
Chris Lattner2da04b32007-08-24 05:35:26 +0000755 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
756 }
Mike Stump0c61b732009-04-01 20:28:16 +0000757 /// Create a binary op that checks for overflow.
758 /// Currently only supports +, - and *.
759 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith4d1458e2012-09-08 02:08:36 +0000760
Chris Lattner8ee6a412010-09-11 21:47:09 +0000761 // Check for undefined division and modulus behaviors.
Craig Toppera97d7e72013-07-26 06:16:11 +0000762 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner8ee6a412010-09-11 21:47:09 +0000763 llvm::Value *Zero,bool isDiv);
David Tweed042e0882013-01-07 16:43:27 +0000764 // Common helper for getting how wide LHS of shift is.
765 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Erich Keane5f0903e2020-04-17 10:44:19 -0700766
767 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
768 // non powers of two.
769 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
770
Chris Lattner2da04b32007-08-24 05:35:26 +0000771 Value *EmitDiv(const BinOpInfo &Ops);
772 Value *EmitRem(const BinOpInfo &Ops);
773 Value *EmitAdd(const BinOpInfo &Ops);
774 Value *EmitSub(const BinOpInfo &Ops);
775 Value *EmitShl(const BinOpInfo &Ops);
776 Value *EmitShr(const BinOpInfo &Ops);
777 Value *EmitAnd(const BinOpInfo &Ops) {
778 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
779 }
780 Value *EmitXor(const BinOpInfo &Ops) {
781 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
782 }
783 Value *EmitOr (const BinOpInfo &Ops) {
784 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
785 }
786
Leonard Chan2044ac82019-01-16 18:13:59 +0000787 // Helper functions for fixed point binary operations.
Leonard Chan837da5d2019-01-16 19:53:50 +0000788 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
Leonard Chan2044ac82019-01-16 18:13:59 +0000789
Chris Lattner3d966d62007-08-24 21:00:35 +0000790 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000791 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
792 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000793 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000794
Chris Lattnerb6334692007-08-26 21:41:21 +0000795 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000796 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
797
798 // Binary operators and binary compound assignment operators.
799#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000800 Value *VisitBin ## OP(const BinaryOperator *E) { \
801 return Emit ## OP(EmitBinOps(E)); \
802 } \
803 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
804 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000805 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000806 HANDLEBINOP(Mul)
807 HANDLEBINOP(Div)
808 HANDLEBINOP(Rem)
809 HANDLEBINOP(Add)
810 HANDLEBINOP(Sub)
811 HANDLEBINOP(Shl)
812 HANDLEBINOP(Shr)
813 HANDLEBINOP(And)
814 HANDLEBINOP(Xor)
815 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000816#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000817
Chris Lattner2da04b32007-08-24 05:35:26 +0000818 // Comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +0000819 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
820 llvm::CmpInst::Predicate SICmpOpc,
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +0100821 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
822#define VISITCOMP(CODE, UI, SI, FP, SIG) \
Chris Lattner2da04b32007-08-24 05:35:26 +0000823 Value *VisitBin##CODE(const BinaryOperator *E) { \
824 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +0100825 llvm::FCmpInst::FP, SIG); }
826 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
827 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
828 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
829 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
830 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
831 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
Chris Lattner2da04b32007-08-24 05:35:26 +0000832#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000833
Chris Lattner2da04b32007-08-24 05:35:26 +0000834 Value *VisitBinAssign (const BinaryOperator *E);
835
836 Value *VisitBinLAnd (const BinaryOperator *E);
837 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000838 Value *VisitBinComma (const BinaryOperator *E);
839
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000840 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
841 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
842
Richard Smith778dc0f2019-10-19 00:04:38 +0000843 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
844 return Visit(E->getSemanticForm());
845 }
846
Chris Lattner2da04b32007-08-24 05:35:26 +0000847 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000848 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000849 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000850 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000851 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000852 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
853 return CGF.EmitObjCStringLiteral(E);
854 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000855 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
856 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000857 }
858 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
859 return CGF.EmitObjCArrayLiteral(E);
860 }
861 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
862 return CGF.EmitObjCDictionaryLiteral(E);
863 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000864 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000865 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000866};
867} // end anonymous namespace.
868
869//===----------------------------------------------------------------------===//
870// Utilities
871//===----------------------------------------------------------------------===//
872
Chris Lattnere0044382007-08-26 16:42:57 +0000873/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000874/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000875Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000876 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000877
John McCall8cb679e2010-11-15 09:13:47 +0000878 if (SrcType->isRealFloatingType())
879 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000880
John McCall7a9aac22010-08-23 01:21:21 +0000881 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
882 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000883
Daniel Dunbaref957f32008-08-25 10:38:11 +0000884 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000885 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000886
John McCall8cb679e2010-11-15 09:13:47 +0000887 if (isa<llvm::IntegerType>(Src->getType()))
888 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000889
John McCall8cb679e2010-11-15 09:13:47 +0000890 assert(isa<llvm::PointerType>(Src->getType()));
Yaxun Liu402804b2016-12-15 08:09:08 +0000891 return EmitPointerToBoolConversion(Src, SrcType);
Chris Lattnere0044382007-08-26 16:42:57 +0000892}
893
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000894void ScalarExprEmitter::EmitFloatConversionCheck(
895 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
896 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
Richard Smith9e52c432019-07-06 21:05:52 +0000897 assert(SrcType->isFloatingType() && "not a conversion from floating point");
898 if (!isa<llvm::IntegerType>(DstTy))
899 return;
900
Alexey Samsonov24cad992014-07-17 18:46:27 +0000901 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000902 using llvm::APFloat;
903 using llvm::APSInt;
904
Craig Topper8a13c412014-05-21 05:09:00 +0000905 llvm::Value *Check = nullptr;
Richard Smith9e52c432019-07-06 21:05:52 +0000906 const llvm::fltSemantics &SrcSema =
907 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000908
Richard Smith9e52c432019-07-06 21:05:52 +0000909 // Floating-point to integer. This has undefined behavior if the source is
910 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
911 // to an integer).
912 unsigned Width = CGF.getContext().getIntWidth(DstType);
913 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000914
Richard Smith9e52c432019-07-06 21:05:52 +0000915 APSInt Min = APSInt::getMinValue(Width, Unsigned);
916 APFloat MinSrc(SrcSema, APFloat::uninitialized);
917 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
918 APFloat::opOverflow)
919 // Don't need an overflow check for lower bound. Just check for
920 // -Inf/NaN.
921 MinSrc = APFloat::getInf(SrcSema, true);
922 else
923 // Find the largest value which is too small to represent (before
924 // truncation toward zero).
925 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000926
Richard Smith9e52c432019-07-06 21:05:52 +0000927 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
928 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
929 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
930 APFloat::opOverflow)
931 // Don't need an overflow check for upper bound. Just check for
932 // +Inf/NaN.
933 MaxSrc = APFloat::getInf(SrcSema, false);
934 else
935 // Find the smallest value which is too large to represent (before
936 // truncation toward zero).
937 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000938
Richard Smith9e52c432019-07-06 21:05:52 +0000939 // If we're converting from __half, convert the range to float to match
940 // the type of src.
941 if (OrigSrcType->isHalfType()) {
942 const llvm::fltSemantics &Sema =
943 CGF.getContext().getFloatTypeSemantics(SrcType);
944 bool IsInexact;
945 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
946 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000947 }
948
Richard Smith9e52c432019-07-06 21:05:52 +0000949 llvm::Value *GE =
950 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
951 llvm::Value *LE =
952 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
953 Check = Builder.CreateAnd(GE, LE);
954
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000955 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
956 CGF.EmitCheckTypeDescriptor(OrigSrcType),
957 CGF.EmitCheckTypeDescriptor(DstType)};
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000958 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000959 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000960}
961
Roman Lebedev62debd802018-10-30 21:58:56 +0000962// Should be called within CodeGenFunction::SanitizerScope RAII scope.
963// Returns 'i1 false' when the truncation Src -> Dst was lossy.
964static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
965 std::pair<llvm::Value *, SanitizerMask>>
966EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
967 QualType DstType, CGBuilderTy &Builder) {
968 llvm::Type *SrcTy = Src->getType();
969 llvm::Type *DstTy = Dst->getType();
Richard Trieu161121f2018-10-30 23:01:15 +0000970 (void)DstTy; // Only used in assert()
Roman Lebedev62debd802018-10-30 21:58:56 +0000971
972 // This should be truncation of integral types.
973 assert(Src != Dst);
974 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
975 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
976 "non-integer llvm type");
977
978 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
979 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
980
981 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
982 // Else, it is a signed truncation.
983 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
984 SanitizerMask Mask;
985 if (!SrcSigned && !DstSigned) {
986 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
987 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
988 } else {
989 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
990 Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
991 }
992
993 llvm::Value *Check = nullptr;
994 // 1. Extend the truncated value back to the same width as the Src.
995 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
996 // 2. Equality-compare with the original source value
997 Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
998 // If the comparison result is 'i1 false', then the truncation was lossy.
999 return std::make_pair(Kind, std::make_pair(Check, Mask));
1000}
1001
Roman Lebedevb98a0c72019-11-27 17:07:06 +03001002static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
1003 QualType SrcType, QualType DstType) {
1004 return SrcType->isIntegerType() && DstType->isIntegerType();
1005}
1006
Roman Lebedevb69ba222018-07-30 18:58:30 +00001007void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1008 Value *Dst, QualType DstType,
1009 SourceLocation Loc) {
Roman Lebedevdd403572018-10-11 09:09:50 +00001010 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
Roman Lebedevb69ba222018-07-30 18:58:30 +00001011 return;
1012
Roman Lebedev62debd802018-10-30 21:58:56 +00001013 // We only care about int->int conversions here.
1014 // We ignore conversions to/from pointer and/or bool.
Roman Lebedevb98a0c72019-11-27 17:07:06 +03001015 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1016 DstType))
Roman Lebedev62debd802018-10-30 21:58:56 +00001017 return;
1018
1019 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1020 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1021 // This must be truncation. Else we do not care.
1022 if (SrcBits <= DstBits)
1023 return;
1024
1025 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1026
1027 // If the integer sign change sanitizer is enabled,
1028 // and we are truncating from larger unsigned type to smaller signed type,
1029 // let that next sanitizer deal with it.
1030 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1031 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1032 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1033 (!SrcSigned && DstSigned))
1034 return;
1035
1036 CodeGenFunction::SanitizerScope SanScope(&CGF);
1037
1038 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1039 std::pair<llvm::Value *, SanitizerMask>>
1040 Check =
1041 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1042 // If the comparison result is 'i1 false', then the truncation was lossy.
1043
1044 // Do we care about this type of truncation?
1045 if (!CGF.SanOpts.has(Check.second.second))
1046 return;
1047
1048 llvm::Constant *StaticArgs[] = {
1049 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1050 CGF.EmitCheckTypeDescriptor(DstType),
1051 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1052 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1053 {Src, Dst});
1054}
1055
1056// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1057// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1058static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1059 std::pair<llvm::Value *, SanitizerMask>>
1060EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1061 QualType DstType, CGBuilderTy &Builder) {
1062 llvm::Type *SrcTy = Src->getType();
1063 llvm::Type *DstTy = Dst->getType();
1064
1065 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1066 "non-integer llvm type");
1067
1068 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1069 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
Richard Trieu161121f2018-10-30 23:01:15 +00001070 (void)SrcSigned; // Only used in assert()
1071 (void)DstSigned; // Only used in assert()
Roman Lebedev62debd802018-10-30 21:58:56 +00001072 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1073 unsigned DstBits = DstTy->getScalarSizeInBits();
1074 (void)SrcBits; // Only used in assert()
1075 (void)DstBits; // Only used in assert()
1076
1077 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1078 "either the widths should be different, or the signednesses.");
1079
1080 // NOTE: zero value is considered to be non-negative.
1081 auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1082 const char *Name) -> Value * {
1083 // Is this value a signed type?
1084 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1085 llvm::Type *VTy = V->getType();
1086 if (!VSigned) {
1087 // If the value is unsigned, then it is never negative.
1088 // FIXME: can we encounter non-scalar VTy here?
1089 return llvm::ConstantInt::getFalse(VTy->getContext());
1090 }
1091 // Get the zero of the same type with which we will be comparing.
1092 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1093 // %V.isnegative = icmp slt %V, 0
1094 // I.e is %V *strictly* less than zero, does it have negative value?
1095 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1096 llvm::Twine(Name) + "." + V->getName() +
1097 ".negativitycheck");
1098 };
1099
1100 // 1. Was the old Value negative?
1101 llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1102 // 2. Is the new Value negative?
1103 llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1104 // 3. Now, was the 'negativity status' preserved during the conversion?
1105 // NOTE: conversion from negative to zero is considered to change the sign.
1106 // (We want to get 'false' when the conversion changed the sign)
1107 // So we should just equality-compare the negativity statuses.
1108 llvm::Value *Check = nullptr;
1109 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1110 // If the comparison result is 'false', then the conversion changed the sign.
1111 return std::make_pair(
1112 ScalarExprEmitter::ICCK_IntegerSignChange,
1113 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1114}
1115
1116void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1117 Value *Dst, QualType DstType,
1118 SourceLocation Loc) {
1119 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1120 return;
1121
Roman Lebedevb69ba222018-07-30 18:58:30 +00001122 llvm::Type *SrcTy = Src->getType();
1123 llvm::Type *DstTy = Dst->getType();
1124
1125 // We only care about int->int conversions here.
1126 // We ignore conversions to/from pointer and/or bool.
Roman Lebedevb98a0c72019-11-27 17:07:06 +03001127 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1128 DstType))
Roman Lebedevb69ba222018-07-30 18:58:30 +00001129 return;
1130
Roman Lebedevdd403572018-10-11 09:09:50 +00001131 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1132 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
Roman Lebedev62debd802018-10-30 21:58:56 +00001133 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1134 unsigned DstBits = DstTy->getScalarSizeInBits();
Roman Lebedevdd403572018-10-11 09:09:50 +00001135
Roman Lebedev62debd802018-10-30 21:58:56 +00001136 // Now, we do not need to emit the check in *all* of the cases.
1137 // We can avoid emitting it in some obvious cases where it would have been
1138 // dropped by the opt passes (instcombine) always anyways.
Roman Lebedev1bb9aea2018-11-01 08:56:51 +00001139 // If it's a cast between effectively the same type, no check.
1140 // NOTE: this is *not* equivalent to checking the canonical types.
1141 if (SrcSigned == DstSigned && SrcBits == DstBits)
Roman Lebedevdd403572018-10-11 09:09:50 +00001142 return;
Roman Lebedev62debd802018-10-30 21:58:56 +00001143 // At least one of the values needs to have signed type.
1144 // If both are unsigned, then obviously, neither of them can be negative.
1145 if (!SrcSigned && !DstSigned)
1146 return;
1147 // If the conversion is to *larger* *signed* type, then no check is needed.
1148 // Because either sign-extension happens (so the sign will remain),
1149 // or zero-extension will happen (the sign bit will be zero.)
1150 if ((DstBits > SrcBits) && DstSigned)
1151 return;
1152 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1153 (SrcBits > DstBits) && SrcSigned) {
1154 // If the signed integer truncation sanitizer is enabled,
1155 // and this is a truncation from signed type, then no check is needed.
1156 // Because here sign change check is interchangeable with truncation check.
1157 return;
1158 }
1159 // That's it. We can't rule out any more cases with the data we have.
Roman Lebedevdd403572018-10-11 09:09:50 +00001160
Roman Lebedevb69ba222018-07-30 18:58:30 +00001161 CodeGenFunction::SanitizerScope SanScope(&CGF);
1162
Roman Lebedev62debd802018-10-30 21:58:56 +00001163 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1164 std::pair<llvm::Value *, SanitizerMask>>
1165 Check;
Roman Lebedevb69ba222018-07-30 18:58:30 +00001166
Roman Lebedev62debd802018-10-30 21:58:56 +00001167 // Each of these checks needs to return 'false' when an issue was detected.
1168 ImplicitConversionCheckKind CheckKind;
1169 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1170 // So we can 'and' all the checks together, and still get 'false',
1171 // if at least one of the checks detected an issue.
1172
1173 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1174 CheckKind = Check.first;
1175 Checks.emplace_back(Check.second);
1176
1177 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1178 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1179 // If the signed integer truncation sanitizer was enabled,
1180 // and we are truncating from larger unsigned type to smaller signed type,
1181 // let's handle the case we skipped in that check.
1182 Check =
1183 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1184 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1185 Checks.emplace_back(Check.second);
1186 // If the comparison result is 'i1 false', then the truncation was lossy.
1187 }
Roman Lebedevb69ba222018-07-30 18:58:30 +00001188
1189 llvm::Constant *StaticArgs[] = {
1190 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1191 CGF.EmitCheckTypeDescriptor(DstType),
Roman Lebedev62debd802018-10-30 21:58:56 +00001192 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1193 // EmitCheck() will 'and' all the checks together.
1194 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1195 {Src, Dst});
Roman Lebedevb69ba222018-07-30 18:58:30 +00001196}
1197
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00001198/// Emit a conversion from the specified type to the specified destination type,
1199/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00001200Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001201 QualType DstType,
Anastasia Stulovab02e7832015-10-05 11:27:41 +00001202 SourceLocation Loc,
Roman Lebedevb69ba222018-07-30 18:58:30 +00001203 ScalarConversionOpts Opts) {
Leonard Chanb4ba4672018-10-23 17:55:35 +00001204 // All conversions involving fixed point types should be handled by the
1205 // EmitFixedPoint family functions. This is done to prevent bloating up this
1206 // function more, and although fixed point numbers are represented by
1207 // integers, we do not want to follow any logic that assumes they should be
1208 // treated as integers.
1209 // TODO(leonardchan): When necessary, add another if statement checking for
1210 // conversions to fixed point types from other types.
1211 if (SrcType->isFixedPointType()) {
Leonard Chan8f7caae2019-03-06 00:28:43 +00001212 if (DstType->isBooleanType())
1213 // It is important that we check this before checking if the dest type is
1214 // an integer because booleans are technically integer types.
Leonard Chanb4ba4672018-10-23 17:55:35 +00001215 // We do not need to check the padding bit on unsigned types if unsigned
1216 // padding is enabled because overflow into this bit is undefined
1217 // behavior.
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001218 return Builder.CreateIsNotNull(Src, "tobool");
Leonard Chan8f7caae2019-03-06 00:28:43 +00001219 if (DstType->isFixedPointType() || DstType->isIntegerType())
1220 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
Leonard Chanb4ba4672018-10-23 17:55:35 +00001221
1222 llvm_unreachable(
Leonard Chan8f7caae2019-03-06 00:28:43 +00001223 "Unhandled scalar conversion from a fixed point type to another type.");
1224 } else if (DstType->isFixedPointType()) {
1225 if (SrcType->isIntegerType())
1226 // This also includes converting booleans and enums to fixed point types.
1227 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1228
1229 llvm_unreachable(
1230 "Unhandled scalar conversion to a fixed point type from another type.");
Leonard Chanb4ba4672018-10-23 17:55:35 +00001231 }
Leonard Chan99bda372018-10-15 16:07:02 +00001232
Roman Lebedevb69ba222018-07-30 18:58:30 +00001233 QualType NoncanonicalSrcType = SrcType;
1234 QualType NoncanonicalDstType = DstType;
1235
Chris Lattner0f398c42008-07-26 22:37:01 +00001236 SrcType = CGF.getContext().getCanonicalType(SrcType);
1237 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +00001238 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +00001239
Craig Topper8a13c412014-05-21 05:09:00 +00001240 if (DstType->isVoidType()) return nullptr;
Mike Stump4a3999f2009-09-09 13:00:44 +00001241
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001242 llvm::Value *OrigSrc = Src;
1243 QualType OrigSrcType = SrcType;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001244 llvm::Type *SrcTy = Src->getType();
1245
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +00001246 // Handle conversions to bool first, they are special: comparisons against 0.
1247 if (DstType->isBooleanType())
1248 return EmitConversionToBool(Src, SrcType);
1249
1250 llvm::Type *DstTy = ConvertType(DstType);
1251
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001252 // Cast from half through float if half isn't a native type.
1253 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1254 // Cast to FP using the intrinsic if the half type itself isn't supported.
1255 if (DstTy->isFloatingPointTy()) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00001256 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001257 return Builder.CreateCall(
1258 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1259 Src);
1260 } else {
1261 // Cast to other types through float, using either the intrinsic or FPExt,
1262 // depending on whether the half type itself is supported
1263 // (as opposed to operations on half, available with NativeHalfType).
Akira Hatanaka502775a2017-12-09 00:02:37 +00001264 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001265 Src = Builder.CreateCall(
1266 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1267 CGF.CGM.FloatTy),
1268 Src);
1269 } else {
1270 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1271 }
1272 SrcType = CGF.getContext().FloatTy;
1273 SrcTy = CGF.FloatTy;
1274 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001275 }
1276
Chris Lattner3474c202007-08-26 06:48:56 +00001277 // Ignore conversions like int -> uint.
Roman Lebedev62debd802018-10-30 21:58:56 +00001278 if (SrcTy == DstTy) {
1279 if (Opts.EmitImplicitIntegerSignChangeChecks)
1280 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1281 NoncanonicalDstType, Loc);
1282
Chris Lattner3474c202007-08-26 06:48:56 +00001283 return Src;
Roman Lebedev62debd802018-10-30 21:58:56 +00001284 }
Chris Lattner3474c202007-08-26 06:48:56 +00001285
Mike Stump4a3999f2009-09-09 13:00:44 +00001286 // Handle pointer conversions next: pointers can only be converted to/from
1287 // other pointers and integers. Check for pointer types in terms of LLVM, as
1288 // some native types (like Obj-C id) may map to a pointer type.
Yaxun Liu26f75662016-08-19 05:17:25 +00001289 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +00001290 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001291 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +00001292 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +00001293
Chris Lattner3474c202007-08-26 06:48:56 +00001294 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +00001295 // First, convert to the correct width so that we control the kind of
1296 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00001297 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001298 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +00001299 llvm::Value* IntResult =
1300 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1301 // Then, cast to pointer.
1302 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001303 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001304
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001305 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +00001306 // Must be an ptr to int cast.
1307 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +00001308 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001309 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001310
Nate Begemance4d7fc2008-04-18 23:10:10 +00001311 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +00001312 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
George Burgess IVdf1ed002016-01-13 01:52:39 +00001313 // Sema should add casts to make sure that the source expression's type is
1314 // the same as the vector's element type (sans qualifiers)
1315 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1316 SrcType.getTypePtr() &&
1317 "Splatted expr doesn't match with vector element type?");
Nate Begemanb699c9b2009-01-18 06:42:49 +00001318
Nate Begemanb699c9b2009-01-18 06:42:49 +00001319 // Splat the element across to all elements
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07001320 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
George Burgess IVdf1ed002016-01-13 01:52:39 +00001321 return Builder.CreateVectorSplat(NumElements, Src, "splat");
Nate Begemanb699c9b2009-01-18 06:42:49 +00001322 }
Nate Begeman330aaa72007-12-30 02:59:45 +00001323
Akira Hatanaka34b5dbc2017-09-23 05:02:02 +00001324 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1325 // Allow bitcast from vector to integer/fp of the same size.
1326 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1327 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1328 if (SrcSize == DstSize)
1329 return Builder.CreateBitCast(Src, DstTy, "conv");
1330
1331 // Conversions between vectors of different sizes are not allowed except
1332 // when vectors of half are involved. Operations on storage-only half
1333 // vectors require promoting half vector operands to float vectors and
1334 // truncating the result, which is either an int or float vector, to a
1335 // short or half vector.
1336
1337 // Source and destination are both expected to be vectors.
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07001338 llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1339 llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
Benjamin Kramer5c42bcc2017-09-23 16:08:48 +00001340 (void)DstElementTy;
Akira Hatanaka34b5dbc2017-09-23 05:02:02 +00001341
1342 assert(((SrcElementTy->isIntegerTy() &&
1343 DstElementTy->isIntegerTy()) ||
1344 (SrcElementTy->isFloatingPointTy() &&
1345 DstElementTy->isFloatingPointTy())) &&
1346 "unexpected conversion between a floating-point vector and an "
1347 "integer vector");
1348
1349 // Truncate an i32 vector to an i16 vector.
1350 if (SrcElementTy->isIntegerTy())
1351 return Builder.CreateIntCast(Src, DstTy, false, "conv");
1352
1353 // Truncate a float vector to a half vector.
1354 if (SrcSize > DstSize)
1355 return Builder.CreateFPTrunc(Src, DstTy, "conv");
1356
1357 // Promote a half vector to a float vector.
1358 return Builder.CreateFPExt(Src, DstTy, "conv");
1359 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001360
Chris Lattner3474c202007-08-26 06:48:56 +00001361 // Finally, we have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001362 Value *Res = nullptr;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001363 llvm::Type *ResTy = DstTy;
1364
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001365 // An overflowing conversion has undefined behavior if either the source type
Richard Smith9e52c432019-07-06 21:05:52 +00001366 // or the destination type is a floating-point type. However, we consider the
1367 // range of representable values for all floating-point types to be
1368 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1369 // floating-point type.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001370 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smith9e52c432019-07-06 21:05:52 +00001371 OrigSrcType->isFloatingType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001372 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1373 Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001374
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001375 // Cast to half through float if half isn't a native type.
1376 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1377 // Make sure we cast in a single step if from another FP type.
1378 if (SrcTy->isFloatingPointTy()) {
1379 // Use the intrinsic if the half type itself isn't supported
1380 // (as opposed to operations on half, available with NativeHalfType).
Akira Hatanaka502775a2017-12-09 00:02:37 +00001381 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001382 return Builder.CreateCall(
1383 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1384 // If the half type is supported, just use an fptrunc.
1385 return Builder.CreateFPTrunc(Src, DstTy);
1386 }
Chris Lattnerece04092012-02-07 00:39:47 +00001387 DstTy = CGF.FloatTy;
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +00001388 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001389
1390 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001391 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Roman Lebedevb69ba222018-07-30 18:58:30 +00001392 if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
Anastasia Stulovab02e7832015-10-05 11:27:41 +00001393 InputSigned = true;
1394 }
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001395 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001396 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001397 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001398 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001399 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001400 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1401 } else if (isa<llvm::IntegerType>(DstTy)) {
1402 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001403 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001404 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001405 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001406 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1407 } else {
1408 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1409 "Unknown real conversion");
1410 if (DstTy->getTypeID() < SrcTy->getTypeID())
1411 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1412 else
1413 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001414 }
1415
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001416 if (DstTy != ResTy) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00001417 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001418 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1419 Res = Builder.CreateCall(
Tim Northover6dbcbac2014-07-17 10:51:31 +00001420 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1421 Res);
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001422 } else {
1423 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1424 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001425 }
1426
Roman Lebedevb69ba222018-07-30 18:58:30 +00001427 if (Opts.EmitImplicitIntegerTruncationChecks)
1428 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1429 NoncanonicalDstType, Loc);
1430
Roman Lebedev62debd802018-10-30 21:58:56 +00001431 if (Opts.EmitImplicitIntegerSignChangeChecks)
1432 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1433 NoncanonicalDstType, Loc);
1434
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001435 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +00001436}
1437
Leonard Chan99bda372018-10-15 16:07:02 +00001438Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1439 QualType DstTy,
1440 SourceLocation Loc) {
Leonard Chan99bda372018-10-15 16:07:02 +00001441 FixedPointSemantics SrcFPSema =
1442 CGF.getContext().getFixedPointSemantics(SrcTy);
1443 FixedPointSemantics DstFPSema =
1444 CGF.getContext().getFixedPointSemantics(DstTy);
Leonard Chan8f7caae2019-03-06 00:28:43 +00001445 return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc,
1446 DstTy->isIntegerType());
Leonard Chan2044ac82019-01-16 18:13:59 +00001447}
1448
1449Value *ScalarExprEmitter::EmitFixedPointConversion(
1450 Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
Leonard Chan8f7caae2019-03-06 00:28:43 +00001451 SourceLocation Loc, bool DstIsInteger) {
Leonard Chan2044ac82019-01-16 18:13:59 +00001452 using llvm::APInt;
1453 using llvm::ConstantInt;
1454 using llvm::Value;
1455
Leonard Chan99bda372018-10-15 16:07:02 +00001456 unsigned SrcWidth = SrcFPSema.getWidth();
1457 unsigned DstWidth = DstFPSema.getWidth();
1458 unsigned SrcScale = SrcFPSema.getScale();
1459 unsigned DstScale = DstFPSema.getScale();
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001460 bool SrcIsSigned = SrcFPSema.isSigned();
1461 bool DstIsSigned = DstFPSema.isSigned();
1462
1463 llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
Leonard Chan99bda372018-10-15 16:07:02 +00001464
1465 Value *Result = Src;
1466 unsigned ResultWidth = SrcWidth;
1467
Leonard Chan8f7caae2019-03-06 00:28:43 +00001468 // Downscale.
1469 if (DstScale < SrcScale) {
1470 // When converting to integers, we round towards zero. For negative numbers,
1471 // right shifting rounds towards negative infinity. In this case, we can
1472 // just round up before shifting.
1473 if (DstIsInteger && SrcIsSigned) {
1474 Value *Zero = llvm::Constant::getNullValue(Result->getType());
1475 Value *IsNegative = Builder.CreateICmpSLT(Result, Zero);
1476 Value *LowBits = ConstantInt::get(
1477 CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
1478 Value *Rounded = Builder.CreateAdd(Result, LowBits);
1479 Result = Builder.CreateSelect(IsNegative, Rounded, Result);
1480 }
Leonard Chan99bda372018-10-15 16:07:02 +00001481
Leonard Chan8f7caae2019-03-06 00:28:43 +00001482 Result = SrcIsSigned
1483 ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale")
1484 : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
1485 }
1486
1487 if (!DstFPSema.isSaturated()) {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001488 // Resize.
1489 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
Leonard Chan99bda372018-10-15 16:07:02 +00001490
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001491 // Upscale.
Leonard Chan99bda372018-10-15 16:07:02 +00001492 if (DstScale > SrcScale)
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001493 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001494 } else {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001495 // Adjust the number of fractional bits.
Leonard Chan99bda372018-10-15 16:07:02 +00001496 if (DstScale > SrcScale) {
Leonard Chan2044ac82019-01-16 18:13:59 +00001497 // Compare to DstWidth to prevent resizing twice.
1498 ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
Leonard Chan99bda372018-10-15 16:07:02 +00001499 llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001500 Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
1501 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001502 }
1503
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001504 // Handle saturation.
1505 bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
1506 if (LessIntBits) {
1507 Value *Max = ConstantInt::get(
Leonard Chan99bda372018-10-15 16:07:02 +00001508 CGF.getLLVMContext(),
1509 APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001510 Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
1511 : Builder.CreateICmpUGT(Result, Max);
1512 Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
1513 }
1514 // Cannot overflow min to dest type if src is unsigned since all fixed
1515 // point types can cover the unsigned min of 0.
1516 if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
1517 Value *Min = ConstantInt::get(
1518 CGF.getLLVMContext(),
1519 APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
1520 Value *TooLow = Builder.CreateICmpSLT(Result, Min);
1521 Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
Leonard Chan99bda372018-10-15 16:07:02 +00001522 }
1523
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001524 // Resize the integer part to get the final destination size.
Leonard Chan2044ac82019-01-16 18:13:59 +00001525 if (ResultWidth != DstWidth)
1526 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
Leonard Chan99bda372018-10-15 16:07:02 +00001527 }
1528 return Result;
1529}
1530
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00001531/// Emit a conversion from the specified complex type to the specified
1532/// destination type, where the destination type is an LLVM scalar type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001533Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1534 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1535 SourceLocation Loc) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001536 // Get the source element type.
John McCall47fb9502013-03-07 21:37:08 +00001537 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001538
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001539 // Handle conversions to bool first, they are special: comparisons against 0.
1540 if (DstTy->isBooleanType()) {
1541 // Complex != 0 -> (Real != 0) | (Imag != 0)
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001542 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1543 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001544 return Builder.CreateOr(Src.first, Src.second, "tobool");
1545 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001546
Chris Lattner42e6b812007-08-26 16:34:22 +00001547 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1548 // the imaginary part of the complex value is discarded and the value of the
1549 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +00001550 // corresponding real type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001551 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00001552}
1553
Anders Carlsson5b944432010-05-22 17:45:10 +00001554Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001555 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlsson5b944432010-05-22 17:45:10 +00001556}
Chris Lattner42e6b812007-08-26 16:34:22 +00001557
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001558/// Emit a sanitization check for the given "binary" operation (which
Richard Smithe30752c2012-10-09 19:52:38 +00001559/// might actually be a unary increment which has been lowered to a binary
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001560/// operation). The check passes if all values in \p Checks (which are \c i1),
1561/// are \c true.
1562void ScalarExprEmitter::EmitBinOpCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001563 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001564 assert(CGF.IsSanitizerScope);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001565 SanitizerHandler Check;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001566 SmallVector<llvm::Constant *, 4> StaticData;
1567 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smithe30752c2012-10-09 19:52:38 +00001568
1569 BinaryOperatorKind Opcode = Info.Opcode;
1570 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1571 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1572
1573 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1574 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1575 if (UO && UO->getOpcode() == UO_Minus) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001576 Check = SanitizerHandler::NegateOverflow;
Richard Smithe30752c2012-10-09 19:52:38 +00001577 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1578 DynamicData.push_back(Info.RHS);
1579 } else {
1580 if (BinaryOperator::isShiftOp(Opcode)) {
1581 // Shift LHS negative or too large, or RHS out of bounds.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001582 Check = SanitizerHandler::ShiftOutOfBounds;
Richard Smithe30752c2012-10-09 19:52:38 +00001583 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1584 StaticData.push_back(
1585 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1586 StaticData.push_back(
1587 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1588 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1589 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001590 Check = SanitizerHandler::DivremOverflow;
Will Dietzcefb4482013-01-07 22:25:52 +00001591 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001592 } else {
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001593 // Arithmetic overflow (+, -, *).
Richard Smithe30752c2012-10-09 19:52:38 +00001594 switch (Opcode) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001595 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1596 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1597 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
Richard Smithe30752c2012-10-09 19:52:38 +00001598 default: llvm_unreachable("unexpected opcode for bin op check");
1599 }
Will Dietzcefb4482013-01-07 22:25:52 +00001600 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001601 }
1602 DynamicData.push_back(Info.LHS);
1603 DynamicData.push_back(Info.RHS);
1604 }
1605
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001606 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
Richard Smithe30752c2012-10-09 19:52:38 +00001607}
1608
Chris Lattner2da04b32007-08-24 05:35:26 +00001609//===----------------------------------------------------------------------===//
1610// Visitor Methods
1611//===----------------------------------------------------------------------===//
1612
1613Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001614 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +00001615 if (E->getType()->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001616 return nullptr;
Owen Anderson7ec07a52009-07-30 23:11:26 +00001617 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +00001618}
1619
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001620Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +00001621 // Vector Mask Case
Craig Topperb3174a82016-05-18 04:11:25 +00001622 if (E->getNumSubExprs() == 2) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00001623 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1624 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1625 Value *Mask;
Craig Toppera97d7e72013-07-26 06:16:11 +00001626
Chris Lattner2192fe52011-07-18 04:24:23 +00001627 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +00001628 unsigned LHSElts = LTy->getNumElements();
1629
Craig Topperb3174a82016-05-18 04:11:25 +00001630 Mask = RHS;
Craig Toppera97d7e72013-07-26 06:16:11 +00001631
Chris Lattner2192fe52011-07-18 04:24:23 +00001632 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001633
Nate Begemana0110022010-06-08 00:16:34 +00001634 // Mask off the high bits of each shuffle index.
Benjamin Kramer99383102015-07-28 16:25:32 +00001635 Value *MaskBits =
1636 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
Nate Begemana0110022010-06-08 00:16:34 +00001637 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Toppera97d7e72013-07-26 06:16:11 +00001638
Nate Begemana0110022010-06-08 00:16:34 +00001639 // newv = undef
1640 // mask = mask & maskbits
1641 // for each elt
1642 // n = extract mask i
1643 // x = extract val n
1644 // newv = insert newv, x, i
Christopher Tetreault79689812020-06-01 09:55:24 -07001645 auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
1646 MTy->getNumElements());
Nate Begemana0110022010-06-08 00:16:34 +00001647 Value* NewV = llvm::UndefValue::get(RTy);
1648 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Michael J. Spencerdd597752014-05-31 00:22:12 +00001649 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman1fa36052012-04-05 21:48:40 +00001650 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Toppera97d7e72013-07-26 06:16:11 +00001651
Nate Begemana0110022010-06-08 00:16:34 +00001652 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +00001653 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +00001654 }
1655 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001656 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001657
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001658 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1659 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Toppera97d7e72013-07-26 06:16:11 +00001660
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001661 SmallVector<int, 32> Indices;
Craig Topper0ed37bd2013-08-01 04:51:48 +00001662 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper50ad5b72013-08-03 17:40:38 +00001663 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1664 // Check for -1 and output it as undef in the IR.
1665 if (Idx.isSigned() && Idx.isAllOnesValue())
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001666 Indices.push_back(-1);
Craig Topper50ad5b72013-08-03 17:40:38 +00001667 else
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001668 Indices.push_back(Idx.getZExtValue());
Nate Begemana0110022010-06-08 00:16:34 +00001669 }
1670
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001671 return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001672}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001673
1674Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1675 QualType SrcType = E->getSrcExpr()->getType(),
1676 DstType = E->getType();
1677
1678 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1679
1680 SrcType = CGF.getContext().getCanonicalType(SrcType);
1681 DstType = CGF.getContext().getCanonicalType(DstType);
1682 if (SrcType == DstType) return Src;
1683
1684 assert(SrcType->isVectorType() &&
1685 "ConvertVector source type must be a vector");
1686 assert(DstType->isVectorType() &&
1687 "ConvertVector destination type must be a vector");
1688
1689 llvm::Type *SrcTy = Src->getType();
1690 llvm::Type *DstTy = ConvertType(DstType);
1691
1692 // Ignore conversions like int -> uint.
1693 if (SrcTy == DstTy)
1694 return Src;
1695
Simon Pilgrime0712012019-10-02 15:31:25 +00001696 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1697 DstEltType = DstType->castAs<VectorType>()->getElementType();
Hal Finkelc4d7c822013-09-18 03:29:45 +00001698
1699 assert(SrcTy->isVectorTy() &&
1700 "ConvertVector source IR type must be a vector");
1701 assert(DstTy->isVectorTy() &&
1702 "ConvertVector destination IR type must be a vector");
1703
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07001704 llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
1705 *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
Hal Finkelc4d7c822013-09-18 03:29:45 +00001706
1707 if (DstEltType->isBooleanType()) {
1708 assert((SrcEltTy->isFloatingPointTy() ||
1709 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1710
1711 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1712 if (SrcEltTy->isFloatingPointTy()) {
1713 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1714 } else {
1715 return Builder.CreateICmpNE(Src, Zero, "tobool");
1716 }
1717 }
1718
1719 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001720 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001721
1722 if (isa<llvm::IntegerType>(SrcEltTy)) {
1723 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1724 if (isa<llvm::IntegerType>(DstEltTy))
1725 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1726 else if (InputSigned)
1727 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1728 else
1729 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1730 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1731 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1732 if (DstEltType->isSignedIntegerOrEnumerationType())
1733 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1734 else
1735 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1736 } else {
1737 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1738 "Unknown real conversion");
1739 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1740 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1741 else
1742 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1743 }
1744
1745 return Res;
1746}
1747
Eli Friedmancb422f12009-11-26 03:22:21 +00001748Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00001749 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1750 CGF.EmitIgnoredExpr(E->getBase());
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +00001751 return CGF.emitScalarConstant(Constant, E);
Alex Lorenz6cc83172017-08-25 10:07:00 +00001752 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00001753 Expr::EvalResult Result;
1754 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1755 llvm::APSInt Value = Result.Val.getInt();
Alex Lorenz6cc83172017-08-25 10:07:00 +00001756 CGF.EmitIgnoredExpr(E->getBase());
1757 return Builder.getInt(Value);
1758 }
Eli Friedmancb422f12009-11-26 03:22:21 +00001759 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001760
Eli Friedmancb422f12009-11-26 03:22:21 +00001761 return EmitLoadOfLValue(E);
1762}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001763
Chris Lattner2da04b32007-08-24 05:35:26 +00001764Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001765 TestAndClearIgnoreResultAssign();
1766
Chris Lattner2da04b32007-08-24 05:35:26 +00001767 // Emit subscript expressions in rvalue context's. For most cases, this just
1768 // loads the lvalue formed by the subscript expr. However, we have to be
1769 // careful, because the base of a vector subscript is occasionally an rvalue,
1770 // so we can't get it as an lvalue.
1771 if (!E->getBase()->getType()->isVectorType())
1772 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001773
Chris Lattner2da04b32007-08-24 05:35:26 +00001774 // Handle the vector case. The base must be a vector, the index must be an
1775 // integer value.
1776 Value *Base = Visit(E->getBase());
1777 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001778 QualType IdxTy = E->getIdx()->getType();
1779
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001780 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001781 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1782
Chris Lattner2da04b32007-08-24 05:35:26 +00001783 return Builder.CreateExtractElement(Base, Idx, "vecext");
1784}
1785
Florian Hahn8f3f88d2020-06-01 19:42:03 +01001786Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
1787 TestAndClearIgnoreResultAssign();
1788
1789 // Handle the vector case. The base must be a vector, the index must be an
1790 // integer value.
1791 Value *RowIdx = Visit(E->getRowIdx());
1792 Value *ColumnIdx = Visit(E->getColumnIdx());
1793 Value *Matrix = Visit(E->getBase());
1794
1795 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
1796 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
1797 return MB.CreateExtractElement(
1798 Matrix, RowIdx, ColumnIdx,
1799 E->getBase()->getType()->getAs<ConstantMatrixType>()->getNumRows());
1800}
1801
Benjamin Kramerb6390912020-04-17 16:33:39 +02001802static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1803 unsigned Off) {
Nate Begeman19351632009-10-18 20:10:40 +00001804 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001805 if (MV == -1)
Benjamin Kramerb6390912020-04-17 16:33:39 +02001806 return -1;
1807 return Off + MV;
Nate Begeman19351632009-10-18 20:10:40 +00001808}
1809
Benjamin Kramerb6390912020-04-17 16:33:39 +02001810static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1811 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
1812 "Index operand too large for shufflevector mask!");
1813 return C->getZExtValue();
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001814}
1815
Nate Begeman19351632009-10-18 20:10:40 +00001816Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1817 bool Ignore = TestAndClearIgnoreResultAssign();
1818 (void)Ignore;
1819 assert (Ignore == false && "init list ignored");
1820 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001821
Nate Begeman19351632009-10-18 20:10:40 +00001822 if (E->hadArrayRangeDesignator())
1823 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001824
Chris Lattner2192fe52011-07-18 04:24:23 +00001825 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001826 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001827
Sebastian Redl12757ab2011-09-24 17:48:14 +00001828 if (!VType) {
1829 if (NumInitElements == 0) {
1830 // C++11 value-initialization for the scalar.
1831 return EmitNullValue(E->getType());
1832 }
1833 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001834 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001835 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001836
Nate Begeman19351632009-10-18 20:10:40 +00001837 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001838
1839 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001840 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1841 // us to fold the shuffle for the swizzle into the shuffle for the vector
1842 // initializer, since LLVM optimizers generally do not want to touch
1843 // shuffles.
1844 unsigned CurIdx = 0;
1845 bool VIsUndefShuffle = false;
1846 llvm::Value *V = llvm::UndefValue::get(VType);
1847 for (unsigned i = 0; i != NumInitElements; ++i) {
1848 Expr *IE = E->getInit(i);
1849 Value *Init = Visit(IE);
Benjamin Kramerb6390912020-04-17 16:33:39 +02001850 SmallVector<int, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001851
Chris Lattner2192fe52011-07-18 04:24:23 +00001852 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001853
Nate Begeman19351632009-10-18 20:10:40 +00001854 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001855 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001856 // extract+insert.
1857 if (!VVT) {
1858 if (isa<ExtVectorElementExpr>(IE)) {
1859 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1860
1861 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1862 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001863 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001864 if (CurIdx == 0) {
1865 // insert into undef -> shuffle (src, undef)
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001866 // shufflemask must use an i32
1867 Args.push_back(getAsInt32(C, CGF.Int32Ty));
Benjamin Kramerb6390912020-04-17 16:33:39 +02001868 Args.resize(ResElts, -1);
Nate Begeman19351632009-10-18 20:10:40 +00001869
1870 LHS = EI->getVectorOperand();
1871 RHS = V;
1872 VIsUndefShuffle = true;
1873 } else if (VIsUndefShuffle) {
1874 // insert into undefshuffle && size match -> shuffle (v, src)
1875 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1876 for (unsigned j = 0; j != CurIdx; ++j)
Benjamin Kramerb6390912020-04-17 16:33:39 +02001877 Args.push_back(getMaskElt(SVV, j, 0));
1878 Args.push_back(ResElts + C->getZExtValue());
1879 Args.resize(ResElts, -1);
Benjamin Kramer8001f742012-02-14 12:06:21 +00001880
Nate Begeman19351632009-10-18 20:10:40 +00001881 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1882 RHS = EI->getVectorOperand();
1883 VIsUndefShuffle = false;
1884 }
1885 if (!Args.empty()) {
Benjamin Kramerb6390912020-04-17 16:33:39 +02001886 V = Builder.CreateShuffleVector(LHS, RHS, Args);
Nate Begeman19351632009-10-18 20:10:40 +00001887 ++CurIdx;
1888 continue;
1889 }
1890 }
1891 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001892 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1893 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001894 VIsUndefShuffle = false;
1895 ++CurIdx;
1896 continue;
1897 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001898
Nate Begeman19351632009-10-18 20:10:40 +00001899 unsigned InitElts = VVT->getNumElements();
1900
Craig Toppera97d7e72013-07-26 06:16:11 +00001901 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001902 // input is the same width as the vector being constructed, generate an
1903 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001904 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001905 if (isa<ExtVectorElementExpr>(IE)) {
1906 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1907 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001908 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001909
Nate Begeman19351632009-10-18 20:10:40 +00001910 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001911 for (unsigned j = 0; j != CurIdx; ++j) {
1912 // If the current vector initializer is a shuffle with undef, merge
1913 // this shuffle directly into it.
1914 if (VIsUndefShuffle) {
Benjamin Kramerb6390912020-04-17 16:33:39 +02001915 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0));
Nate Begeman19351632009-10-18 20:10:40 +00001916 } else {
Benjamin Kramerb6390912020-04-17 16:33:39 +02001917 Args.push_back(j);
Nate Begeman19351632009-10-18 20:10:40 +00001918 }
1919 }
1920 for (unsigned j = 0, je = InitElts; j != je; ++j)
Benjamin Kramerb6390912020-04-17 16:33:39 +02001921 Args.push_back(getMaskElt(SVI, j, Offset));
1922 Args.resize(ResElts, -1);
Nate Begeman19351632009-10-18 20:10:40 +00001923
1924 if (VIsUndefShuffle)
1925 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1926
1927 Init = SVOp;
1928 }
1929 }
1930
1931 // Extend init to result vector length, and then shuffle its contribution
1932 // to the vector initializer into V.
1933 if (Args.empty()) {
1934 for (unsigned j = 0; j != InitElts; ++j)
Benjamin Kramerb6390912020-04-17 16:33:39 +02001935 Args.push_back(j);
1936 Args.resize(ResElts, -1);
1937 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), Args,
1938 "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001939
1940 Args.clear();
1941 for (unsigned j = 0; j != CurIdx; ++j)
Benjamin Kramerb6390912020-04-17 16:33:39 +02001942 Args.push_back(j);
Nate Begeman19351632009-10-18 20:10:40 +00001943 for (unsigned j = 0; j != InitElts; ++j)
Benjamin Kramerb6390912020-04-17 16:33:39 +02001944 Args.push_back(j + Offset);
1945 Args.resize(ResElts, -1);
Nate Begeman19351632009-10-18 20:10:40 +00001946 }
1947
1948 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1949 // merging subsequent shuffles into this one.
1950 if (CurIdx == 0)
1951 std::swap(V, Init);
Benjamin Kramerb6390912020-04-17 16:33:39 +02001952 V = Builder.CreateShuffleVector(V, Init, Args, "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001953 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1954 CurIdx += InitElts;
1955 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001956
Nate Begeman19351632009-10-18 20:10:40 +00001957 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1958 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001959 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001960
Nate Begeman19351632009-10-18 20:10:40 +00001961 // Emit remaining default initializers
1962 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001963 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001964 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1965 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1966 }
1967 return V;
1968}
1969
John McCall7f416cc2015-09-08 08:05:57 +00001970bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001971 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001972
John McCalle3027922010-08-25 11:45:40 +00001973 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001974 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001975
John McCall7f416cc2015-09-08 08:05:57 +00001976 if (isa<CXXThisExpr>(E->IgnoreParens())) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001977 // We always assume that 'this' is never null.
1978 return false;
1979 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001980
Anders Carlsson8c793172009-11-23 17:57:54 +00001981 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001982 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001983 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001984 return false;
1985 }
1986
1987 return true;
1988}
1989
Chris Lattner2da04b32007-08-24 05:35:26 +00001990// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1991// have to handle a more broad range of conversions than explicit casts, as they
1992// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001993Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001994 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001995 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001996 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001997
John McCalle399e5b2016-01-27 18:32:30 +00001998 // These cases are generally not written to ignore the result of
1999 // evaluating their sub-expressions, so we clear this now.
2000 bool Ignored = TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00002001
Eli Friedman0dfc6802009-11-27 02:07:44 +00002002 // Since almost all cast kinds apply to scalars, this switch doesn't have
2003 // a default case, so the compiler will warn on a missing case. The cases
2004 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00002005 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00002006 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00002007 case CK_BuiltinFnToFnPtr:
2008 llvm_unreachable("builtin functions are handled elsewhere");
2009
Craig Toppera97d7e72013-07-26 06:16:11 +00002010 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00002011 case CK_ObjCObjectLValueCast: {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002012 Address Addr = EmitLValue(E).getAddress(CGF);
Alexey Bataevf2440332015-10-07 10:22:08 +00002013 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
John McCall7f416cc2015-09-08 08:05:57 +00002014 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
2015 return EmitLoadOfLValue(LV, CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00002016 }
John McCallcd78e802011-09-10 01:16:55 +00002017
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002018 case CK_LValueToRValueBitCast: {
2019 LValue SourceLVal = CGF.EmitLValue(E);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002020 Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002021 CGF.ConvertTypeForMem(DestTy));
2022 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2023 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2024 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2025 }
2026
John McCall9320b872011-09-09 05:25:32 +00002027 case CK_CPointerToObjCPointerCast:
2028 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002029 case CK_AnyPointerToBlockPointerCast:
2030 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002031 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00002032 llvm::Type *SrcTy = Src->getType();
2033 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00002034 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00002035 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002036 llvm_unreachable("wrong cast for pointers in different address spaces"
2037 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00002038 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00002039
2040 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2041 if (auto PT = DestTy->getAs<PointerType>())
2042 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002043 /*MayBeNull=*/true,
2044 CodeGenFunction::CFITCK_UnrelatedCast,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002045 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002046 }
2047
Piotr Padlewski07058292018-07-02 19:21:36 +00002048 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2049 const QualType SrcType = E->getType();
2050
2051 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2052 // Casting to pointer that could carry dynamic information (provided by
2053 // invariant.group) requires launder.
2054 Src = Builder.CreateLaunderInvariantGroup(Src);
2055 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2056 // Casting to pointer that does not carry dynamic information (provided
2057 // by invariant.group) requires stripping it. Note that we don't do it
2058 // if the source could not be dynamic type and destination could be
2059 // dynamic because dynamic information is already laundered. It is
2060 // because launder(strip(src)) == launder(src), so there is no need to
2061 // add extra strip before launder.
2062 Src = Builder.CreateStripInvariantGroup(Src);
2063 }
2064 }
2065
Arthur Eubanksce7d3e12020-06-08 19:07:59 -07002066 // Update heapallocsite metadata when there is an explicit pointer cast.
2067 if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
2068 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) {
2069 QualType PointeeType = DestTy->getPointeeType();
2070 if (!PointeeType.isNull())
2071 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
2072 CE->getExprLoc());
2073 }
2074 }
Amy Huang301a5bb2019-05-02 20:07:35 +00002075
David Tweede1468322013-12-11 13:39:46 +00002076 return Builder.CreateBitCast(Src, DstTy);
2077 }
2078 case CK_AddressSpaceConversion: {
Yaxun Liu402804b2016-12-15 08:09:08 +00002079 Expr::EvalResult Result;
2080 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2081 Result.Val.isNullPointer()) {
2082 // If E has side effect, it is emitted even if its final result is a
2083 // null pointer. In that case, a DCE pass should be able to
2084 // eliminate the useless instructions emitted during translating E.
2085 if (Result.HasSideEffects)
2086 Visit(E);
2087 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2088 ConvertType(DestTy)), DestTy);
2089 }
Yaxun Liub7b6d0f2016-04-12 19:03:49 +00002090 // Since target may map different address spaces in AST to the same address
2091 // space, an address space conversion may end up as a bitcast.
Yaxun Liu6d96f1632017-05-18 18:51:09 +00002092 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2093 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2094 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002095 }
David Chisnallfa35df62012-01-16 17:27:18 +00002096 case CK_AtomicToNonAtomic:
2097 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00002098 case CK_NoOp:
2099 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002100 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00002101
John McCalle3027922010-08-25 11:45:40 +00002102 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00002103 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2104 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2105
John McCall7f416cc2015-09-08 08:05:57 +00002106 Address Base = CGF.EmitPointerWithAlignment(E);
2107 Address Derived =
2108 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002109 CE->path_begin(), CE->path_end(),
John McCall7f416cc2015-09-08 08:05:57 +00002110 CGF.ShouldNullCheckClassCastValue(CE));
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002111
Richard Smith2c5868c2013-02-13 21:18:23 +00002112 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2113 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00002114 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00002115 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00002116 Derived.getPointer(), DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00002117
Peter Collingbourned2926c92015-03-14 02:42:25 +00002118 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002119 CGF.EmitVTablePtrCheckForCast(
2120 DestTy->getPointeeType(), Derived.getPointer(),
2121 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2122 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002123
John McCall7f416cc2015-09-08 08:05:57 +00002124 return Derived.getPointer();
Anders Carlsson8c793172009-11-23 17:57:54 +00002125 }
John McCalle3027922010-08-25 11:45:40 +00002126 case CK_UncheckedDerivedToBase:
2127 case CK_DerivedToBase: {
John McCall7f416cc2015-09-08 08:05:57 +00002128 // The EmitPointerWithAlignment path does this fine; just discard
2129 // the alignment.
2130 return CGF.EmitPointerWithAlignment(CE).getPointer();
Anders Carlsson12f5a252009-09-12 04:57:16 +00002131 }
John McCall7f416cc2015-09-08 08:05:57 +00002132
Anders Carlsson8a01a752011-04-11 02:03:26 +00002133 case CK_Dynamic: {
John McCall7f416cc2015-09-08 08:05:57 +00002134 Address V = CGF.EmitPointerWithAlignment(E);
Eli Friedman0dfc6802009-11-27 02:07:44 +00002135 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2136 return CGF.EmitDynamicCast(V, DCE);
2137 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00002138
John McCall7f416cc2015-09-08 08:05:57 +00002139 case CK_ArrayToPointerDecay:
2140 return CGF.EmitArrayToPointerDecay(E).getPointer();
John McCalle3027922010-08-25 11:45:40 +00002141 case CK_FunctionToPointerDecay:
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002142 return EmitLValue(E).getPointer(CGF);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002143
John McCalle84af4e2010-11-13 01:35:44 +00002144 case CK_NullToPointer:
2145 if (MustVisitNullValue(E))
Richard Smith27252a12019-06-14 17:46:38 +00002146 CGF.EmitIgnoredExpr(E);
John McCalle84af4e2010-11-13 01:35:44 +00002147
Yaxun Liu402804b2016-12-15 08:09:08 +00002148 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2149 DestTy);
John McCalle84af4e2010-11-13 01:35:44 +00002150
John McCalle3027922010-08-25 11:45:40 +00002151 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00002152 if (MustVisitNullValue(E))
Richard Smith27252a12019-06-14 17:46:38 +00002153 CGF.EmitIgnoredExpr(E);
John McCalla1dee5302010-08-22 10:59:02 +00002154
John McCall7a9aac22010-08-23 01:21:21 +00002155 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2156 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2157 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00002158
John McCallc62bb392012-02-15 01:22:51 +00002159 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00002160 case CK_BaseToDerivedMemberPointer:
2161 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00002162 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002163
John McCalla1dee5302010-08-22 10:59:02 +00002164 // Note that the AST doesn't distinguish between checked and
2165 // unchecked member pointer conversions, so we always have to
2166 // implement checked conversions here. This is inefficient when
2167 // actual control flow may be required in order to perform the
2168 // check, which it is for data member pointers (but not member
2169 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00002170 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00002171 }
John McCall31168b02011-06-15 23:02:42 +00002172
John McCall2d637d22011-09-10 06:18:15 +00002173 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00002174 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00002175 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00002176 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCalle399e5b2016-01-27 18:32:30 +00002177 case CK_ARCReclaimReturnedObject:
2178 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
John McCallff613032011-10-04 06:23:45 +00002179 case CK_ARCExtendBlockObject:
2180 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00002181
Douglas Gregored90df32012-02-22 05:02:47 +00002182 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00002183 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00002184
John McCallc5e62b42010-11-13 09:02:35 +00002185 case CK_FloatingRealToComplex:
2186 case CK_FloatingComplexCast:
2187 case CK_IntegralRealToComplex:
2188 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002189 case CK_IntegralComplexToFloatingComplex:
2190 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00002191 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00002192 case CK_ToUnion:
2193 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00002194
John McCallf3735e02010-12-01 04:43:34 +00002195 case CK_LValueToRValue:
2196 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00002197 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00002198 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00002199
John McCalle3027922010-08-25 11:45:40 +00002200 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00002201 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002202
Anders Carlsson094c4592009-10-18 18:12:03 +00002203 // First, convert to the correct width so that we control the kind of
2204 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00002205 auto DestLLVMTy = ConvertType(DestTy);
2206 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002207 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00002208 llvm::Value* IntResult =
2209 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002210
Piotr Padlewski07058292018-07-02 19:21:36 +00002211 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002212
Piotr Padlewski07058292018-07-02 19:21:36 +00002213 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2214 // Going from integer to pointer that could be dynamic requires reloading
2215 // dynamic information from invariant.group.
2216 if (DestTy.mayBeDynamicClass())
2217 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2218 }
2219 return IntToPtr;
2220 }
2221 case CK_PointerToIntegral: {
2222 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2223 auto *PtrExpr = Visit(E);
2224
2225 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2226 const QualType SrcType = E->getType();
2227
2228 // Casting to integer requires stripping dynamic information as it does
2229 // not carries it.
2230 if (SrcType.mayBeDynamicClass())
2231 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2232 }
2233
2234 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2235 }
John McCalle3027922010-08-25 11:45:40 +00002236 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00002237 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002238 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002239 }
John McCalle3027922010-08-25 11:45:40 +00002240 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00002241 llvm::Type *DstTy = ConvertType(DestTy);
George Burgess IVdf1ed002016-01-13 01:52:39 +00002242 Value *Elt = Visit(const_cast<Expr*>(E));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002243 // Splat the element across to all elements
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07002244 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00002245 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002246 }
John McCall8cb679e2010-11-15 09:13:47 +00002247
Leonard Chan99bda372018-10-15 16:07:02 +00002248 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00002249 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2250 CE->getExprLoc());
2251
2252 case CK_FixedPointToBoolean:
2253 assert(E->getType()->isFixedPointType() &&
2254 "Expected src type to be fixed point type");
2255 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2256 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2257 CE->getExprLoc());
Leonard Chan99bda372018-10-15 16:07:02 +00002258
Leonard Chan8f7caae2019-03-06 00:28:43 +00002259 case CK_FixedPointToIntegral:
2260 assert(E->getType()->isFixedPointType() &&
2261 "Expected src type to be fixed point type");
2262 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2263 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2264 CE->getExprLoc());
2265
2266 case CK_IntegralToFixedPoint:
2267 assert(E->getType()->isIntegerType() &&
2268 "Expected src type to be an integer");
2269 assert(DestTy->isFixedPointType() &&
2270 "Expected dest type to be fixed point type");
2271 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2272 CE->getExprLoc());
2273
Roman Lebedevb69ba222018-07-30 18:58:30 +00002274 case CK_IntegralCast: {
2275 ScalarConversionOpts Opts;
Roman Lebedev62debd802018-10-30 21:58:56 +00002276 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Roman Lebedevd677c3f2018-11-19 19:56:43 +00002277 if (!ICE->isPartOfExplicitCast())
2278 Opts = ScalarConversionOpts(CGF.SanOpts);
Roman Lebedevb69ba222018-07-30 18:58:30 +00002279 }
2280 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2281 CE->getExprLoc(), Opts);
2282 }
John McCalle3027922010-08-25 11:45:40 +00002283 case CK_IntegralToFloating:
2284 case CK_FloatingToIntegral:
2285 case CK_FloatingCast:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002286 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2287 CE->getExprLoc());
Roman Lebedevb69ba222018-07-30 18:58:30 +00002288 case CK_BooleanToSignedIntegral: {
2289 ScalarConversionOpts Opts;
2290 Opts.TreatBooleanAsSigned = true;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002291 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
Roman Lebedevb69ba222018-07-30 18:58:30 +00002292 CE->getExprLoc(), Opts);
2293 }
John McCall8cb679e2010-11-15 09:13:47 +00002294 case CK_IntegralToBoolean:
2295 return EmitIntToBoolConversion(Visit(E));
2296 case CK_PointerToBoolean:
Yaxun Liu402804b2016-12-15 08:09:08 +00002297 return EmitPointerToBoolConversion(Visit(E), E->getType());
John McCall8cb679e2010-11-15 09:13:47 +00002298 case CK_FloatingToBoolean:
2299 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00002300 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00002301 llvm::Value *MemPtr = Visit(E);
2302 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2303 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00002304 }
John McCalld7646252010-11-14 08:17:51 +00002305
2306 case CK_FloatingComplexToReal:
2307 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00002308 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00002309
2310 case CK_FloatingComplexToBoolean:
2311 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00002312 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00002313
2314 // TODO: kill this function off, inline appropriate case here
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002315 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2316 CE->getExprLoc());
John McCalld7646252010-11-14 08:17:51 +00002317 }
2318
Andrew Savonichevb555b762018-10-23 15:19:20 +00002319 case CK_ZeroToOCLOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002320 assert((DestTy->isEventT() || DestTy->isQueueT() ||
2321 DestTy->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00002322 "CK_ZeroToOCLEvent cast on non-event type");
Egor Churaev89831422016-12-23 14:55:49 +00002323 return llvm::Constant::getNullValue(ConvertType(DestTy));
2324 }
2325
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002326 case CK_IntToOCLSampler:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002327 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002328
2329 } // end of switch
Mike Stump4a3999f2009-09-09 13:00:44 +00002330
John McCall3eba6e62010-11-16 06:21:14 +00002331 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00002332}
2333
Chris Lattner04a913b2007-08-31 22:09:40 +00002334Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00002335 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002336 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2337 !E->getType()->isVoidType());
2338 if (!RetAlloca.isValid())
Craig Topper8a13c412014-05-21 05:09:00 +00002339 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002340 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2341 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00002342}
2343
Reid Kleckner092d0652017-03-06 22:18:34 +00002344Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
Reid Kleckner092d0652017-03-06 22:18:34 +00002345 CodeGenFunction::RunCleanupsScope Scope(CGF);
2346 Value *V = Visit(E->getSubExpr());
2347 // Defend against dominance problems caused by jumps out of expression
2348 // evaluation through the shared cleanup block.
2349 Scope.ForceCleanup({&V});
2350 return V;
2351}
2352
Chris Lattner2da04b32007-08-24 05:35:26 +00002353//===----------------------------------------------------------------------===//
2354// Unary Operators
2355//===----------------------------------------------------------------------===//
2356
Alexey Samsonovf6246502015-04-23 01:50:45 +00002357static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
Melanie Blowerf5360d42020-05-01 10:32:06 -07002358 llvm::Value *InVal, bool IsInc,
2359 FPOptions FPFeatures) {
Alexey Samsonovf6246502015-04-23 01:50:45 +00002360 BinOpInfo BinOp;
2361 BinOp.LHS = InVal;
2362 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2363 BinOp.Ty = E->getType();
2364 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
Melanie Blowerf5360d42020-05-01 10:32:06 -07002365 BinOp.FPFeatures = FPFeatures;
Alexey Samsonovf6246502015-04-23 01:50:45 +00002366 BinOp.E = E;
2367 return BinOp;
2368}
2369
2370llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2371 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2372 llvm::Value *Amount =
2373 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2374 StringRef Name = IsInc ? "inc" : "dec";
Richard Smith9c6890a2012-11-01 22:30:59 +00002375 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00002376 case LangOptions::SOB_Defined:
Alexey Samsonovf6246502015-04-23 01:50:45 +00002377 return Builder.CreateAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00002378 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002379 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002380 return Builder.CreateNSWAdd(InVal, Amount, Name);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00002381 LLVM_FALLTHROUGH;
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002382 case LangOptions::SOB_Trapping:
2383 if (!E->canOverflow())
2384 return Builder.CreateNSWAdd(InVal, Amount, Name);
Melanie Blowerf5360d42020-05-01 10:32:06 -07002385 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2386 E, InVal, IsInc, E->getFPFeatures(CGF.getLangOpts())));
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002387 }
David Blaikie83d382b2011-09-23 05:06:16 +00002388 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00002389}
2390
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002391namespace {
2392/// Handles check and update for lastprivate conditional variables.
2393class OMPLastprivateConditionalUpdateRAII {
2394private:
2395 CodeGenFunction &CGF;
2396 const UnaryOperator *E;
2397
2398public:
2399 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2400 const UnaryOperator *E)
2401 : CGF(CGF), E(E) {}
2402 ~OMPLastprivateConditionalUpdateRAII() {
2403 if (CGF.getLangOpts().OpenMP)
2404 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2405 CGF, E->getSubExpr());
2406 }
2407};
2408} // namespace
2409
John McCalle3dc1702011-02-15 09:22:45 +00002410llvm::Value *
2411ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2412 bool isInc, bool isPre) {
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002413 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
John McCalle3dc1702011-02-15 09:22:45 +00002414 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002415 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002416 llvm::Value *value;
2417 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00002418
John McCalle3dc1702011-02-15 09:22:45 +00002419 int amount = (isInc ? 1 : -1);
Vedant Kumar175b6d12017-07-13 20:55:26 +00002420 bool isSubtraction = !isInc;
John McCalle3dc1702011-02-15 09:22:45 +00002421
David Chisnallfa35df62012-01-16 17:27:18 +00002422 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00002423 type = atomicTy->getValueType();
2424 if (isInc && type->isBooleanType()) {
2425 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2426 if (isPre) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002427 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2428 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002429 return Builder.getTrue();
2430 }
2431 // For atomic bool increment, we just store true and return it for
2432 // preincrement, do an atomic swap with true for postincrement
JF Bastien92f4ef12016-04-06 17:26:42 +00002433 return Builder.CreateAtomicRMW(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002434 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
JF Bastien92f4ef12016-04-06 17:26:42 +00002435 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002436 }
2437 // Special case for atomic increment / decrement on integers, emit
2438 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00002439 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00002440 if (!type->isBooleanType() && type->isIntegerType() &&
2441 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002442 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00002443 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002444 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002445 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2446 llvm::AtomicRMWInst::Sub;
2447 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2448 llvm::Instruction::Sub;
2449 llvm::Value *amt = CGF.EmitToMemory(
2450 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002451 llvm::Value *old =
2452 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2453 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002454 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2455 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00002456 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002457 input = value;
2458 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00002459 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2460 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00002461 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002462 Builder.CreateBr(opBB);
2463 Builder.SetInsertPoint(opBB);
2464 atomicPHI = Builder.CreatePHI(value->getType(), 2);
2465 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002466 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00002467 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002468 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002469 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00002470 }
2471
John McCalle3dc1702011-02-15 09:22:45 +00002472 // Special case of integer increment that we have to check first: bool++.
2473 // Due to promotion rules, we get:
2474 // bool++ -> bool = bool + 1
2475 // -> bool = (int)bool + 1
2476 // -> bool = ((int)bool + 1 != 0)
2477 // An interesting aspect of this is that increment is always true.
2478 // Decrement does not have this property.
2479 if (isInc && type->isBooleanType()) {
2480 value = Builder.getTrue();
2481
2482 // Most common case by far: integer increment.
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002483 } else if (type->isIntegerType()) {
Roman Lebedevb98a0c72019-11-27 17:07:06 +03002484 QualType promotedType;
2485 bool canPerformLossyDemotionCheck = false;
2486 if (type->isPromotableIntegerType()) {
2487 promotedType = CGF.getContext().getPromotedIntegerType(type);
2488 assert(promotedType != type && "Shouldn't promote to the same type.");
2489 canPerformLossyDemotionCheck = true;
2490 canPerformLossyDemotionCheck &=
2491 CGF.getContext().getCanonicalType(type) !=
2492 CGF.getContext().getCanonicalType(promotedType);
2493 canPerformLossyDemotionCheck &=
2494 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2495 type, promotedType);
2496 assert((!canPerformLossyDemotionCheck ||
2497 type->isSignedIntegerOrEnumerationType() ||
2498 promotedType->isSignedIntegerOrEnumerationType() ||
2499 ConvertType(type)->getScalarSizeInBits() ==
2500 ConvertType(promotedType)->getScalarSizeInBits()) &&
2501 "The following check expects that if we do promotion to different "
2502 "underlying canonical type, at least one of the types (either "
2503 "base or promoted) will be signed, or the bitwidths will match.");
2504 }
2505 if (CGF.SanOpts.hasOneOf(
2506 SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2507 canPerformLossyDemotionCheck) {
2508 // While `x += 1` (for `x` with width less than int) is modeled as
2509 // promotion+arithmetics+demotion, and we can catch lossy demotion with
2510 // ease; inc/dec with width less than int can't overflow because of
2511 // promotion rules, so we omit promotion+demotion, which means that we can
2512 // not catch lossy "demotion". Because we still want to catch these cases
2513 // when the sanitizer is enabled, we perform the promotion, then perform
2514 // the increment/decrement in the wider type, and finally
2515 // perform the demotion. This will catch lossy demotions.
2516
2517 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2518 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2519 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2520 // Do pass non-default ScalarConversionOpts so that sanitizer check is
2521 // emitted.
2522 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2523 ScalarConversionOpts(CGF.SanOpts));
2524
2525 // Note that signed integer inc/dec with width less than int can't
2526 // overflow because of promotion rules; we're just eliding a few steps
2527 // here.
2528 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002529 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2530 } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2531 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
Melanie Blowerf5360d42020-05-01 10:32:06 -07002532 value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2533 E, value, isInc, E->getFPFeatures(CGF.getLangOpts())));
Alexey Samsonovf6246502015-04-23 01:50:45 +00002534 } else {
2535 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00002536 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Alexey Samsonovf6246502015-04-23 01:50:45 +00002537 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002538
John McCalle3dc1702011-02-15 09:22:45 +00002539 // Next most common: pointer increment.
2540 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2541 QualType type = ptr->getPointeeType();
2542
2543 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00002544 if (const VariableArrayType *vla
2545 = CGF.getContext().getAsVariableArrayType(type)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00002546 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002547 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00002548 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00002549 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00002550 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002551 value = CGF.EmitCheckedInBoundsGEP(
2552 value, numElts, /*SignedIndices=*/false, isSubtraction,
2553 E->getExprLoc(), "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00002554
John McCalle3dc1702011-02-15 09:22:45 +00002555 // Arithmetic on function pointers (!) is just +-1.
2556 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00002557 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00002558
2559 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00002560 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002561 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2562 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002563 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2564 isSubtraction, E->getExprLoc(),
2565 "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00002566 value = Builder.CreateBitCast(value, input->getType());
2567
2568 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00002569 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00002570 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00002571 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002572 value = Builder.CreateGEP(value, amt, "incdec.ptr");
2573 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002574 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2575 isSubtraction, E->getExprLoc(),
2576 "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00002577 }
2578
2579 // Vector increment/decrement.
2580 } else if (type->isVectorType()) {
2581 if (type->hasIntegerRepresentation()) {
2582 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2583
Eli Friedman409943e2011-05-06 18:04:18 +00002584 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00002585 } else {
2586 value = Builder.CreateFAdd(
2587 value,
2588 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00002589 isInc ? "inc" : "dec");
2590 }
Anton Yartsev85129b82011-02-07 02:17:30 +00002591
John McCalle3dc1702011-02-15 09:22:45 +00002592 // Floating point.
2593 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00002594 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00002595 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002596
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002597 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002598 // Another special case: half FP increment should be done via float
Akira Hatanaka502775a2017-12-09 00:02:37 +00002599 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002600 value = Builder.CreateCall(
2601 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2602 CGF.CGM.FloatTy),
2603 input, "incdec.conv");
2604 } else {
2605 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2606 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002607 }
2608
John McCalle3dc1702011-02-15 09:22:45 +00002609 if (value->getType()->isFloatTy())
2610 amt = llvm::ConstantFP::get(VMContext,
2611 llvm::APFloat(static_cast<float>(amount)));
2612 else if (value->getType()->isDoubleTy())
2613 amt = llvm::ConstantFP::get(VMContext,
2614 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002615 else {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002616 // Remaining types are Half, LongDouble or __float128. Convert from float.
John McCalle3dc1702011-02-15 09:22:45 +00002617 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002618 bool ignored;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002619 const llvm::fltSemantics *FS;
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00002620 // Don't use getFloatTypeSemantics because Half isn't
2621 // necessarily represented using the "half" LLVM type.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002622 if (value->getType()->isFP128Ty())
2623 FS = &CGF.getTarget().getFloat128Format();
2624 else if (value->getType()->isHalfTy())
2625 FS = &CGF.getTarget().getHalfFormat();
2626 else
2627 FS = &CGF.getTarget().getLongDoubleFormat();
2628 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00002629 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002630 }
John McCalle3dc1702011-02-15 09:22:45 +00002631 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2632
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002633 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00002634 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002635 value = Builder.CreateCall(
2636 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2637 CGF.CGM.FloatTy),
2638 value, "incdec.conv");
2639 } else {
2640 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2641 }
2642 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002643
Bevin Hansson39baaab2020-01-08 11:12:55 +01002644 // Fixed-point types.
2645 } else if (type->isFixedPointType()) {
2646 // Fixed-point types are tricky. In some cases, it isn't possible to
2647 // represent a 1 or a -1 in the type at all. Piggyback off of
2648 // EmitFixedPointBinOp to avoid having to reimplement saturation.
2649 BinOpInfo Info;
2650 Info.E = E;
2651 Info.Ty = E->getType();
2652 Info.Opcode = isInc ? BO_Add : BO_Sub;
2653 Info.LHS = value;
2654 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2655 // If the type is signed, it's better to represent this as +(-1) or -(-1),
2656 // since -1 is guaranteed to be representable.
2657 if (type->isSignedFixedPointType()) {
2658 Info.Opcode = isInc ? BO_Sub : BO_Add;
2659 Info.RHS = Builder.CreateNeg(Info.RHS);
2660 }
2661 // Now, convert from our invented integer literal to the type of the unary
2662 // op. This will upscale and saturate if necessary. This value can become
2663 // undef in some cases.
2664 FixedPointSemantics SrcSema =
2665 FixedPointSemantics::GetIntegerSemantics(value->getType()
2666 ->getScalarSizeInBits(),
2667 /*IsSigned=*/true);
2668 FixedPointSemantics DstSema =
2669 CGF.getContext().getFixedPointSemantics(Info.Ty);
2670 Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema,
2671 E->getExprLoc());
2672 value = EmitFixedPointBinOp(Info);
2673
John McCalle3dc1702011-02-15 09:22:45 +00002674 // Objective-C pointer types.
2675 } else {
2676 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2677 value = CGF.EmitCastToVoidPtr(value);
2678
2679 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2680 if (!isInc) size = -size;
2681 llvm::Value *sizeValue =
2682 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2683
Richard Smith9c6890a2012-11-01 22:30:59 +00002684 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002685 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2686 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002687 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2688 /*SignedIndices=*/false, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00002689 E->getExprLoc(), "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00002690 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00002691 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002692
David Chisnallfa35df62012-01-16 17:27:18 +00002693 if (atomicPHI) {
Erik Pilkington53e43f42019-02-28 00:47:55 +00002694 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
David Chisnallfa35df62012-01-16 17:27:18 +00002695 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002696 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002697 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2698 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2699 llvm::Value *success = Pair.second;
Erik Pilkington53e43f42019-02-28 00:47:55 +00002700 atomicPHI->addIncoming(old, curBlock);
2701 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
David Chisnallfa35df62012-01-16 17:27:18 +00002702 Builder.SetInsertPoint(contBB);
2703 return isPre ? value : input;
2704 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002705
Chris Lattner05dc78c2010-06-26 22:09:34 +00002706 // Store the updated result through the lvalue.
2707 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002708 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002709 else
John McCall55e1fbc2011-06-25 02:11:03 +00002710 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002711
Chris Lattner05dc78c2010-06-26 22:09:34 +00002712 // If this is a postinc, return the value read from memory, otherwise use the
2713 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00002714 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00002715}
2716
2717
2718
Chris Lattner2da04b32007-08-24 05:35:26 +00002719Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002720 TestAndClearIgnoreResultAssign();
Cameron McInally20b8ed22019-10-14 15:35:01 +00002721 Value *Op = Visit(E->getSubExpr());
2722
2723 // Generate a unary FNeg for FP ops.
2724 if (Op->getType()->isFPOrFPVectorTy())
2725 return Builder.CreateFNeg(Op, "fneg");
2726
Chris Lattner0bf27622010-06-26 21:48:21 +00002727 // Emit unary minus with EmitSub so we handle overflow cases etc.
2728 BinOpInfo BinOp;
Cameron McInally20b8ed22019-10-14 15:35:01 +00002729 BinOp.RHS = Op;
2730 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00002731 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00002732 BinOp.Opcode = BO_Sub;
Melanie Blowerf5360d42020-05-01 10:32:06 -07002733 BinOp.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
Chris Lattner0bf27622010-06-26 21:48:21 +00002734 BinOp.E = E;
2735 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00002736}
2737
2738Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002739 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002740 Value *Op = Visit(E->getSubExpr());
2741 return Builder.CreateNot(Op, "neg");
2742}
2743
2744Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00002745 // Perform vector logical not on comparison with zero vector.
Fangrui Songfc935fc2020-06-08 09:32:30 -07002746 if (E->getType()->isVectorType() &&
2747 E->getType()->castAs<VectorType>()->getVectorKind() ==
2748 VectorType::GenericVector) {
Tanya Lattner20248222012-01-16 21:02:28 +00002749 Value *Oper = Visit(E->getSubExpr());
2750 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00002751 Value *Result;
Melanie Blowerf5360d42020-05-01 10:32:06 -07002752 if (Oper->getType()->isFPOrFPVectorTy()) {
John McCall7fac1ac2020-06-11 18:09:36 -04002753 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
2754 CGF, E->getFPFeatures(CGF.getLangOpts()));
Joey Gouly7d00f002013-02-21 11:49:56 +00002755 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
Melanie Blowerf5360d42020-05-01 10:32:06 -07002756 } else
Joey Gouly7d00f002013-02-21 11:49:56 +00002757 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00002758 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2759 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002760
Chris Lattner2da04b32007-08-24 05:35:26 +00002761 // Compare operand to zero.
2762 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002763
Chris Lattner2da04b32007-08-24 05:35:26 +00002764 // Invert value.
2765 // TODO: Could dynamically modify easy computations here. For example, if
2766 // the operand is an icmp ne, turn into icmp eq.
2767 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00002768
Anders Carlsson775640d2009-05-19 18:44:53 +00002769 // ZExt result to the expr type.
2770 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002771}
2772
Eli Friedmand7c72322010-08-05 09:58:49 +00002773Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2774 // Try folding the offsetof to a constant.
Fangrui Song407659a2018-11-30 23:41:18 +00002775 Expr::EvalResult EVResult;
2776 if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2777 llvm::APSInt Value = EVResult.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +00002778 return Builder.getInt(Value);
Fangrui Song407659a2018-11-30 23:41:18 +00002779 }
Eli Friedmand7c72322010-08-05 09:58:49 +00002780
2781 // Loop over the components of the offsetof to compute the value.
2782 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00002783 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00002784 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2785 QualType CurrentType = E->getTypeSourceInfo()->getType();
2786 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00002787 OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00002788 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00002789 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00002790 case OffsetOfNode::Array: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002791 // Compute the index
2792 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2793 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002794 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00002795 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2796
2797 // Save the element type
2798 CurrentType =
2799 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2800
2801 // Compute the element size
2802 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2803 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2804
2805 // Multiply out to compute the result
2806 Offset = Builder.CreateMul(Idx, ElemSize);
2807 break;
2808 }
2809
James Y Knight7281c352015-12-29 22:31:18 +00002810 case OffsetOfNode::Field: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002811 FieldDecl *MemberDecl = ON.getField();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002812 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
Eli Friedmand7c72322010-08-05 09:58:49 +00002813 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2814
2815 // Compute the index of the field in its parent.
2816 unsigned i = 0;
2817 // FIXME: It would be nice if we didn't have to loop here!
2818 for (RecordDecl::field_iterator Field = RD->field_begin(),
2819 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00002820 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002821 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00002822 break;
2823 }
2824 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2825
2826 // Compute the offset to the field
2827 int64_t OffsetInt = RL.getFieldOffset(i) /
2828 CGF.getContext().getCharWidth();
2829 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2830
2831 // Save the element type.
2832 CurrentType = MemberDecl->getType();
2833 break;
2834 }
Eli Friedman165301d2010-08-06 16:37:05 +00002835
James Y Knight7281c352015-12-29 22:31:18 +00002836 case OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00002837 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00002838
James Y Knight7281c352015-12-29 22:31:18 +00002839 case OffsetOfNode::Base: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002840 if (ON.getBase()->isVirtual()) {
2841 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2842 continue;
2843 }
2844
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002845 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
Eli Friedmand7c72322010-08-05 09:58:49 +00002846 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2847
2848 // Save the element type.
2849 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00002850
Eli Friedmand7c72322010-08-05 09:58:49 +00002851 // Compute the offset to the base.
2852 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2853 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002854 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2855 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00002856 break;
2857 }
2858 }
2859 Result = Builder.CreateAdd(Result, Offset);
2860 }
2861 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00002862}
2863
Peter Collingbournee190dee2011-03-11 19:24:49 +00002864/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00002865/// argument of the sizeof expression as an integer.
2866Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00002867ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2868 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00002869 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002870 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002871 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002872 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2873 if (E->isArgumentType()) {
2874 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00002875 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00002876 } else {
2877 // C99 6.5.3.4p2: If the argument is an expression of type
2878 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00002879 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002880 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002881
Sander de Smalen891af03a2018-02-03 13:55:59 +00002882 auto VlaSize = CGF.getVLASize(VAT);
2883 llvm::Value *size = VlaSize.NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002884
2885 // Scale the number of non-VLA elements by the non-VLA element size.
Sander de Smalen891af03a2018-02-03 13:55:59 +00002886 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
John McCall23c29fe2011-06-24 21:55:10 +00002887 if (!eltSize.isOne())
Sander de Smalen891af03a2018-02-03 13:55:59 +00002888 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
John McCall23c29fe2011-06-24 21:55:10 +00002889
2890 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002891 }
Alexey Bataev00396512015-07-02 03:40:19 +00002892 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2893 auto Alignment =
2894 CGF.getContext()
2895 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2896 E->getTypeOfArgument()->getPointeeType()))
2897 .getQuantity();
2898 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
Anders Carlsson30032882008-12-12 07:38:43 +00002899 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002900
Mike Stump4a3999f2009-09-09 13:00:44 +00002901 // If this isn't sizeof(vla), the result must be constant; use the constant
2902 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002903 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002904}
2905
Chris Lattner9f0ad962007-08-24 21:20:17 +00002906Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2907 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002908 if (Op->getType()->isAnyComplexType()) {
2909 // If it's an l-value, load through the appropriate subobject l-value.
2910 // Note that we have to ask E because Op might be an l-value that
2911 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002912 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002913 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2914 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002915
2916 // Otherwise, calculate and project.
2917 return CGF.EmitComplexExpr(Op, false, true).first;
2918 }
2919
Chris Lattner9f0ad962007-08-24 21:20:17 +00002920 return Visit(Op);
2921}
John McCall07bb1962010-11-16 10:08:07 +00002922
Chris Lattner9f0ad962007-08-24 21:20:17 +00002923Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2924 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002925 if (Op->getType()->isAnyComplexType()) {
2926 // If it's an l-value, load through the appropriate subobject l-value.
2927 // Note that we have to ask E because Op might be an l-value that
2928 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002929 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002930 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2931 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002932
2933 // Otherwise, calculate and project.
2934 return CGF.EmitComplexExpr(Op, true, false).second;
2935 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002936
Mike Stumpdf0fe272009-05-29 15:46:01 +00002937 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2938 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002939 if (Op->isGLValue())
2940 CGF.EmitLValue(Op);
2941 else
2942 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002943 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002944}
2945
Chris Lattner2da04b32007-08-24 05:35:26 +00002946//===----------------------------------------------------------------------===//
2947// Binary Operators
2948//===----------------------------------------------------------------------===//
2949
2950BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002951 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002952 BinOpInfo Result;
2953 Result.LHS = Visit(E->getLHS());
2954 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002955 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002956 Result.Opcode = E->getOpcode();
Benjamin Kramer3ee1ec02020-04-16 11:45:02 +02002957 Result.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
Chris Lattner2da04b32007-08-24 05:35:26 +00002958 Result.E = E;
2959 return Result;
2960}
2961
Douglas Gregor914af212010-04-23 04:16:32 +00002962LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2963 const CompoundAssignOperator *E,
2964 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002965 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002966 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002967 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002968
Eli Friedmanf0450072013-06-12 01:40:06 +00002969 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002970 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002971
Mike Stumpc63428b2009-05-22 19:07:20 +00002972 // Emit the RHS first. __block variables need to have the rhs evaluated
2973 // first, plus this should improve codegen a little.
2974 OpInfo.RHS = Visit(E->getRHS());
2975 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002976 OpInfo.Opcode = E->getOpcode();
Benjamin Kramer3ee1ec02020-04-16 11:45:02 +02002977 OpInfo.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
Mike Stumpc63428b2009-05-22 19:07:20 +00002978 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002979 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002980 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002981
Craig Topper8a13c412014-05-21 05:09:00 +00002982 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002983 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2984 QualType type = atomicTy->getValueType();
2985 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002986 !(type->isUnsignedIntegerType() &&
2987 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2988 CGF.getLangOpts().getSignedOverflowBehavior() !=
2989 LangOptions::SOB_Trapping) {
Tim Northover10e0d642019-11-07 13:36:03 +00002990 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
2991 llvm::Instruction::BinaryOps Op;
David Chisnallef78c302013-03-03 16:02:42 +00002992 switch (OpInfo.Opcode) {
2993 // We don't have atomicrmw operands for *, %, /, <<, >>
2994 case BO_MulAssign: case BO_DivAssign:
2995 case BO_RemAssign:
2996 case BO_ShlAssign:
2997 case BO_ShrAssign:
2998 break;
2999 case BO_AddAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00003000 AtomicOp = llvm::AtomicRMWInst::Add;
3001 Op = llvm::Instruction::Add;
David Chisnallef78c302013-03-03 16:02:42 +00003002 break;
3003 case BO_SubAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00003004 AtomicOp = llvm::AtomicRMWInst::Sub;
3005 Op = llvm::Instruction::Sub;
David Chisnallef78c302013-03-03 16:02:42 +00003006 break;
3007 case BO_AndAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00003008 AtomicOp = llvm::AtomicRMWInst::And;
3009 Op = llvm::Instruction::And;
David Chisnallef78c302013-03-03 16:02:42 +00003010 break;
3011 case BO_XorAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00003012 AtomicOp = llvm::AtomicRMWInst::Xor;
3013 Op = llvm::Instruction::Xor;
David Chisnallef78c302013-03-03 16:02:42 +00003014 break;
3015 case BO_OrAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00003016 AtomicOp = llvm::AtomicRMWInst::Or;
3017 Op = llvm::Instruction::Or;
David Chisnallef78c302013-03-03 16:02:42 +00003018 break;
3019 default:
3020 llvm_unreachable("Invalid compound assignment type");
3021 }
Tim Northover10e0d642019-11-07 13:36:03 +00003022 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
3023 llvm::Value *Amt = CGF.EmitToMemory(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003024 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3025 E->getExprLoc()),
3026 LHSTy);
Tim Northover10e0d642019-11-07 13:36:03 +00003027 Value *OldVal = Builder.CreateAtomicRMW(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003028 AtomicOp, LHSLV.getPointer(CGF), Amt,
JF Bastien92f4ef12016-04-06 17:26:42 +00003029 llvm::AtomicOrdering::SequentiallyConsistent);
Tim Northover10e0d642019-11-07 13:36:03 +00003030
3031 // Since operation is atomic, the result type is guaranteed to be the
3032 // same as the input in LLVM terms.
3033 Result = Builder.CreateBinOp(Op, OldVal, Amt);
David Chisnallef78c302013-03-03 16:02:42 +00003034 return LHSLV;
3035 }
3036 }
David Chisnallfa35df62012-01-16 17:27:18 +00003037 // FIXME: For floating point types, we should be saving and restoring the
3038 // floating point environment in the loop.
3039 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3040 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00003041 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00003042 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00003043 Builder.CreateBr(opBB);
3044 Builder.SetInsertPoint(opBB);
3045 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3046 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00003047 OpInfo.LHS = atomicPHI;
3048 }
David Chisnallef78c302013-03-03 16:02:42 +00003049 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00003050 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003051
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003052 SourceLocation Loc = E->getExprLoc();
3053 OpInfo.LHS =
3054 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003055
Chris Lattner3d966d62007-08-24 21:00:35 +00003056 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003057 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00003058
Roman Lebedevd677c3f2018-11-19 19:56:43 +00003059 // Convert the result back to the LHS type,
3060 // potentially with Implicit Conversion sanitizer check.
3061 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3062 Loc, ScalarConversionOpts(CGF.SanOpts));
David Chisnallfa35df62012-01-16 17:27:18 +00003063
3064 if (atomicPHI) {
Erik Pilkington53e43f42019-02-28 00:47:55 +00003065 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
David Chisnallfa35df62012-01-16 17:27:18 +00003066 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00003067 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00003068 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3069 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3070 llvm::Value *success = Pair.second;
Erik Pilkington53e43f42019-02-28 00:47:55 +00003071 atomicPHI->addIncoming(old, curBlock);
3072 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
David Chisnallfa35df62012-01-16 17:27:18 +00003073 Builder.SetInsertPoint(contBB);
3074 return LHSLV;
3075 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003076
Mike Stump4a3999f2009-09-09 13:00:44 +00003077 // Store the result value into the LHS lvalue. Bit-fields are handled
3078 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3079 // 'An assignment expression has the value of the left operand after the
3080 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003081 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00003082 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003083 else
John McCall55e1fbc2011-06-25 02:11:03 +00003084 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003085
Alexey Bataeva58da1a2019-12-27 09:44:43 -05003086 if (CGF.getLangOpts().OpenMP)
3087 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3088 E->getLHS());
Douglas Gregor914af212010-04-23 04:16:32 +00003089 return LHSLV;
3090}
3091
3092Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3093 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3094 bool Ignore = TestAndClearIgnoreResultAssign();
Simon Pilgrim30aa42e2019-05-18 12:17:15 +00003095 Value *RHS = nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003096 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3097
3098 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003099 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00003100 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003101
John McCall07bb1962010-11-16 10:08:07 +00003102 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00003103 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00003104 return RHS;
3105
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003106 // If the lvalue is non-volatile, return the computed value of the assignment.
3107 if (!LHS.isVolatileQualified())
3108 return RHS;
3109
3110 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003111 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00003112}
3113
Chris Lattner8ee6a412010-09-11 21:47:09 +00003114void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00003115 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003116 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00003117
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003118 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003119 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3120 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003121 }
Richard Smithc86a1142012-11-06 02:30:30 +00003122
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003123 const auto *BO = cast<BinaryOperator>(Ops.E);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003124 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003125 Ops.Ty->hasSignedIntegerRepresentation() &&
Vedant Kumard9191152017-05-02 23:46:56 +00003126 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3127 Ops.mayHaveIntegerOverflow()) {
Richard Smithc86a1142012-11-06 02:30:30 +00003128 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3129
Chris Lattner8ee6a412010-09-11 21:47:09 +00003130 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00003131 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00003132 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3133
Richard Smith4d1458e2012-09-08 02:08:36 +00003134 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3135 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003136 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3137 Checks.push_back(
3138 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00003139 }
Richard Smithc86a1142012-11-06 02:30:30 +00003140
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003141 if (Checks.size() > 0)
3142 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003143}
Chris Lattner3d966d62007-08-24 21:00:35 +00003144
Chris Lattner2da04b32007-08-24 05:35:26 +00003145Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003146 {
3147 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003148 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3149 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003150 Ops.Ty->isIntegerType() &&
3151 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003152 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3153 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003154 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003155 Ops.Ty->isRealFloatingType() &&
3156 Ops.mayHaveFloatDivisionByZero()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003157 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003158 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3159 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3160 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003161 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00003162 }
Will Dietz1897cb32012-11-27 15:01:55 +00003163
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003164 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
Melanie Blowerf5360d42020-05-01 10:32:06 -07003165 llvm::Value *Val;
John McCall7fac1ac2020-06-11 18:09:36 -04003166 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
Melanie Blowerf5360d42020-05-01 10:32:06 -07003167 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Yaxun Liuffb60902016-08-09 20:10:18 +00003168 if (CGF.getLangOpts().OpenCL &&
3169 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3170 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3171 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3172 // build option allows an application to specify that single precision
3173 // floating-point divide (x/y and 1/x) and sqrt used in the program
3174 // source are correctly rounded.
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003175 llvm::Type *ValTy = Val->getType();
3176 if (ValTy->isFloatTy() ||
3177 (isa<llvm::VectorType>(ValTy) &&
3178 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00003179 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003180 }
3181 return Val;
3182 }
Bevin Hansson39baaab2020-01-08 11:12:55 +01003183 else if (Ops.isFixedPointOp())
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003184 return EmitFixedPointBinOp(Ops);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003185 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003186 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3187 else
3188 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3189}
3190
3191Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3192 // Rem in C can't be a floating point type: C99 6.5.5p2.
Vedant Kumar42de3802017-02-25 00:43:39 +00003193 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3194 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003195 Ops.Ty->isIntegerType() &&
3196 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003197 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003198 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Vedant Kumar42de3802017-02-25 00:43:39 +00003199 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003200 }
3201
Eli Friedman493c34a2011-04-10 04:44:11 +00003202 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003203 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3204 else
3205 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3206}
3207
Mike Stump0c61b732009-04-01 20:28:16 +00003208Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3209 unsigned IID;
3210 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00003211
Will Dietz1897cb32012-11-27 15:01:55 +00003212 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00003213 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00003214 case BO_Add:
3215 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003216 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003217 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3218 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003219 break;
John McCalle3027922010-08-25 11:45:40 +00003220 case BO_Sub:
3221 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003222 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00003223 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3224 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003225 break;
John McCalle3027922010-08-25 11:45:40 +00003226 case BO_Mul:
3227 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003228 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00003229 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3230 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003231 break;
3232 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003233 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00003234 }
Mike Stumpd3e38852009-04-02 18:15:54 +00003235 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003236 if (isSigned)
3237 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00003238
Vedant Kumar4b62b5c2017-05-09 23:34:49 +00003239 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattnera5f58b02011-07-09 17:41:47 +00003240 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00003241
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003242 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00003243
David Blaikie43f9bb72015-05-18 22:14:03 +00003244 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Mike Stump0c61b732009-04-01 20:28:16 +00003245 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3246 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3247
Richard Smith4d1458e2012-09-08 02:08:36 +00003248 // Handle overflow with llvm.trap if no custom handler has been specified.
3249 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00003250 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00003251 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00003252 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00003253 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003254 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003255 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003256 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003257 : SanitizerKind::UnsignedIntegerOverflow;
3258 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003259 } else
Chad Rosierae229d52013-01-29 23:31:22 +00003260 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00003261 return result;
3262 }
3263
Mike Stump0c61b732009-04-01 20:28:16 +00003264 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00003265 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Duncan P. N. Exon Smith01f574c2016-08-17 03:15:29 +00003266 llvm::BasicBlock *continueBB =
3267 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
Chris Lattner8139c982010-08-07 00:20:46 +00003268 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00003269
3270 Builder.CreateCondBr(overflow, overflowBB, continueBB);
3271
David Chisnalldd84ef12010-09-17 18:29:54 +00003272 // If an overflow handler is set, then we want to call it and then use its
3273 // result, if it returns.
3274 Builder.SetInsertPoint(overflowBB);
3275
3276 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00003277 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00003278 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00003279 llvm::FunctionType *handlerTy =
3280 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
James Y Knight9871db02019-02-05 16:42:33 +00003281 llvm::FunctionCallee handler =
3282 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
David Chisnalldd84ef12010-09-17 18:29:54 +00003283
3284 // Sign extend the args to 64-bit, so that we can use the same handler for
3285 // all types of overflow.
3286 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3287 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3288
3289 // Call the handler with the two arguments, the operation, and the size of
3290 // the result.
John McCall882987f2013-02-28 19:01:20 +00003291 llvm::Value *handlerArgs[] = {
3292 lhs,
3293 rhs,
3294 Builder.getInt8(OpID),
3295 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3296 };
3297 llvm::Value *handlerResult =
3298 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00003299
3300 // Truncate the result back to the desired size.
3301 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3302 Builder.CreateBr(continueBB);
3303
Mike Stump0c61b732009-04-01 20:28:16 +00003304 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00003305 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00003306 phi->addIncoming(result, initialBB);
3307 phi->addIncoming(handlerResult, overflowBB);
3308
3309 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00003310}
Chris Lattner2da04b32007-08-24 05:35:26 +00003311
John McCall77527a82011-06-25 01:32:37 +00003312/// Emit pointer + index arithmetic.
3313static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3314 const BinOpInfo &op,
3315 bool isSubtraction) {
3316 // Must have binary (not unary) expr here. Unary pointer
3317 // increment/decrement doesn't use this path.
3318 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00003319
John McCall77527a82011-06-25 01:32:37 +00003320 Value *pointer = op.LHS;
3321 Expr *pointerOperand = expr->getLHS();
3322 Value *index = op.RHS;
3323 Expr *indexOperand = expr->getRHS();
3324
3325 // In a subtraction, the LHS is always the pointer.
3326 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3327 std::swap(pointer, index);
3328 std::swap(pointerOperand, indexOperand);
3329 }
3330
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003331 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003332
John McCall77527a82011-06-25 01:32:37 +00003333 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
Yaxun Liu26f75662016-08-19 05:17:25 +00003334 auto &DL = CGF.CGM.getDataLayout();
3335 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003336
3337 // Some versions of glibc and gcc use idioms (particularly in their malloc
3338 // routines) that add a pointer-sized integer (known to be a pointer value)
3339 // to a null pointer in order to cast the value back to an integer or as
3340 // part of a pointer alignment algorithm. This is undefined behavior, but
3341 // we'd like to be able to compile programs that use it.
3342 //
3343 // Normally, we'd generate a GEP with a null-pointer base here in response
3344 // to that code, but it's also UB to dereference a pointer created that
3345 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
3346 // generate a direct cast of the integer value to a pointer.
3347 //
3348 // The idiom (p = nullptr + N) is not met if any of the following are true:
3349 //
3350 // The operation is subtraction.
3351 // The index is not pointer-sized.
3352 // The pointer type is not byte-sized.
3353 //
3354 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3355 op.Opcode,
Fangrui Song6907ce22018-07-30 19:24:48 +00003356 expr->getLHS(),
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003357 expr->getRHS()))
3358 return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3359
Nicola Zaghen97572772019-12-13 09:55:45 +00003360 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
John McCall77527a82011-06-25 01:32:37 +00003361 // Zero-extend or sign-extend the pointer value according to
3362 // whether the index is signed or not.
Nicola Zaghen97572772019-12-13 09:55:45 +00003363 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
John McCall77527a82011-06-25 01:32:37 +00003364 "idx.ext");
3365 }
3366
3367 // If this is subtraction, negate the index.
3368 if (isSubtraction)
3369 index = CGF.Builder.CreateNeg(index, "idx.neg");
3370
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003371 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00003372 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3373 /*Accessed*/ false);
3374
John McCall77527a82011-06-25 01:32:37 +00003375 const PointerType *pointerType
3376 = pointerOperand->getType()->getAs<PointerType>();
3377 if (!pointerType) {
3378 QualType objectType = pointerOperand->getType()
3379 ->castAs<ObjCObjectPointerType>()
3380 ->getPointeeType();
3381 llvm::Value *objectSize
3382 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3383
3384 index = CGF.Builder.CreateMul(index, objectSize);
3385
3386 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3387 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3388 return CGF.Builder.CreateBitCast(result, pointer->getType());
3389 }
3390
3391 QualType elementType = pointerType->getPointeeType();
3392 if (const VariableArrayType *vla
3393 = CGF.getContext().getAsVariableArrayType(elementType)) {
3394 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003395 llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
John McCall77527a82011-06-25 01:32:37 +00003396
3397 // Effectively, the multiply by the VLA size is part of the GEP.
3398 // GEP indexes are signed, and scaling an index isn't permitted to
3399 // signed-overflow, so we use the same semantics for our explicit
3400 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003401 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003402 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3403 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3404 } else {
3405 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003406 pointer =
Vedant Kumar175b6d12017-07-13 20:55:26 +00003407 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003408 op.E->getExprLoc(), "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00003409 }
John McCall77527a82011-06-25 01:32:37 +00003410 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00003411 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003412
Mike Stump4a3999f2009-09-09 13:00:44 +00003413 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3414 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3415 // future proof.
John McCall77527a82011-06-25 01:32:37 +00003416 if (elementType->isVoidType() || elementType->isFunctionType()) {
Matt Arsenaultc6da9ec2019-10-31 08:41:37 -07003417 Value *result = CGF.EmitCastToVoidPtr(pointer);
John McCall77527a82011-06-25 01:32:37 +00003418 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3419 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00003420 }
3421
David Blaikiebbafb8a2012-03-11 07:00:24 +00003422 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00003423 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3424
Vedant Kumar175b6d12017-07-13 20:55:26 +00003425 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003426 op.E->getExprLoc(), "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00003427}
3428
Lang Hames5de91cc2012-10-02 04:45:10 +00003429// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3430// Addend. Use negMul and negAdd to negate the first operand of the Mul or
3431// the add operand respectively. This allows fmuladd to represent a*b-c, or
3432// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3433// efficient operations.
Wang, Pengfei3239b502020-01-15 19:08:38 +08003434static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
Lang Hames5de91cc2012-10-02 04:45:10 +00003435 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3436 bool negMul, bool negAdd) {
3437 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00003438
Lang Hames5de91cc2012-10-02 04:45:10 +00003439 Value *MulOp0 = MulOp->getOperand(0);
3440 Value *MulOp1 = MulOp->getOperand(1);
Craig Topper8b23b2b2019-12-30 13:24:08 -08003441 if (negMul)
3442 MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3443 if (negAdd)
3444 Addend = Builder.CreateFNeg(Addend, "neg");
Lang Hames5de91cc2012-10-02 04:45:10 +00003445
Wang, Pengfei3239b502020-01-15 19:08:38 +08003446 Value *FMulAdd = nullptr;
3447 if (Builder.getIsFPConstrained()) {
3448 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3449 "Only constrained operation should be created when Builder is in FP "
3450 "constrained mode");
3451 FMulAdd = Builder.CreateConstrainedFPCall(
3452 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3453 Addend->getType()),
3454 {MulOp0, MulOp1, Addend});
3455 } else {
3456 FMulAdd = Builder.CreateCall(
3457 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3458 {MulOp0, MulOp1, Addend});
3459 }
3460 MulOp->eraseFromParent();
Lang Hames5de91cc2012-10-02 04:45:10 +00003461
Wang, Pengfei3239b502020-01-15 19:08:38 +08003462 return FMulAdd;
Lang Hames5de91cc2012-10-02 04:45:10 +00003463}
3464
3465// Check whether it would be legal to emit an fmuladd intrinsic call to
3466// represent op and if so, build the fmuladd.
3467//
3468// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3469// Does NOT check the type of the operation - it's assumed that this function
3470// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00003471static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00003472 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3473 bool isSub=false) {
3474
3475 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3476 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3477 "Only fadd/fsub can be the root of an fmuladd.");
3478
3479 // Check whether this op is marked as fusable.
Adam Nemet049a31d2017-03-29 21:54:24 +00003480 if (!op.FPFeatures.allowFPContractWithinStatement())
Craig Topper8a13c412014-05-21 05:09:00 +00003481 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003482
3483 // We have a potentially fusable op. Look for a mul on one of the operands.
Sanjay Patela30cee62015-12-03 01:25:12 +00003484 // Also, make sure that the mul result isn't used directly. In that case,
3485 // there's no point creating a muladd operation.
3486 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3487 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3488 LHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003489 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
Sanjay Patela30cee62015-12-03 01:25:12 +00003490 }
3491 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3492 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3493 RHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003494 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
Lang Hames5de91cc2012-10-02 04:45:10 +00003495 }
3496
Wang, Pengfei3239b502020-01-15 19:08:38 +08003497 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3498 if (LHSBinOp->getIntrinsicID() ==
3499 llvm::Intrinsic::experimental_constrained_fmul &&
3500 LHSBinOp->use_empty())
3501 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3502 }
3503 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3504 if (RHSBinOp->getIntrinsicID() ==
3505 llvm::Intrinsic::experimental_constrained_fmul &&
3506 RHSBinOp->use_empty())
3507 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3508 }
3509
Craig Topper8a13c412014-05-21 05:09:00 +00003510 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003511}
3512
John McCall77527a82011-06-25 01:32:37 +00003513Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3514 if (op.LHS->getType()->isPointerTy() ||
3515 op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003516 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
John McCall77527a82011-06-25 01:32:37 +00003517
3518 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003519 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00003520 case LangOptions::SOB_Defined:
3521 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00003522 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003523 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003524 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003525 LLVM_FALLTHROUGH;
John McCall77527a82011-06-25 01:32:37 +00003526 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003527 if (CanElideOverflowCheck(CGF.getContext(), op))
3528 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
John McCall77527a82011-06-25 01:32:37 +00003529 return EmitOverflowCheckedBinOp(op);
3530 }
3531 }
Will Dietz1897cb32012-11-27 15:01:55 +00003532
Florian Hahn6f6e91d2020-05-29 20:42:22 +01003533 if (op.Ty->isConstantMatrixType()) {
3534 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3535 return MB.CreateAdd(op.LHS, op.RHS);
3536 }
3537
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003538 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003539 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3540 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003541 return EmitOverflowCheckedBinOp(op);
3542
Lang Hames5de91cc2012-10-02 04:45:10 +00003543 if (op.LHS->getType()->isFPOrFPVectorTy()) {
John McCall7fac1ac2020-06-11 18:09:36 -04003544 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
Lang Hames5de91cc2012-10-02 04:45:10 +00003545 // Try to form an fmuladd.
3546 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3547 return FMulAdd;
3548
John McCall8a8d7032020-06-01 21:02:02 -04003549 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hames5de91cc2012-10-02 04:45:10 +00003550 }
John McCall77527a82011-06-25 01:32:37 +00003551
Bevin Hansson39baaab2020-01-08 11:12:55 +01003552 if (op.isFixedPointOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003553 return EmitFixedPointBinOp(op);
Leonard Chan2044ac82019-01-16 18:13:59 +00003554
John McCall77527a82011-06-25 01:32:37 +00003555 return Builder.CreateAdd(op.LHS, op.RHS, "add");
3556}
3557
Leonard Chan2044ac82019-01-16 18:13:59 +00003558/// The resulting value must be calculated with exact precision, so the operands
3559/// may not be the same type.
Leonard Chan837da5d2019-01-16 19:53:50 +00003560Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
Leonard Chan2044ac82019-01-16 18:13:59 +00003561 using llvm::APSInt;
3562 using llvm::ConstantInt;
3563
Bevin Hansson39baaab2020-01-08 11:12:55 +01003564 // This is either a binary operation where at least one of the operands is
3565 // a fixed-point type, or a unary operation where the operand is a fixed-point
3566 // type. The result type of a binary operation is determined by
3567 // Sema::handleFixedPointConversions().
Leonard Chan2044ac82019-01-16 18:13:59 +00003568 QualType ResultTy = op.Ty;
Bevin Hansson39baaab2020-01-08 11:12:55 +01003569 QualType LHSTy, RHSTy;
3570 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
Bevin Hansson39baaab2020-01-08 11:12:55 +01003571 RHSTy = BinOp->getRHS()->getType();
Bevin Hansson313461f2020-01-08 14:01:30 +01003572 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3573 // For compound assignment, the effective type of the LHS at this point
3574 // is the computation LHS type, not the actual LHS type, and the final
3575 // result type is not the type of the expression but rather the
3576 // computation result type.
3577 LHSTy = CAO->getComputationLHSType();
3578 ResultTy = CAO->getComputationResultType();
3579 } else
3580 LHSTy = BinOp->getLHS()->getType();
Bevin Hansson39baaab2020-01-08 11:12:55 +01003581 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3582 LHSTy = UnOp->getSubExpr()->getType();
3583 RHSTy = UnOp->getSubExpr()->getType();
3584 }
Leonard Chan2044ac82019-01-16 18:13:59 +00003585 ASTContext &Ctx = CGF.getContext();
3586 Value *LHS = op.LHS;
3587 Value *RHS = op.RHS;
3588
3589 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3590 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3591 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3592 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3593
3594 // Convert the operands to the full precision type.
3595 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003596 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003597 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003598 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003599
Bevin Hansson313461f2020-01-08 14:01:30 +01003600 // Perform the actual operation.
Leonard Chan2044ac82019-01-16 18:13:59 +00003601 Value *Result;
Bevin Hansson39baaab2020-01-08 11:12:55 +01003602 switch (op.Opcode) {
Bevin Hansson313461f2020-01-08 14:01:30 +01003603 case BO_AddAssign:
Leonard Chan837da5d2019-01-16 19:53:50 +00003604 case BO_Add: {
3605 if (ResultFixedSema.isSaturated()) {
3606 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3607 ? llvm::Intrinsic::sadd_sat
3608 : llvm::Intrinsic::uadd_sat;
3609 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3610 } else {
3611 Result = Builder.CreateAdd(FullLHS, FullRHS);
3612 }
3613 break;
3614 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003615 case BO_SubAssign:
Leonard Chan837da5d2019-01-16 19:53:50 +00003616 case BO_Sub: {
3617 if (ResultFixedSema.isSaturated()) {
3618 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3619 ? llvm::Intrinsic::ssub_sat
3620 : llvm::Intrinsic::usub_sat;
3621 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3622 } else {
3623 Result = Builder.CreateSub(FullLHS, FullRHS);
3624 }
3625 break;
3626 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003627 case BO_MulAssign:
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003628 case BO_Mul: {
3629 llvm::Intrinsic::ID IID;
3630 if (ResultFixedSema.isSaturated())
3631 IID = ResultFixedSema.isSigned()
3632 ? llvm::Intrinsic::smul_fix_sat
3633 : llvm::Intrinsic::umul_fix_sat;
3634 else
3635 IID = ResultFixedSema.isSigned()
3636 ? llvm::Intrinsic::smul_fix
3637 : llvm::Intrinsic::umul_fix;
3638 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3639 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3640 break;
3641 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003642 case BO_DivAssign:
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003643 case BO_Div: {
3644 llvm::Intrinsic::ID IID;
3645 if (ResultFixedSema.isSaturated())
3646 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat
3647 : llvm::Intrinsic::udiv_fix_sat;
3648 else
3649 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix
3650 : llvm::Intrinsic::udiv_fix;
3651 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3652 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3653 break;
3654 }
Leonard Chance1d4f12019-02-21 20:50:09 +00003655 case BO_LT:
3656 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3657 : Builder.CreateICmpULT(FullLHS, FullRHS);
3658 case BO_GT:
3659 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3660 : Builder.CreateICmpUGT(FullLHS, FullRHS);
3661 case BO_LE:
3662 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3663 : Builder.CreateICmpULE(FullLHS, FullRHS);
3664 case BO_GE:
3665 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3666 : Builder.CreateICmpUGE(FullLHS, FullRHS);
3667 case BO_EQ:
3668 // For equality operations, we assume any padding bits on unsigned types are
3669 // zero'd out. They could be overwritten through non-saturating operations
3670 // that cause overflow, but this leads to undefined behavior.
3671 return Builder.CreateICmpEQ(FullLHS, FullRHS);
3672 case BO_NE:
3673 return Builder.CreateICmpNE(FullLHS, FullRHS);
Leonard Chan837da5d2019-01-16 19:53:50 +00003674 case BO_Shl:
3675 case BO_Shr:
3676 case BO_Cmp:
Leonard Chan837da5d2019-01-16 19:53:50 +00003677 case BO_LAnd:
3678 case BO_LOr:
Leonard Chan837da5d2019-01-16 19:53:50 +00003679 case BO_ShlAssign:
3680 case BO_ShrAssign:
3681 llvm_unreachable("Found unimplemented fixed point binary operation");
3682 case BO_PtrMemD:
3683 case BO_PtrMemI:
3684 case BO_Rem:
3685 case BO_Xor:
3686 case BO_And:
3687 case BO_Or:
3688 case BO_Assign:
3689 case BO_RemAssign:
3690 case BO_AndAssign:
3691 case BO_XorAssign:
3692 case BO_OrAssign:
3693 case BO_Comma:
3694 llvm_unreachable("Found unsupported binary operation for fixed point types.");
Leonard Chan2044ac82019-01-16 18:13:59 +00003695 }
3696
3697 // Convert to the result type.
3698 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003699 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003700}
3701
John McCall77527a82011-06-25 01:32:37 +00003702Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3703 // The LHS is always a pointer if either side is.
3704 if (!op.LHS->getType()->isPointerTy()) {
3705 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003706 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00003707 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00003708 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00003709 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003710 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003711 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003712 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +00003713 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003714 if (CanElideOverflowCheck(CGF.getContext(), op))
3715 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
John McCall77527a82011-06-25 01:32:37 +00003716 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00003717 }
3718 }
Will Dietz1897cb32012-11-27 15:01:55 +00003719
Florian Hahn6f6e91d2020-05-29 20:42:22 +01003720 if (op.Ty->isConstantMatrixType()) {
3721 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3722 return MB.CreateSub(op.LHS, op.RHS);
3723 }
3724
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003725 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003726 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3727 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003728 return EmitOverflowCheckedBinOp(op);
3729
Lang Hames5de91cc2012-10-02 04:45:10 +00003730 if (op.LHS->getType()->isFPOrFPVectorTy()) {
John McCall7fac1ac2020-06-11 18:09:36 -04003731 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
Lang Hames5de91cc2012-10-02 04:45:10 +00003732 // Try to form an fmuladd.
3733 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3734 return FMulAdd;
John McCall8a8d7032020-06-01 21:02:02 -04003735 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hames5de91cc2012-10-02 04:45:10 +00003736 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00003737
Bevin Hansson39baaab2020-01-08 11:12:55 +01003738 if (op.isFixedPointOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003739 return EmitFixedPointBinOp(op);
3740
John McCall77527a82011-06-25 01:32:37 +00003741 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00003742 }
Chris Lattner3d966d62007-08-24 21:00:35 +00003743
John McCall77527a82011-06-25 01:32:37 +00003744 // If the RHS is not a pointer, then we have normal pointer
3745 // arithmetic.
3746 if (!op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003747 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
Eli Friedmane381f7e2009-03-28 02:45:41 +00003748
John McCall77527a82011-06-25 01:32:37 +00003749 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00003750
John McCall77527a82011-06-25 01:32:37 +00003751 // Do the raw subtraction part.
3752 llvm::Value *LHS
3753 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3754 llvm::Value *RHS
3755 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3756 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003757
John McCall77527a82011-06-25 01:32:37 +00003758 // Okay, figure out the element size.
3759 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3760 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00003761
Craig Topper8a13c412014-05-21 05:09:00 +00003762 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00003763
3764 // For a variable-length array, this is going to be non-constant.
3765 if (const VariableArrayType *vla
3766 = CGF.getContext().getAsVariableArrayType(elementType)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00003767 auto VlaSize = CGF.getVLASize(vla);
3768 elementType = VlaSize.Type;
3769 divisor = VlaSize.NumElts;
John McCall77527a82011-06-25 01:32:37 +00003770
3771 // Scale the number of non-VLA elements by the non-VLA element size.
3772 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3773 if (!eltSize.isOne())
3774 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3775
3776 // For everything elese, we can just compute it, safe in the
3777 // assumption that Sema won't let anything through that we can't
3778 // safely compute the size of.
3779 } else {
3780 CharUnits elementSize;
3781 // Handle GCC extension for pointer arithmetic on void* and
3782 // function pointer types.
3783 if (elementType->isVoidType() || elementType->isFunctionType())
3784 elementSize = CharUnits::One();
3785 else
3786 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3787
3788 // Don't even emit the divide for element size of 1.
3789 if (elementSize.isOne())
3790 return diffInChars;
3791
3792 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00003793 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003794
Chris Lattner2e72da942011-03-01 00:03:48 +00003795 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3796 // pointer difference in C is only defined in the case where both operands
3797 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00003798 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00003799}
3800
David Tweed042e0882013-01-07 16:43:27 +00003801Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00003802 llvm::IntegerType *Ty;
3803 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3804 Ty = cast<llvm::IntegerType>(VT->getElementType());
3805 else
3806 Ty = cast<llvm::IntegerType>(LHS->getType());
3807 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00003808}
3809
Erich Keane5f0903e2020-04-17 10:44:19 -07003810Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
3811 const Twine &Name) {
3812 llvm::IntegerType *Ty;
3813 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3814 Ty = cast<llvm::IntegerType>(VT->getElementType());
3815 else
3816 Ty = cast<llvm::IntegerType>(LHS->getType());
3817
3818 if (llvm::isPowerOf2_64(Ty->getBitWidth()))
3819 return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
3820
3821 return Builder.CreateURem(
3822 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
3823}
3824
Chris Lattner2da04b32007-08-24 05:35:26 +00003825Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3826 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3827 // RHS to the same size as the LHS.
3828 Value *RHS = Ops.RHS;
3829 if (Ops.LHS->getType() != RHS->getType())
3830 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003831
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003832 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
James Molloy59802322016-08-16 09:45:36 +00003833 Ops.Ty->hasSignedIntegerRepresentation() &&
Richard Smith7939ba02019-06-25 01:45:26 +00003834 !CGF.getLangOpts().isSignedOverflowDefined() &&
Aaron Ballman6a308942020-04-21 15:37:19 -04003835 !CGF.getLangOpts().CPlusPlus20;
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003836 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3837 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3838 if (CGF.getLangOpts().OpenCL)
Erich Keane5f0903e2020-04-17 10:44:19 -07003839 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003840 else if ((SanitizeBase || SanitizeExponent) &&
3841 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003842 CodeGenFunction::SanitizerScope SanScope(&CGF);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003843 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
Vedant Kumard3a601b2017-01-30 23:38:54 +00003844 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3845 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00003846
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003847 if (SanitizeExponent) {
3848 Checks.push_back(
3849 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3850 }
3851
3852 if (SanitizeBase) {
3853 // Check whether we are shifting any non-zero bits off the top of the
3854 // integer. We only emit this check if exponent is valid - otherwise
3855 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003856 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3857 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003858 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3859 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003860 llvm::Value *PromotedWidthMinusOne =
3861 (RHS == Ops.RHS) ? WidthMinusOne
3862 : GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003863 CGF.EmitBlock(CheckShiftBase);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003864 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3865 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3866 /*NUW*/ true, /*NSW*/ true),
3867 "shl.check");
Richard Smith3e056de2012-08-25 00:32:28 +00003868 if (CGF.getLangOpts().CPlusPlus) {
3869 // In C99, we are not permitted to shift a 1 bit into the sign bit.
3870 // Under C++11's rules, shifting a 1 bit into the sign bit is
3871 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3872 // define signed left shifts, so we use the C99 and C++11 rules there).
3873 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3874 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3875 }
3876 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003877 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003878 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003879 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3880 BaseCheck->addIncoming(Builder.getTrue(), Orig);
3881 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3882 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00003883 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00003884
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003885 assert(!Checks.empty());
3886 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00003887 }
3888
Chris Lattner2da04b32007-08-24 05:35:26 +00003889 return Builder.CreateShl(Ops.LHS, RHS, "shl");
3890}
3891
3892Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3893 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3894 // RHS to the same size as the LHS.
3895 Value *RHS = Ops.RHS;
3896 if (Ops.LHS->getType() != RHS->getType())
3897 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003898
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003899 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3900 if (CGF.getLangOpts().OpenCL)
Erich Keane5f0903e2020-04-17 10:44:19 -07003901 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003902 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3903 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003904 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003905 llvm::Value *Valid =
3906 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003907 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003908 }
David Tweed042e0882013-01-07 16:43:27 +00003909
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003910 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003911 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3912 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3913}
3914
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003915enum IntrinsicType { VCMPEQ, VCMPGT };
3916// return corresponding comparison intrinsic for given vector type
3917static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3918 BuiltinType::Kind ElemKind) {
3919 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003920 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003921 case BuiltinType::Char_U:
3922 case BuiltinType::UChar:
3923 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3924 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003925 case BuiltinType::Char_S:
3926 case BuiltinType::SChar:
3927 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3928 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003929 case BuiltinType::UShort:
3930 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3931 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003932 case BuiltinType::Short:
3933 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3934 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003935 case BuiltinType::UInt:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003936 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3937 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003938 case BuiltinType::Int:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003939 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3940 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003941 case BuiltinType::ULong:
3942 case BuiltinType::ULongLong:
3943 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3944 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3945 case BuiltinType::Long:
3946 case BuiltinType::LongLong:
3947 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3948 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003949 case BuiltinType::Float:
3950 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3951 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003952 case BuiltinType::Double:
3953 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3954 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003955 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003956}
3957
Craig Topperc82f8962015-12-16 06:24:28 +00003958Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3959 llvm::CmpInst::Predicate UICmpOpc,
3960 llvm::CmpInst::Predicate SICmpOpc,
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01003961 llvm::CmpInst::Predicate FCmpOpc,
3962 bool IsSignaling) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003963 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00003964 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00003965 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00003966 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00003967 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00003968 assert(E->getOpcode() == BO_EQ ||
3969 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00003970 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3971 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00003972 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00003973 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00003974 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Leonard Chance1d4f12019-02-21 20:50:09 +00003975 BinOpInfo BOInfo = EmitBinOps(E);
3976 Value *LHS = BOInfo.LHS;
3977 Value *RHS = BOInfo.RHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003978
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003979 // If AltiVec, the comparison results in a numeric type, so we use
3980 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00003981 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003982 // constants for mapping CR6 register bits to predicate result
3983 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3984
3985 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3986
3987 // in several cases vector arguments order will be reversed
3988 Value *FirstVecArg = LHS,
3989 *SecondVecArg = RHS;
3990
Simon Pilgrime0712012019-10-02 15:31:25 +00003991 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00003992 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003993
3994 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003995 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003996 case BO_EQ:
3997 CR6 = CR6_LT;
3998 ID = GetIntrinsic(VCMPEQ, ElementKind);
3999 break;
4000 case BO_NE:
4001 CR6 = CR6_EQ;
4002 ID = GetIntrinsic(VCMPEQ, ElementKind);
4003 break;
4004 case BO_LT:
4005 CR6 = CR6_LT;
4006 ID = GetIntrinsic(VCMPGT, ElementKind);
4007 std::swap(FirstVecArg, SecondVecArg);
4008 break;
4009 case BO_GT:
4010 CR6 = CR6_LT;
4011 ID = GetIntrinsic(VCMPGT, ElementKind);
4012 break;
4013 case BO_LE:
4014 if (ElementKind == BuiltinType::Float) {
4015 CR6 = CR6_LT;
4016 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4017 std::swap(FirstVecArg, SecondVecArg);
4018 }
4019 else {
4020 CR6 = CR6_EQ;
4021 ID = GetIntrinsic(VCMPGT, ElementKind);
4022 }
4023 break;
4024 case BO_GE:
4025 if (ElementKind == BuiltinType::Float) {
4026 CR6 = CR6_LT;
4027 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4028 }
4029 else {
4030 CR6 = CR6_EQ;
4031 ID = GetIntrinsic(VCMPGT, ElementKind);
4032 std::swap(FirstVecArg, SecondVecArg);
4033 }
4034 break;
4035 }
4036
Chris Lattner2531eb42011-04-19 22:55:03 +00004037 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00004038 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
David Blaikie43f9bb72015-05-18 22:14:03 +00004039 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
Guozhi Wei3625f3e2017-10-10 20:31:27 +00004040
4041 // The result type of intrinsic may not be same as E->getType().
4042 // If E->getType() is not BoolTy, EmitScalarConversion will do the
4043 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
4044 // do nothing, if ResultTy is not i1 at the same time, it will cause
4045 // crash later.
4046 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
4047 if (ResultTy->getBitWidth() > 1 &&
4048 E->getType() == CGF.getContext().BoolTy)
4049 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004050 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4051 E->getExprLoc());
Anton Yartsev3f8f2882010-11-18 03:19:30 +00004052 }
4053
Bevin Hansson39baaab2020-01-08 11:12:55 +01004054 if (BOInfo.isFixedPointOp()) {
Leonard Chance1d4f12019-02-21 20:50:09 +00004055 Result = EmitFixedPointBinOp(BOInfo);
4056 } else if (LHS->getType()->isFPOrFPVectorTy()) {
John McCall7fac1ac2020-06-11 18:09:36 -04004057 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01004058 if (!IsSignaling)
4059 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4060 else
4061 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004062 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Craig Topperc82f8962015-12-16 06:24:28 +00004063 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00004064 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00004065 // Unsigned integers and pointers.
Piotr Padlewski07058292018-07-02 19:21:36 +00004066
4067 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4068 !isa<llvm::ConstantPointerNull>(LHS) &&
4069 !isa<llvm::ConstantPointerNull>(RHS)) {
4070
4071 // Dynamic information is required to be stripped for comparisons,
4072 // because it could leak the dynamic information. Based on comparisons
4073 // of pointers to dynamic objects, the optimizer can replace one pointer
4074 // with another, which might be incorrect in presence of invariant
4075 // groups. Comparison with null is safe because null does not carry any
4076 // dynamic information.
4077 if (LHSTy.mayBeDynamicClass())
4078 LHS = Builder.CreateStripInvariantGroup(LHS);
4079 if (RHSTy.mayBeDynamicClass())
4080 RHS = Builder.CreateStripInvariantGroup(RHS);
4081 }
4082
Craig Topperc82f8962015-12-16 06:24:28 +00004083 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00004084 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00004085
4086 // If this is a vector comparison, sign extend the result to the appropriate
4087 // vector integer type and return it (don't convert to bool).
4088 if (LHSTy->isVectorType())
4089 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00004090
Chris Lattner2da04b32007-08-24 05:35:26 +00004091 } else {
4092 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00004093 CodeGenFunction::ComplexPairTy LHS, RHS;
4094 QualType CETy;
4095 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4096 LHS = CGF.EmitComplexExpr(E->getLHS());
4097 CETy = CTy->getElementType();
4098 } else {
4099 LHS.first = Visit(E->getLHS());
4100 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4101 CETy = LHSTy;
4102 }
4103 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4104 RHS = CGF.EmitComplexExpr(E->getRHS());
4105 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4106 CTy->getElementType()) &&
4107 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00004108 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00004109 } else {
4110 RHS.first = Visit(E->getRHS());
4111 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4112 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4113 "The element types must always match.");
4114 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004115
Chris Lattner42e6b812007-08-26 16:34:22 +00004116 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00004117 if (CETy->isRealFloatingType()) {
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01004118 // As complex comparisons can only be equality comparisons, they
4119 // are never signaling comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +00004120 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4121 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00004122 } else {
4123 // Complex comparisons can only be equality comparisons. As such, signed
4124 // and unsigned opcodes are the same.
Craig Topperc82f8962015-12-16 06:24:28 +00004125 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4126 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00004127 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004128
John McCalle3027922010-08-25 11:45:40 +00004129 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00004130 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4131 } else {
John McCalle3027922010-08-25 11:45:40 +00004132 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004133 "Complex comparison other than == or != ?");
4134 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4135 }
4136 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00004137
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004138 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4139 E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00004140}
4141
4142Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004143 bool Ignore = TestAndClearIgnoreResultAssign();
4144
John McCall31168b02011-06-15 23:02:42 +00004145 Value *RHS;
4146 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004147
John McCall31168b02011-06-15 23:02:42 +00004148 switch (E->getLHS()->getType().getObjCLifetime()) {
4149 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004150 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00004151 break;
4152
4153 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004154 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00004155 break;
4156
John McCalle399e5b2016-01-27 18:32:30 +00004157 case Qualifiers::OCL_ExplicitNone:
4158 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4159 break;
4160
John McCall31168b02011-06-15 23:02:42 +00004161 case Qualifiers::OCL_Weak:
4162 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00004163 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004164 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
John McCall31168b02011-06-15 23:02:42 +00004165 break;
4166
John McCall31168b02011-06-15 23:02:42 +00004167 case Qualifiers::OCL_None:
John McCall31168b02011-06-15 23:02:42 +00004168 // __block variables need to have the rhs evaluated first, plus
4169 // this should improve codegen just a little.
4170 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00004171 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00004172
4173 // Store the value into the LHS. Bit-fields are handled specially
4174 // because the result is altered by the store, i.e., [C99 6.5.16p1]
4175 // 'An assignment expression has the value of the left operand after
4176 // the assignment...'.
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004177 if (LHS.isBitField()) {
John McCall55e1fbc2011-06-25 02:11:03 +00004178 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004179 } else {
4180 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004181 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004182 }
John McCall31168b02011-06-15 23:02:42 +00004183 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004184
4185 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004186 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00004187 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004188
John McCall07bb1962010-11-16 10:08:07 +00004189 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00004190 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00004191 return RHS;
4192
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004193 // If the lvalue is non-volatile, return the computed value of the assignment.
4194 if (!LHS.isVolatileQualified())
4195 return RHS;
4196
4197 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00004198 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00004199}
4200
4201Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004202 // Perform vector logical and on comparisons with zero vectors.
4203 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004204 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004205
Tanya Lattner20248222012-01-16 21:02:28 +00004206 Value *LHS = Visit(E->getLHS());
4207 Value *RHS = Visit(E->getRHS());
4208 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004209 if (LHS->getType()->isFPOrFPVectorTy()) {
John McCall7fac1ac2020-06-11 18:09:36 -04004210 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4211 CGF, E->getFPFeatures(CGF.getLangOpts()));
Joey Gouly7d00f002013-02-21 11:49:56 +00004212 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4213 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4214 } else {
4215 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4216 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4217 }
Tanya Lattner20248222012-01-16 21:02:28 +00004218 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004219 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004220 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004221
Chris Lattner2192fe52011-07-18 04:24:23 +00004222 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004223
Chris Lattner8b084582008-11-12 08:26:50 +00004224 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4225 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004226 bool LHSCondVal;
4227 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4228 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004229 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004230
Chris Lattner5b1964b2008-11-11 07:41:27 +00004231 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004232 // ZExt result to int or bool.
4233 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004234 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004235
Chris Lattner671fec82009-10-17 04:24:20 +00004236 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00004237 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004238 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004239 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004240
Daniel Dunbara612e792008-11-13 01:38:36 +00004241 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4242 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00004243
John McCallce1de612011-01-26 04:00:11 +00004244 CodeGenFunction::ConditionalEvaluation eval(CGF);
4245
Chris Lattner35710d182008-11-12 08:38:24 +00004246 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogner66242d62015-04-23 23:06:47 +00004247 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4248 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004249
4250 // Any edges into the ContBlock are now from an (indeterminate number of)
4251 // edges from this first condition. All of these values will be false. Start
4252 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004253 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004254 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004255 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4256 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004257 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00004258
John McCallce1de612011-01-26 04:00:11 +00004259 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00004260 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004261 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004262 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00004263 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004264
Chris Lattner2da04b32007-08-24 05:35:26 +00004265 // Reaquire the RHS block, as there may be subblocks inserted.
4266 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00004267
David Blaikie1b5adb82014-07-10 20:42:59 +00004268 // Emit an unconditional branch from this block to ContBlock.
4269 {
Devang Patel4d761272011-03-30 00:08:31 +00004270 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00004271 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00004272 CGF.EmitBlock(ContBlock);
4273 }
4274 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00004275 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004276
Anastasis Grammenosdfe8fe52018-06-21 16:53:48 +00004277 // Artificial location to preserve the scope information
4278 {
4279 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4280 PN->setDebugLoc(Builder.getCurrentDebugLocation());
4281 }
4282
Chris Lattner2da04b32007-08-24 05:35:26 +00004283 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004284 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004285}
4286
4287Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004288 // Perform vector logical or on comparisons with zero vectors.
4289 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004290 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004291
Tanya Lattner20248222012-01-16 21:02:28 +00004292 Value *LHS = Visit(E->getLHS());
4293 Value *RHS = Visit(E->getRHS());
4294 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004295 if (LHS->getType()->isFPOrFPVectorTy()) {
John McCall7fac1ac2020-06-11 18:09:36 -04004296 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4297 CGF, E->getFPFeatures(CGF.getLangOpts()));
Joey Gouly7d00f002013-02-21 11:49:56 +00004298 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4299 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4300 } else {
4301 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4302 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4303 }
Tanya Lattner20248222012-01-16 21:02:28 +00004304 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004305 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004306 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004307
Chris Lattner2192fe52011-07-18 04:24:23 +00004308 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004309
Chris Lattner8b084582008-11-12 08:26:50 +00004310 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4311 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004312 bool LHSCondVal;
4313 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4314 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004315 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004316
Chris Lattner5b1964b2008-11-11 07:41:27 +00004317 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004318 // ZExt result to int or bool.
4319 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004320 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004321
Chris Lattner671fec82009-10-17 04:24:20 +00004322 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00004323 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004324 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004325 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004326
Daniel Dunbara612e792008-11-13 01:38:36 +00004327 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4328 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00004329
John McCallce1de612011-01-26 04:00:11 +00004330 CodeGenFunction::ConditionalEvaluation eval(CGF);
4331
Chris Lattner35710d182008-11-12 08:38:24 +00004332 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00004333 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00004334 CGF.getCurrentProfileCount() -
4335 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004336
4337 // Any edges into the ContBlock are now from an (indeterminate number of)
4338 // edges from this first condition. All of these values will be true. Start
4339 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004340 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004341 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004342 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4343 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004344 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00004345
John McCallce1de612011-01-26 04:00:11 +00004346 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00004347
Chris Lattner35710d182008-11-12 08:38:24 +00004348 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00004349 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004350 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004351 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00004352
John McCallce1de612011-01-26 04:00:11 +00004353 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004354
Chris Lattner2da04b32007-08-24 05:35:26 +00004355 // Reaquire the RHS block, as there may be subblocks inserted.
4356 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00004357
Chris Lattner35710d182008-11-12 08:38:24 +00004358 // Emit an unconditional branch from this block to ContBlock. Insert an entry
4359 // into the phi node for the edge with the value of RHSCond.
4360 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00004361 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004362
Chris Lattner2da04b32007-08-24 05:35:26 +00004363 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004364 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004365}
4366
4367Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00004368 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004369 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00004370 return Visit(E->getRHS());
4371}
4372
4373//===----------------------------------------------------------------------===//
4374// Other Operators
4375//===----------------------------------------------------------------------===//
4376
Chris Lattner3fd91f832008-11-12 08:55:54 +00004377/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4378/// expression is cheap enough and side-effect-free enough to evaluate
4379/// unconditionally instead of conditionally. This is used to convert control
4380/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00004381static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4382 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00004383 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00004384 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00004385
Nick Lewycky22e55a02013-11-08 23:00:12 +00004386 // Even non-volatile automatic variables can't be evaluated unconditionally.
4387 // Referencing a thread_local may cause non-trivial initialization work to
4388 // occur. If we're inside a lambda and one of the variables is from the scope
4389 // outside the lambda, that function may have returned already. Reading its
4390 // locals is a bad idea. Also, these reads may introduce races there didn't
4391 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00004392}
4393
4394
Chris Lattner2da04b32007-08-24 05:35:26 +00004395Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00004396VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004397 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00004398
4399 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00004400 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00004401
4402 Expr *condExpr = E->getCond();
4403 Expr *lhsExpr = E->getTrueExpr();
4404 Expr *rhsExpr = E->getFalseExpr();
4405
Chris Lattnercd439292008-11-12 08:04:58 +00004406 // If the condition constant folds and can be elided, try to avoid emitting
4407 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004408 bool CondExprBool;
4409 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00004410 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00004411 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00004412
Eli Friedman27ef75b2011-10-15 02:10:40 +00004413 // If the dead side doesn't have labels we need, just emit the Live part.
4414 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00004415 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00004416 CGF.incrementProfileCounter(E);
Eli Friedman27ef75b2011-10-15 02:10:40 +00004417 Value *Result = Visit(live);
4418
4419 // If the live part is a throw expression, it acts like it has a void
4420 // type, so evaluating it returns a null Value*. However, a conditional
4421 // with non-void type must return a non-null Value*.
4422 if (!Result && !E->getType()->isVoidType())
4423 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4424
4425 return Result;
4426 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00004427 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004428
Nate Begemanabb5a732010-09-20 22:41:17 +00004429 // OpenCL: If the condition is a vector, we can treat this condition like
4430 // the select function.
Min-Yih Hsu4431d642020-05-26 06:27:34 +00004431 if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
4432 condExpr->getType()->isExtVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004433 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004434
John McCallc07a0c72011-02-17 10:25:35 +00004435 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4436 llvm::Value *LHS = Visit(lhsExpr);
4437 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00004438
Chris Lattner2192fe52011-07-18 04:24:23 +00004439 llvm::Type *condType = ConvertType(condExpr->getType());
4440 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00004441
4442 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00004443 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00004444
Chris Lattner2d6b7b92012-01-25 05:34:41 +00004445 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00004446 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Christopher Tetreault79689812020-06-01 09:55:24 -07004447 llvm::Value *tmp = Builder.CreateSExt(
4448 TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
Nate Begemanabb5a732010-09-20 22:41:17 +00004449 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00004450
Nate Begemanabb5a732010-09-20 22:41:17 +00004451 // Cast float to int to perform ANDs if necessary.
4452 llvm::Value *RHSTmp = RHS;
4453 llvm::Value *LHSTmp = LHS;
4454 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00004455 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00004456 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00004457 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4458 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4459 wasCast = true;
4460 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004461
Nate Begemanabb5a732010-09-20 22:41:17 +00004462 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4463 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4464 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4465 if (wasCast)
4466 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4467
4468 return tmp5;
4469 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004470
Erich Keane349636d2019-12-05 06:17:39 -08004471 if (condExpr->getType()->isVectorType()) {
4472 CGF.incrementProfileCounter(E);
4473
4474 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4475 llvm::Value *LHS = Visit(lhsExpr);
4476 llvm::Value *RHS = Visit(rhsExpr);
4477
4478 llvm::Type *CondType = ConvertType(condExpr->getType());
4479 auto *VecTy = cast<llvm::VectorType>(CondType);
4480 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4481
4482 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4483 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4484 }
4485
Chris Lattner3fd91f832008-11-12 08:55:54 +00004486 // If this is a really simple expression (like x ? 4 : 5), emit this as a
4487 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00004488 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00004489 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4490 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4491 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
Vedant Kumar502bbfa2017-02-25 06:35:45 +00004492 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4493
4494 CGF.incrementProfileCounter(E, StepV);
4495
John McCallc07a0c72011-02-17 10:25:35 +00004496 llvm::Value *LHS = Visit(lhsExpr);
4497 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00004498 if (!LHS) {
4499 // If the conditional has void type, make sure we return a null Value*.
4500 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00004501 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00004502 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00004503 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4504 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004505
Daniel Dunbard2a53a72008-11-12 10:13:37 +00004506 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4507 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00004508 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00004509
4510 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00004511 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4512 CGF.getProfileCount(lhsExpr));
Anders Carlsson43c52cd2009-06-04 03:00:32 +00004513
Chris Lattner2da04b32007-08-24 05:35:26 +00004514 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004515 CGF.incrementProfileCounter(E);
John McCallce1de612011-01-26 04:00:11 +00004516 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004517 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004518 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004519
Chris Lattner2da04b32007-08-24 05:35:26 +00004520 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00004521 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004522
Chris Lattner2da04b32007-08-24 05:35:26 +00004523 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00004524 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004525 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004526 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004527
John McCallce1de612011-01-26 04:00:11 +00004528 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00004529 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004530
Eli Friedmanf6c175b2009-12-07 20:25:53 +00004531 // If the LHS or RHS is a throw expression, it will be legitimately null.
4532 if (!LHS)
4533 return RHS;
4534 if (!RHS)
4535 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004536
Chris Lattner2da04b32007-08-24 05:35:26 +00004537 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00004538 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00004539 PN->addIncoming(LHS, LHSBlock);
4540 PN->addIncoming(RHS, RHSBlock);
4541 return PN;
4542}
4543
4544Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00004545 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00004546}
4547
Chris Lattnerb6a7b582007-11-30 17:56:23 +00004548Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00004549 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00004550
Richard Smitha1a808c2014-04-14 23:47:48 +00004551 if (Ty->isVariablyModifiedType())
4552 CGF.EmitVariablyModifiedType(Ty);
4553
Charles Davisc7d5c942015-09-17 20:55:33 +00004554 Address ArgValue = Address::invalid();
4555 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4556
Daniel Sanders59229dc2014-11-19 10:01:35 +00004557 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004558
James Y Knight29b5f082016-02-24 02:59:33 +00004559 // If EmitVAArg fails, emit an error.
4560 if (!ArgPtr.isValid()) {
4561 CGF.ErrorUnsupported(VE, "va_arg expression");
4562 return llvm::UndefValue::get(ArgTy);
4563 }
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004564
Mike Stumpdf0fe272009-05-29 15:46:01 +00004565 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00004566 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4567
4568 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00004569 if (ArgTy != Val->getType()) {
4570 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4571 Val = Builder.CreateIntToPtr(Val, ArgTy);
4572 else
4573 Val = Builder.CreateTrunc(Val, ArgTy);
4574 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00004575
4576 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00004577}
4578
John McCall351762c2011-02-07 10:33:21 +00004579Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4580 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00004581}
4582
Yaxun Liuc5647012016-06-08 15:11:21 +00004583// Convert a vec3 to vec4, or vice versa.
4584static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4585 Value *Src, unsigned NumElementsDst) {
4586 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02004587 static constexpr int Mask[] = {0, 1, 2, -1};
4588 return Builder.CreateShuffleVector(Src, UnV,
4589 llvm::makeArrayRef(Mask, NumElementsDst));
Yaxun Liuc5647012016-06-08 15:11:21 +00004590}
4591
Yaxun Liuea6b7962016-10-03 14:41:50 +00004592// Create cast instructions for converting LLVM value \p Src to LLVM type \p
4593// DstTy. \p Src has the same size as \p DstTy. Both are single value types
4594// but could be scalar or vectors of different lengths, and either can be
4595// pointer.
4596// There are 4 cases:
4597// 1. non-pointer -> non-pointer : needs 1 bitcast
4598// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
4599// 3. pointer -> non-pointer
4600// a) pointer -> intptr_t : needs 1 ptrtoint
4601// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
4602// 4. non-pointer -> pointer
4603// a) intptr_t -> pointer : needs 1 inttoptr
4604// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
4605// Note: for cases 3b and 4b two casts are required since LLVM casts do not
4606// allow casting directly between pointer types and non-integer non-pointer
4607// types.
4608static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4609 const llvm::DataLayout &DL,
4610 Value *Src, llvm::Type *DstTy,
4611 StringRef Name = "") {
4612 auto SrcTy = Src->getType();
4613
4614 // Case 1.
4615 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4616 return Builder.CreateBitCast(Src, DstTy, Name);
4617
4618 // Case 2.
4619 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4620 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4621
4622 // Case 3.
4623 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4624 // Case 3b.
4625 if (!DstTy->isIntegerTy())
4626 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4627 // Cases 3a and 3b.
4628 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4629 }
4630
4631 // Case 4b.
4632 if (!SrcTy->isIntegerTy())
4633 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4634 // Cases 4a and 4b.
4635 return Builder.CreateIntToPtr(Src, DstTy, Name);
4636}
4637
Tanya Lattner55808c12011-06-04 00:47:47 +00004638Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4639 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00004640 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004641
Chris Lattner2192fe52011-07-18 04:24:23 +00004642 llvm::Type *SrcTy = Src->getType();
Yaxun Liuc5647012016-06-08 15:11:21 +00004643 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4644 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4645 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4646 cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
Craig Toppera97d7e72013-07-26 06:16:11 +00004647
Yaxun Liuc5647012016-06-08 15:11:21 +00004648 // Going from vec3 to non-vec3 is a special case and requires a shuffle
4649 // vector to get a vec4, then a bitcast if the target type is different.
4650 if (NumElementsSrc == 3 && NumElementsDst != 3) {
4651 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004652
4653 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4654 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4655 DstTy);
4656 }
4657
Yaxun Liuc5647012016-06-08 15:11:21 +00004658 Src->setName("astype");
4659 return Src;
4660 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004661
Yaxun Liuc5647012016-06-08 15:11:21 +00004662 // Going from non-vec3 to vec3 is a special case and requires a bitcast
4663 // to vec4 if the original type is not vec4, then a shuffle vector to
4664 // get a vec3.
4665 if (NumElementsSrc != 3 && NumElementsDst == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004666 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
Christopher Tetreault79689812020-06-01 09:55:24 -07004667 auto *Vec4Ty = llvm::FixedVectorType::get(
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07004668 cast<llvm::VectorType>(DstTy)->getElementType(), 4);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004669 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4670 Vec4Ty);
4671 }
4672
Yaxun Liuc5647012016-06-08 15:11:21 +00004673 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4674 Src->setName("astype");
4675 return Src;
Tanya Lattner55808c12011-06-04 00:47:47 +00004676 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004677
Sylvestre Ledru4644e9a2019-10-12 15:24:00 +00004678 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4679 Src, DstTy, "astype");
Tanya Lattner55808c12011-06-04 00:47:47 +00004680}
4681
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004682Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4683 return CGF.EmitAtomicExpr(E).getScalarVal();
4684}
4685
Chris Lattner2da04b32007-08-24 05:35:26 +00004686//===----------------------------------------------------------------------===//
4687// Entry Point into this File
4688//===----------------------------------------------------------------------===//
4689
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004690/// Emit the computation of the specified expression of scalar type, ignoring
4691/// the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004692Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00004693 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004694 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00004695
David Blaikie38b25912015-02-09 19:13:51 +00004696 return ScalarExprEmitter(*this, IgnoreResultAssign)
4697 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00004698}
Chris Lattner3474c202007-08-26 06:48:56 +00004699
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004700/// Emit a conversion from the specified type to the specified destination type,
4701/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00004702Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004703 QualType DstTy,
4704 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004705 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00004706 "Invalid scalar expression to emit");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004707 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner3474c202007-08-26 06:48:56 +00004708}
Chris Lattner42e6b812007-08-26 16:34:22 +00004709
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004710/// Emit a conversion from the specified complex type to the specified
4711/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00004712Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4713 QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004714 QualType DstTy,
4715 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004716 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00004717 "Invalid complex -> scalar conversion");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004718 return ScalarExprEmitter(*this)
4719 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00004720}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00004721
Chris Lattner05dc78c2010-06-26 22:09:34 +00004722
4723llvm::Value *CodeGenFunction::
4724EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4725 bool isInc, bool isPre) {
4726 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4727}
4728
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004729LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004730 // object->isa or (*object).isa
4731 // Generate code as for: *(Class*)object
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004732
4733 Expr *BaseExpr = E->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00004734 Address Addr = Address::invalid();
John McCall086a4642010-11-24 05:12:34 +00004735 if (BaseExpr->isRValue()) {
John McCall7f416cc2015-09-08 08:05:57 +00004736 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00004737 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004738 Addr = EmitLValue(BaseExpr).getAddress(*this);
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004739 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004740
John McCall7f416cc2015-09-08 08:05:57 +00004741 // Cast the address to Class*.
4742 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4743 return MakeAddrLValue(Addr, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004744}
4745
Douglas Gregor914af212010-04-23 04:16:32 +00004746
John McCalla2342eb2010-12-05 02:00:02 +00004747LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00004748 const CompoundAssignOperator *E) {
4749 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00004750 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00004751 switch (E->getOpcode()) {
4752#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00004753 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00004754 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004755 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00004756 COMPOUND_OP(Mul);
4757 COMPOUND_OP(Div);
4758 COMPOUND_OP(Rem);
4759 COMPOUND_OP(Add);
4760 COMPOUND_OP(Sub);
4761 COMPOUND_OP(Shl);
4762 COMPOUND_OP(Shr);
4763 COMPOUND_OP(And);
4764 COMPOUND_OP(Xor);
4765 COMPOUND_OP(Or);
4766#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00004767
John McCalle3027922010-08-25 11:45:40 +00004768 case BO_PtrMemD:
4769 case BO_PtrMemI:
4770 case BO_Mul:
4771 case BO_Div:
4772 case BO_Rem:
4773 case BO_Add:
4774 case BO_Sub:
4775 case BO_Shl:
4776 case BO_Shr:
4777 case BO_LT:
4778 case BO_GT:
4779 case BO_LE:
4780 case BO_GE:
4781 case BO_EQ:
4782 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00004783 case BO_Cmp:
John McCalle3027922010-08-25 11:45:40 +00004784 case BO_And:
4785 case BO_Xor:
4786 case BO_Or:
4787 case BO_LAnd:
4788 case BO_LOr:
4789 case BO_Assign:
4790 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00004791 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00004792 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004793
Douglas Gregor914af212010-04-23 04:16:32 +00004794 llvm_unreachable("Unhandled compound assignment operator");
4795}
Vedant Kumara125eb52017-06-01 19:22:18 +00004796
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004797struct GEPOffsetAndOverflow {
4798 // The total (signed) byte offset for the GEP.
4799 llvm::Value *TotalOffset;
4800 // The offset overflow flag - true if the total offset overflows.
4801 llvm::Value *OffsetOverflows;
4802};
Vedant Kumara125eb52017-06-01 19:22:18 +00004803
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004804/// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004805/// and compute the total offset it applies from it's base pointer BasePtr.
4806/// Returns offset in bytes and a boolean flag whether an overflow happened
4807/// during evaluation.
4808static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4809 llvm::LLVMContext &VMContext,
4810 CodeGenModule &CGM,
Nikita Popov7c362b22020-02-16 17:57:18 +01004811 CGBuilderTy &Builder) {
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004812 const auto &DL = CGM.getDataLayout();
4813
4814 // The total (signed) byte offset for the GEP.
4815 llvm::Value *TotalOffset = nullptr;
4816
4817 // Was the GEP already reduced to a constant?
4818 if (isa<llvm::Constant>(GEPVal)) {
4819 // Compute the offset by casting both pointers to integers and subtracting:
4820 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4821 Value *BasePtr_int =
4822 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4823 Value *GEPVal_int =
4824 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4825 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4826 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4827 }
4828
Vedant Kumara125eb52017-06-01 19:22:18 +00004829 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004830 assert(GEP->getPointerOperand() == BasePtr &&
4831 "BasePtr must be the the base of the GEP.");
Vedant Kumara125eb52017-06-01 19:22:18 +00004832 assert(GEP->isInBounds() && "Expected inbounds GEP");
4833
Vedant Kumara125eb52017-06-01 19:22:18 +00004834 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4835
4836 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4837 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4838 auto *SAddIntrinsic =
4839 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4840 auto *SMulIntrinsic =
4841 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4842
Vedant Kumara125eb52017-06-01 19:22:18 +00004843 // The offset overflow flag - true if the total offset overflows.
4844 llvm::Value *OffsetOverflows = Builder.getFalse();
4845
4846 /// Return the result of the given binary operation.
4847 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4848 llvm::Value *RHS) -> llvm::Value * {
Davide Italiano77378e42017-06-01 23:55:18 +00004849 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
Vedant Kumara125eb52017-06-01 19:22:18 +00004850
4851 // If the operands are constants, return a constant result.
4852 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4853 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4854 llvm::APInt N;
4855 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4856 /*Signed=*/true, N);
4857 if (HasOverflow)
4858 OffsetOverflows = Builder.getTrue();
4859 return llvm::ConstantInt::get(VMContext, N);
4860 }
4861 }
4862
4863 // Otherwise, compute the result with checked arithmetic.
4864 auto *ResultAndOverflow = Builder.CreateCall(
4865 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4866 OffsetOverflows = Builder.CreateOr(
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004867 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
Vedant Kumara125eb52017-06-01 19:22:18 +00004868 return Builder.CreateExtractValue(ResultAndOverflow, 0);
4869 };
4870
4871 // Determine the total byte offset by looking at each GEP operand.
4872 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4873 GTI != GTE; ++GTI) {
4874 llvm::Value *LocalOffset;
4875 auto *Index = GTI.getOperand();
4876 // Compute the local offset contributed by this indexing step:
4877 if (auto *STy = GTI.getStructTypeOrNull()) {
4878 // For struct indexing, the local offset is the byte position of the
4879 // specified field.
4880 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4881 LocalOffset = llvm::ConstantInt::get(
4882 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4883 } else {
4884 // Otherwise this is array-like indexing. The local offset is the index
4885 // multiplied by the element size.
4886 auto *ElementSize = llvm::ConstantInt::get(
4887 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4888 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4889 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4890 }
4891
4892 // If this is the first offset, set it as the total offset. Otherwise, add
4893 // the local offset into the running total.
4894 if (!TotalOffset || TotalOffset == Zero)
4895 TotalOffset = LocalOffset;
4896 else
4897 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4898 }
4899
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004900 return {TotalOffset, OffsetOverflows};
4901}
4902
4903Value *
4904CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4905 bool SignedIndices, bool IsSubtraction,
4906 SourceLocation Loc, const Twine &Name) {
4907 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4908
4909 // If the pointer overflow sanitizer isn't enabled, do nothing.
4910 if (!SanOpts.has(SanitizerKind::PointerOverflow))
4911 return GEPVal;
4912
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004913 llvm::Type *PtrTy = Ptr->getType();
4914
4915 // Perform nullptr-and-offset check unless the nullptr is defined.
4916 bool PerformNullCheck = !NullPointerIsDefined(
4917 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4918 // Check for overflows unless the GEP got constant-folded,
4919 // and only in the default address space
4920 bool PerformOverflowCheck =
4921 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4922
4923 if (!(PerformNullCheck || PerformOverflowCheck))
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004924 return GEPVal;
4925
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004926 const auto &DL = CGM.getDataLayout();
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004927
4928 SanitizerScope SanScope(this);
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004929 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004930
4931 GEPOffsetAndOverflow EvaluatedGEP =
4932 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4933
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004934 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4935 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4936 "If the offset got constant-folded, we don't expect that there was an "
4937 "overflow.");
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004938
4939 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4940
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004941 // Common case: if the total offset is zero, and we are using C++ semantics,
4942 // where nullptr+0 is defined, don't emit a check.
4943 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
Vedant Kumara125eb52017-06-01 19:22:18 +00004944 return GEPVal;
4945
4946 // Now that we've computed the total offset, add it to the base pointer (with
4947 // wrapping semantics).
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004948 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004949 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
Vedant Kumara125eb52017-06-01 19:22:18 +00004950
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004951 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Roman Lebedevf1d33842019-09-06 14:19:04 +00004952
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004953 if (PerformNullCheck) {
4954 // In C++, if the base pointer evaluates to a null pointer value,
4955 // the only valid pointer this inbounds GEP can produce is also
4956 // a null pointer, so the offset must also evaluate to zero.
4957 // Likewise, if we have non-zero base pointer, we can not get null pointer
4958 // as a result, so the offset can not be -intptr_t(BasePtr).
4959 // In other words, both pointers are either null, or both are non-null,
4960 // or the behaviour is undefined.
4961 //
4962 // C, however, is more strict in this regard, and gives more
4963 // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4964 // So both the input to the 'gep inbounds' AND the output must not be null.
4965 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4966 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4967 auto *Valid =
4968 CGM.getLangOpts().CPlusPlus
4969 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4970 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4971 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004972 }
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004973
4974 if (PerformOverflowCheck) {
4975 // The GEP is valid if:
4976 // 1) The total offset doesn't overflow, and
4977 // 2) The sign of the difference between the computed address and the base
4978 // pointer matches the sign of the total offset.
4979 llvm::Value *ValidGEP;
4980 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
4981 if (SignedIndices) {
4982 // GEP is computed as `unsigned base + signed offset`, therefore:
4983 // * If offset was positive, then the computed pointer can not be
4984 // [unsigned] less than the base pointer, unless it overflowed.
4985 // * If offset was negative, then the computed pointer can not be
4986 // [unsigned] greater than the bas pointere, unless it overflowed.
4987 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4988 auto *PosOrZeroOffset =
4989 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
4990 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4991 ValidGEP =
4992 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
4993 } else if (!IsSubtraction) {
4994 // GEP is computed as `unsigned base + unsigned offset`, therefore the
4995 // computed pointer can not be [unsigned] less than base pointer,
4996 // unless there was an overflow.
4997 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
4998 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4999 } else {
5000 // GEP is computed as `unsigned base - unsigned offset`, therefore the
5001 // computed pointer can not be [unsigned] greater than base pointer,
5002 // unless there was an overflow.
5003 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
5004 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
5005 }
5006 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
5007 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
5008 }
Roman Lebedevf1d33842019-09-06 14:19:04 +00005009
5010 assert(!Checks.empty() && "Should have produced some checks.");
Vedant Kumara125eb52017-06-01 19:22:18 +00005011
5012 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
5013 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
5014 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
Roman Lebedevf1d33842019-09-06 14:19:04 +00005015 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
Vedant Kumara125eb52017-06-01 19:22:18 +00005016
5017 return GEPVal;
5018}