blob: c14e6d12da8219f741979bd5f52632ef5c88c8c2 [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2da04b32007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Fariborz Jahanian07ca7272009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Alexey Bataev00396512015-07-02 03:40:19 +000019#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000022#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/StmtVisitor.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000025#include "clang/Basic/TargetInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000026#include "clang/Frontend/CodeGenOptions.h"
Vedant Kumar82ee16b2017-02-25 00:43:36 +000027#include "llvm/ADT/Optional.h"
Chandler Carruth735e6d82014-03-04 11:46:22 +000028#include "llvm/IR/CFG.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Module.h"
Chris Lattner1800c182008-01-03 07:05:49 +000035#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000036
Chris Lattner2da04b32007-08-24 05:35:26 +000037using namespace clang;
38using namespace CodeGen;
39using llvm::Value;
40
41//===----------------------------------------------------------------------===//
42// Scalar Expression Emitter
43//===----------------------------------------------------------------------===//
44
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000045namespace {
Chris Lattner2da04b32007-08-24 05:35:26 +000046struct BinOpInfo {
47 Value *LHS;
48 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000049 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-06-26 21:48:21 +000050 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Lang Hames5de91cc2012-10-02 04:45:10 +000051 bool FPContractable;
Chris Lattner0bf27622010-06-26 21:48:21 +000052 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner2da04b32007-08-24 05:35:26 +000053};
54
John McCalle84af4e2010-11-13 01:35:44 +000055static bool MustVisitNullValue(const Expr *E) {
56 // If a null pointer expression's type is the C++0x nullptr_t, then
57 // it's not necessarily a simple constant and it must be evaluated
58 // for its potential side effects.
59 return E->getType()->isNullPtrType();
60}
61
Vedant Kumar82ee16b2017-02-25 00:43:36 +000062/// If \p E is a widened promoted integer, get its base (unpromoted) type.
63static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
64 const Expr *E) {
65 const Expr *Base = E->IgnoreImpCasts();
66 if (E == Base)
67 return llvm::None;
68
69 QualType BaseTy = Base->getType();
70 if (!BaseTy->isPromotableIntegerType() ||
71 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
72 return llvm::None;
73
74 return BaseTy;
75}
76
77/// Check if \p E is a widened promoted integer.
78static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
79 return getUnwidenedIntegerType(Ctx, E).hasValue();
80}
81
82/// Check if we can skip the overflow check for \p Op.
83static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
84 assert(isa<UnaryOperator>(Op.E) ||
85 isa<BinaryOperator>(Op.E) && "Expected a unary or binary operator");
86
87 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
88 return IsWidenedIntegerOp(Ctx, UO->getSubExpr());
89
90 const auto *BO = cast<BinaryOperator>(Op.E);
91 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
92 if (!OptionalLHSTy)
93 return false;
94
95 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
96 if (!OptionalRHSTy)
97 return false;
98
99 QualType LHSTy = *OptionalLHSTy;
100 QualType RHSTy = *OptionalRHSTy;
101
102 // We usually don't need overflow checks for binary operations with widened
103 // operands. Multiplication with promoted unsigned operands is a special case.
104 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
105 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
106 return true;
107
108 // The overflow check can be skipped if either one of the unpromoted types
109 // are less than half the size of the promoted type.
110 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
111 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
112 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
113}
114
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000115class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +0000116 : public StmtVisitor<ScalarExprEmitter, Value*> {
117 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +0000118 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +0000119 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +0000120 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +0000121public:
122
Mike Stumpdf0fe272009-05-29 15:46:01 +0000123 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +0000124 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +0000125 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +0000126 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000127
Chris Lattner2da04b32007-08-24 05:35:26 +0000128 //===--------------------------------------------------------------------===//
129 // Utilities
130 //===--------------------------------------------------------------------===//
131
Mike Stumpdf0fe272009-05-29 15:46:01 +0000132 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +0000133 bool I = IgnoreResultAssign;
134 IgnoreResultAssign = false;
135 return I;
136 }
Mike Stumpdf0fe272009-05-29 15:46:01 +0000137
Chris Lattner2192fe52011-07-18 04:24:23 +0000138 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +0000139 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith4d1458e2012-09-08 02:08:36 +0000140 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
141 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith69d0d262012-08-24 00:54:33 +0000142 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000143
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000144 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000145 const BinOpInfo &Info);
Richard Smithe30752c2012-10-09 19:52:38 +0000146
Nick Lewycky2d84e842013-10-02 02:29:49 +0000147 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
148 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000149 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000150
Hal Finkel64567a82014-10-04 15:26:49 +0000151 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
152 const AlignValueAttr *AVAttr = nullptr;
153 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
154 const ValueDecl *VD = DRE->getDecl();
155
156 if (VD->getType()->isReferenceType()) {
157 if (const auto *TTy =
158 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
159 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
160 } else {
161 // Assumptions for function parameters are emitted at the start of the
162 // function, so there is no need to repeat that here.
163 if (isa<ParmVarDecl>(VD))
164 return;
165
166 AVAttr = VD->getAttr<AlignValueAttr>();
167 }
168 }
169
170 if (!AVAttr)
171 if (const auto *TTy =
172 dyn_cast<TypedefType>(E->getType()))
173 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
174
175 if (!AVAttr)
176 return;
177
178 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
179 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
180 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
181 }
182
Chris Lattner2da04b32007-08-24 05:35:26 +0000183 /// EmitLoadOfLValue - Given an expression with complex type that represents a
184 /// value l-value, this method emits the address of the l-value, then loads
185 /// and returns the result.
186 Value *EmitLoadOfLValue(const Expr *E) {
Hal Finkel64567a82014-10-04 15:26:49 +0000187 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
188 E->getExprLoc());
189
190 EmitLValueAlignmentAssumption(E, V);
191 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000192 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000193
Chris Lattnere0044382007-08-26 16:42:57 +0000194 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000195 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000196 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000197
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000198 /// Emit a check that a conversion to or from a floating-point type does not
199 /// overflow.
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000200 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000201 Value *Src, QualType SrcType, QualType DstType,
202 llvm::Type *DstTy, SourceLocation Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000203
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000204 /// Emit a conversion from the specified type to the specified destination
205 /// type, both of which are LLVM scalar types.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000206 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
207 SourceLocation Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +0000208
Anastasia Stulovab02e7832015-10-05 11:27:41 +0000209 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
210 SourceLocation Loc, bool TreatBooleanAsSigned);
211
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000212 /// Emit a conversion from the specified complex type to the specified
213 /// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000214 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000215 QualType SrcTy, QualType DstTy,
216 SourceLocation Loc);
Mike Stumpab3afd82009-02-12 18:29:15 +0000217
Anders Carlsson5b944432010-05-22 17:45:10 +0000218 /// EmitNullValue - Emit a value that corresponds to null for the given type.
219 Value *EmitNullValue(QualType Ty);
220
John McCall8cb679e2010-11-15 09:13:47 +0000221 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
222 Value *EmitFloatToBoolConversion(Value *V) {
223 // Compare against 0.0 for fp scalars.
224 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
225 return Builder.CreateFCmpUNE(V, Zero, "tobool");
226 }
227
228 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
Yaxun Liu402804b2016-12-15 08:09:08 +0000229 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
230 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
231
John McCall8cb679e2010-11-15 09:13:47 +0000232 return Builder.CreateICmpNE(V, Zero, "tobool");
233 }
234
235 Value *EmitIntToBoolConversion(Value *V) {
236 // Because of the type rules of C, we often end up computing a
237 // logical value, then zero extending it to int, then wanting it
238 // as a logical value again. Optimize this common case.
239 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
240 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
241 Value *Result = ZI->getOperand(0);
242 // If there aren't any more uses, zap the instruction to save space.
243 // Note that there can be more uses, for example if this
244 // is the result of an assignment.
245 if (ZI->use_empty())
246 ZI->eraseFromParent();
247 return Result;
248 }
249 }
250
Chris Lattner2531eb42011-04-19 22:55:03 +0000251 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000252 }
253
Chris Lattner2da04b32007-08-24 05:35:26 +0000254 //===--------------------------------------------------------------------===//
255 // Visitor Methods
256 //===--------------------------------------------------------------------===//
257
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000258 Value *Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000259 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000260 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
261 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000262
Chris Lattner2da04b32007-08-24 05:35:26 +0000263 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000264 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000265 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000266 }
267 Value *VisitExpr(Expr *S);
Craig Toppera97d7e72013-07-26 06:16:11 +0000268
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000269 Value *VisitParenExpr(ParenExpr *PE) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000270 return Visit(PE->getSubExpr());
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000271 }
John McCall7c454bb2011-07-15 05:09:51 +0000272 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000273 return Visit(E->getReplacement());
John McCall7c454bb2011-07-15 05:09:51 +0000274 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000275 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
276 return Visit(GE->getResultExpr());
277 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000278
279 // Leaves.
280 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000281 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000282 }
283 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000284 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000285 }
286 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000287 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000288 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000289 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
290 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
291 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000292 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000293 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000294 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000295 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000296 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000297 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000298 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000299 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000300 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000301 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000302 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000303 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000304 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
305 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000306 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000307
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000308 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000309 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000310 }
John McCall1bf58462011-02-16 08:02:54 +0000311
John McCallfe96e0b2011-11-06 09:01:30 +0000312 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
313 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
314 }
315
John McCall1bf58462011-02-16 08:02:54 +0000316 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000317 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +0000318 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
John McCall1bf58462011-02-16 08:02:54 +0000319
320 // Otherwise, assume the mapping is the scalar directly.
John McCallc07a0c72011-02-17 10:25:35 +0000321 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000322 }
John McCall71335052012-03-10 03:05:10 +0000323
Chris Lattner2da04b32007-08-24 05:35:26 +0000324 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000325 Value *VisitDeclRefExpr(DeclRefExpr *E) {
326 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCall71335052012-03-10 03:05:10 +0000327 if (result.isReference())
Nick Lewycky2d84e842013-10-02 02:29:49 +0000328 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
329 E->getExprLoc());
John McCall71335052012-03-10 03:05:10 +0000330 return result.getValue();
Richard Smithbc6387672012-03-02 23:27:11 +0000331 }
John McCall113bee02012-03-10 09:33:50 +0000332 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000333 }
334
Mike Stump4a3999f2009-09-09 13:00:44 +0000335 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
336 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000337 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000338 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
339 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000340 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000341 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000342 return EmitLoadOfLValue(E);
343 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000344 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000345 if (E->getMethodDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +0000346 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanianff989032011-03-02 20:09:49 +0000347 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000348 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000349 }
350
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000351 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000352 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000353 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000354 return V;
355 }
356
Erik Pilkington9c42a8d2017-02-23 21:08:08 +0000357 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
358 VersionTuple Version = E->getVersion();
359
360 // If we're checking for a platform older than our minimum deployment
361 // target, we can fold the check away.
362 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
363 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
364
365 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
366 llvm::Value *Args[] = {
367 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
368 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
369 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
370 };
371
372 return CGF.EmitBuiltinAvailable(Args);
373 }
374
Chris Lattner2da04b32007-08-24 05:35:26 +0000375 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000376 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkelc4d7c822013-09-18 03:29:45 +0000377 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000378 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000379 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000380 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
381 return EmitLoadOfLValue(E);
382 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000383
Nate Begeman19351632009-10-18 20:10:40 +0000384 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000385
Richard Smith410306b2016-12-12 02:53:20 +0000386 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
387 assert(CGF.getArrayInitIndex() &&
388 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
389 return CGF.getArrayInitIndex();
390 }
391
Douglas Gregor0202cb42009-01-29 17:44:32 +0000392 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000393 return EmitNullValue(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000394 }
John McCall23c29fe2011-06-24 21:55:10 +0000395 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000396 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
John McCall23c29fe2011-06-24 21:55:10 +0000397 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000398 }
John McCall23c29fe2011-06-24 21:55:10 +0000399 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000400
401 Value *VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000402 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000403 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000404
Hal Finkel64567a82014-10-04 15:26:49 +0000405 Value *V = CGF.EmitCallExpr(E).getScalarVal();
406
407 EmitLValueAlignmentAssumption(E, V);
408 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000409 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000410
Chris Lattner04a913b2007-08-31 22:09:40 +0000411 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000412
Chris Lattner2da04b32007-08-24 05:35:26 +0000413 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000414 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000415 LValue LV = EmitLValue(E->getSubExpr());
416 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000417 }
418 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000419 LValue LV = EmitLValue(E->getSubExpr());
420 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000421 }
422 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000423 LValue LV = EmitLValue(E->getSubExpr());
424 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000425 }
426 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000427 LValue LV = EmitLValue(E->getSubExpr());
428 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000429 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000430
Alexey Samsonovf6246502015-04-23 01:50:45 +0000431 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
432 llvm::Value *InVal,
433 bool IsInc);
Anton Yartsev85129b82011-02-07 02:17:30 +0000434
Chris Lattner05dc78c2010-06-26 22:09:34 +0000435 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
436 bool isInc, bool isPre);
437
Craig Toppera97d7e72013-07-26 06:16:11 +0000438
Chris Lattner2da04b32007-08-24 05:35:26 +0000439 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000440 if (isa<MemberPointerType>(E->getType())) // never sugared
441 return CGF.CGM.getMemberPointerConstant(E);
442
John McCall7f416cc2015-09-08 08:05:57 +0000443 return EmitLValue(E->getSubExpr()).getPointer();
Chris Lattner2da04b32007-08-24 05:35:26 +0000444 }
John McCall59482722010-12-04 12:43:24 +0000445 Value *VisitUnaryDeref(const UnaryOperator *E) {
446 if (E->getType()->isVoidType())
447 return Visit(E->getSubExpr()); // the actual value should be unused
448 return EmitLoadOfLValue(E);
449 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000450 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000451 // This differs from gcc, though, most likely due to a bug in gcc.
452 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000453 return Visit(E->getSubExpr());
454 }
455 Value *VisitUnaryMinus (const UnaryOperator *E);
456 Value *VisitUnaryNot (const UnaryOperator *E);
457 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000458 Value *VisitUnaryReal (const UnaryOperator *E);
459 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000460 Value *VisitUnaryExtension(const UnaryOperator *E) {
461 return Visit(E->getSubExpr());
462 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000463
Anders Carlssona5d077d2009-04-14 16:58:56 +0000464 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000465 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000466 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000467 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000468
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000469 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
470 return Visit(DAE->getExpr());
471 }
Richard Smith852c9db2013-04-20 22:23:05 +0000472 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
473 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
474 return Visit(DIE->getExpr());
475 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000476 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
477 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000478 }
479
John McCall5d413782010-12-06 08:20:24 +0000480 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +0000481 CGF.enterFullExpression(E);
482 CodeGenFunction::RunCleanupsScope Scope(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +0000483 return Visit(E->getSubExpr());
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000484 }
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000485 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
486 return CGF.EmitCXXNewExpr(E);
487 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000488 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
489 CGF.EmitCXXDeleteExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000490 return nullptr;
Anders Carlsson81f0df92009-08-16 21:13:42 +0000491 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000492
Alp Tokercbb90342013-12-13 20:49:58 +0000493 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000494 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000495 }
496
John Wiegley6242b6a2011-04-28 00:16:57 +0000497 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
498 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
499 }
500
John Wiegleyf9f65842011-04-25 06:54:41 +0000501 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
502 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
503 }
504
Douglas Gregorad8a3362009-09-04 17:36:40 +0000505 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
506 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000507 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000508 // operator (), and the result of such a call has type void. The only
509 // effect is the evaluation of the postfix-expression before the dot or
510 // arrow.
511 CGF.EmitScalarExpr(E->getBase());
Craig Topper8a13c412014-05-21 05:09:00 +0000512 return nullptr;
Douglas Gregorad8a3362009-09-04 17:36:40 +0000513 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000514
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000515 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000516 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000517 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000518
519 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
520 CGF.EmitCXXThrowExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000521 return nullptr;
Anders Carlsson4b08db72009-10-30 01:42:31 +0000522 }
523
Sebastian Redlb67655f2010-09-10 21:04:00 +0000524 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000525 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000526 }
527
Chris Lattner2da04b32007-08-24 05:35:26 +0000528 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000529 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000530 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000531 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000532 case LangOptions::SOB_Defined:
533 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000534 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000535 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +0000536 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
537 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +0000538 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000539 if (CanElideOverflowCheck(CGF.getContext(), Ops))
540 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner51924e512010-06-26 21:25:03 +0000541 return EmitOverflowCheckedBinOp(Ops);
542 }
543 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000544
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000545 if (Ops.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000546 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
547 !CanElideOverflowCheck(CGF.getContext(), Ops))
Will Dietz1897cb32012-11-27 15:01:55 +0000548 return EmitOverflowCheckedBinOp(Ops);
549
Duncan Sands998f9d92010-02-15 16:14:01 +0000550 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner94dfae22009-06-17 06:36:24 +0000551 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner2da04b32007-08-24 05:35:26 +0000552 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
553 }
Mike Stump0c61b732009-04-01 20:28:16 +0000554 /// Create a binary op that checks for overflow.
555 /// Currently only supports +, - and *.
556 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith4d1458e2012-09-08 02:08:36 +0000557
Chris Lattner8ee6a412010-09-11 21:47:09 +0000558 // Check for undefined division and modulus behaviors.
Craig Toppera97d7e72013-07-26 06:16:11 +0000559 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner8ee6a412010-09-11 21:47:09 +0000560 llvm::Value *Zero,bool isDiv);
David Tweed042e0882013-01-07 16:43:27 +0000561 // Common helper for getting how wide LHS of shift is.
562 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner2da04b32007-08-24 05:35:26 +0000563 Value *EmitDiv(const BinOpInfo &Ops);
564 Value *EmitRem(const BinOpInfo &Ops);
565 Value *EmitAdd(const BinOpInfo &Ops);
566 Value *EmitSub(const BinOpInfo &Ops);
567 Value *EmitShl(const BinOpInfo &Ops);
568 Value *EmitShr(const BinOpInfo &Ops);
569 Value *EmitAnd(const BinOpInfo &Ops) {
570 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
571 }
572 Value *EmitXor(const BinOpInfo &Ops) {
573 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
574 }
575 Value *EmitOr (const BinOpInfo &Ops) {
576 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
577 }
578
Chris Lattner3d966d62007-08-24 21:00:35 +0000579 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000580 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
581 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000582 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000583
Chris Lattnerb6334692007-08-26 21:41:21 +0000584 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000585 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
586
587 // Binary operators and binary compound assignment operators.
588#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000589 Value *VisitBin ## OP(const BinaryOperator *E) { \
590 return Emit ## OP(EmitBinOps(E)); \
591 } \
592 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
593 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000594 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000595 HANDLEBINOP(Mul)
596 HANDLEBINOP(Div)
597 HANDLEBINOP(Rem)
598 HANDLEBINOP(Add)
599 HANDLEBINOP(Sub)
600 HANDLEBINOP(Shl)
601 HANDLEBINOP(Shr)
602 HANDLEBINOP(And)
603 HANDLEBINOP(Xor)
604 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000605#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000606
Chris Lattner2da04b32007-08-24 05:35:26 +0000607 // Comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +0000608 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
609 llvm::CmpInst::Predicate SICmpOpc,
610 llvm::CmpInst::Predicate FCmpOpc);
Chris Lattner2da04b32007-08-24 05:35:26 +0000611#define VISITCOMP(CODE, UI, SI, FP) \
612 Value *VisitBin##CODE(const BinaryOperator *E) { \
613 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
614 llvm::FCmpInst::FP); }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000615 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
616 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
617 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
618 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
619 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
620 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner2da04b32007-08-24 05:35:26 +0000621#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000622
Chris Lattner2da04b32007-08-24 05:35:26 +0000623 Value *VisitBinAssign (const BinaryOperator *E);
624
625 Value *VisitBinLAnd (const BinaryOperator *E);
626 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000627 Value *VisitBinComma (const BinaryOperator *E);
628
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000629 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
630 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
631
Chris Lattner2da04b32007-08-24 05:35:26 +0000632 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000633 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000634 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000635 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000636 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000637 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
638 return CGF.EmitObjCStringLiteral(E);
639 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000640 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
641 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000642 }
643 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
644 return CGF.EmitObjCArrayLiteral(E);
645 }
646 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
647 return CGF.EmitObjCDictionaryLiteral(E);
648 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000649 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000650 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000651};
652} // end anonymous namespace.
653
654//===----------------------------------------------------------------------===//
655// Utilities
656//===----------------------------------------------------------------------===//
657
Chris Lattnere0044382007-08-26 16:42:57 +0000658/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000659/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000660Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000661 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000662
John McCall8cb679e2010-11-15 09:13:47 +0000663 if (SrcType->isRealFloatingType())
664 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000665
John McCall7a9aac22010-08-23 01:21:21 +0000666 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
667 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000668
Daniel Dunbaref957f32008-08-25 10:38:11 +0000669 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000670 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000671
John McCall8cb679e2010-11-15 09:13:47 +0000672 if (isa<llvm::IntegerType>(Src->getType()))
673 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000674
John McCall8cb679e2010-11-15 09:13:47 +0000675 assert(isa<llvm::PointerType>(Src->getType()));
Yaxun Liu402804b2016-12-15 08:09:08 +0000676 return EmitPointerToBoolConversion(Src, SrcType);
Chris Lattnere0044382007-08-26 16:42:57 +0000677}
678
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000679void ScalarExprEmitter::EmitFloatConversionCheck(
680 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
681 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000682 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000683 using llvm::APFloat;
684 using llvm::APSInt;
685
686 llvm::Type *SrcTy = Src->getType();
687
Craig Topper8a13c412014-05-21 05:09:00 +0000688 llvm::Value *Check = nullptr;
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000689 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
690 // Integer to floating-point. This can fail for unsigned short -> __half
691 // or unsigned __int128 -> float.
692 assert(DstType->isFloatingType());
693 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
694
695 APFloat LargestFloat =
696 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
697 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
698
699 bool IsExact;
700 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
701 &IsExact) != APFloat::opOK)
702 // The range of representable values of this floating point type includes
703 // all values of this integer type. Don't need an overflow check.
704 return;
705
706 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
707 if (SrcIsUnsigned)
708 Check = Builder.CreateICmpULE(Src, Max);
709 else {
710 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
711 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
712 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
713 Check = Builder.CreateAnd(GE, LE);
714 }
715 } else {
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000716 const llvm::fltSemantics &SrcSema =
717 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000718 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith2b01d502013-03-27 23:20:25 +0000719 // Floating-point to integer. This has undefined behavior if the source is
720 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
721 // to an integer).
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000722 unsigned Width = CGF.getContext().getIntWidth(DstType);
723 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
724
725 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000726 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000727 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
728 APFloat::opOverflow)
729 // Don't need an overflow check for lower bound. Just check for
730 // -Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000731 MinSrc = APFloat::getInf(SrcSema, true);
732 else
733 // Find the largest value which is too small to represent (before
734 // truncation toward zero).
735 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000736
737 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000738 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000739 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
740 APFloat::opOverflow)
741 // Don't need an overflow check for upper bound. Just check for
742 // +Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000743 MaxSrc = APFloat::getInf(SrcSema, false);
744 else
745 // Find the smallest value which is too large to represent (before
746 // truncation toward zero).
747 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000748
Richard Smith2b01d502013-03-27 23:20:25 +0000749 // If we're converting from __half, convert the range to float to match
750 // the type of src.
751 if (OrigSrcType->isHalfType()) {
752 const llvm::fltSemantics &Sema =
753 CGF.getContext().getFloatTypeSemantics(SrcType);
754 bool IsInexact;
755 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
756 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
757 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000758
Richard Smith4af40c42013-03-19 00:01:12 +0000759 llvm::Value *GE =
760 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
761 llvm::Value *LE =
762 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
763 Check = Builder.CreateAnd(GE, LE);
764 } else {
Richard Smith2b01d502013-03-27 23:20:25 +0000765 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
766 //
767 // Floating-point to floating-point. This has undefined behavior if the
768 // source is not in the range of representable values of the destination
769 // type. The C and C++ standards are spectacularly unclear here. We
770 // diagnose finite out-of-range conversions, but allow infinities and NaNs
771 // to convert to the corresponding value in the smaller type.
772 //
773 // C11 Annex F gives all such conversions defined behavior for IEC 60559
774 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
775 // does not.
776
777 // Converting from a lower rank to a higher rank can never have
778 // undefined behavior, since higher-rank types must have a superset
779 // of values of lower-rank types.
780 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
781 return;
782
783 assert(!OrigSrcType->isHalfType() &&
784 "should not check conversion from __half, it has the lowest rank");
785
786 const llvm::fltSemantics &DstSema =
787 CGF.getContext().getFloatTypeSemantics(DstType);
788 APFloat MinBad = APFloat::getLargest(DstSema, false);
789 APFloat MaxBad = APFloat::getInf(DstSema, false);
790
791 bool IsInexact;
792 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
793 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
794
795 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
796 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smith4af40c42013-03-19 00:01:12 +0000797 llvm::Value *GE =
Richard Smith2b01d502013-03-27 23:20:25 +0000798 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smith4af40c42013-03-19 00:01:12 +0000799 llvm::Value *LE =
Richard Smith2b01d502013-03-27 23:20:25 +0000800 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
801 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smith4af40c42013-03-19 00:01:12 +0000802 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000803 }
804
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000805 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
806 CGF.EmitCheckTypeDescriptor(OrigSrcType),
807 CGF.EmitCheckTypeDescriptor(DstType)};
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000808 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000809 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000810}
811
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000812/// Emit a conversion from the specified type to the specified destination type,
813/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000814Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000815 QualType DstType,
816 SourceLocation Loc) {
Anastasia Stulovab02e7832015-10-05 11:27:41 +0000817 return EmitScalarConversion(Src, SrcType, DstType, Loc, false);
818}
819
820Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
821 QualType DstType,
822 SourceLocation Loc,
823 bool TreatBooleanAsSigned) {
Chris Lattner0f398c42008-07-26 22:37:01 +0000824 SrcType = CGF.getContext().getCanonicalType(SrcType);
825 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +0000826 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +0000827
Craig Topper8a13c412014-05-21 05:09:00 +0000828 if (DstType->isVoidType()) return nullptr;
Mike Stump4a3999f2009-09-09 13:00:44 +0000829
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000830 llvm::Value *OrigSrc = Src;
831 QualType OrigSrcType = SrcType;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000832 llvm::Type *SrcTy = Src->getType();
833
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000834 // Handle conversions to bool first, they are special: comparisons against 0.
835 if (DstType->isBooleanType())
836 return EmitConversionToBool(Src, SrcType);
837
838 llvm::Type *DstTy = ConvertType(DstType);
839
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000840 // Cast from half through float if half isn't a native type.
841 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
842 // Cast to FP using the intrinsic if the half type itself isn't supported.
843 if (DstTy->isFloatingPointTy()) {
844 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns)
845 return Builder.CreateCall(
846 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
847 Src);
848 } else {
849 // Cast to other types through float, using either the intrinsic or FPExt,
850 // depending on whether the half type itself is supported
851 // (as opposed to operations on half, available with NativeHalfType).
852 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
853 Src = Builder.CreateCall(
854 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
855 CGF.CGM.FloatTy),
856 Src);
857 } else {
858 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
859 }
860 SrcType = CGF.getContext().FloatTy;
861 SrcTy = CGF.FloatTy;
862 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000863 }
864
Chris Lattner3474c202007-08-26 06:48:56 +0000865 // Ignore conversions like int -> uint.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000866 if (SrcTy == DstTy)
Chris Lattner3474c202007-08-26 06:48:56 +0000867 return Src;
868
Mike Stump4a3999f2009-09-09 13:00:44 +0000869 // Handle pointer conversions next: pointers can only be converted to/from
870 // other pointers and integers. Check for pointer types in terms of LLVM, as
871 // some native types (like Obj-C id) may map to a pointer type.
Yaxun Liu26f75662016-08-19 05:17:25 +0000872 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000873 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000874 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +0000875 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +0000876
Chris Lattner3474c202007-08-26 06:48:56 +0000877 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000878 // First, convert to the correct width so that we control the kind of
879 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +0000880 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000881 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000882 llvm::Value* IntResult =
883 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
884 // Then, cast to pointer.
885 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000886 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000887
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000888 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000889 // Must be an ptr to int cast.
890 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +0000891 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000892 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000893
Nate Begemance4d7fc2008-04-18 23:10:10 +0000894 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +0000895 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
George Burgess IVdf1ed002016-01-13 01:52:39 +0000896 // Sema should add casts to make sure that the source expression's type is
897 // the same as the vector's element type (sans qualifiers)
898 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
899 SrcType.getTypePtr() &&
900 "Splatted expr doesn't match with vector element type?");
Nate Begemanb699c9b2009-01-18 06:42:49 +0000901
Nate Begemanb699c9b2009-01-18 06:42:49 +0000902 // Splat the element across to all elements
Craig Topperf2f1a092016-07-08 02:17:35 +0000903 unsigned NumElements = DstTy->getVectorNumElements();
George Burgess IVdf1ed002016-01-13 01:52:39 +0000904 return Builder.CreateVectorSplat(NumElements, Src, "splat");
Nate Begemanb699c9b2009-01-18 06:42:49 +0000905 }
Nate Begeman330aaa72007-12-30 02:59:45 +0000906
Chris Lattner6cba8e92008-02-02 04:51:41 +0000907 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000908 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner6cba8e92008-02-02 04:51:41 +0000909 isa<llvm::VectorType>(DstTy))
Anders Carlssona297e7a2007-12-05 07:36:10 +0000910 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stump4a3999f2009-09-09 13:00:44 +0000911
Chris Lattner3474c202007-08-26 06:48:56 +0000912 // Finally, we have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +0000913 Value *Res = nullptr;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000914 llvm::Type *ResTy = DstTy;
915
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000916 // An overflowing conversion has undefined behavior if either the source type
917 // or the destination type is a floating-point type.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000918 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000919 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000920 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
921 Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000922
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000923 // Cast to half through float if half isn't a native type.
924 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
925 // Make sure we cast in a single step if from another FP type.
926 if (SrcTy->isFloatingPointTy()) {
927 // Use the intrinsic if the half type itself isn't supported
928 // (as opposed to operations on half, available with NativeHalfType).
929 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns)
930 return Builder.CreateCall(
931 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
932 // If the half type is supported, just use an fptrunc.
933 return Builder.CreateFPTrunc(Src, DstTy);
934 }
Chris Lattnerece04092012-02-07 00:39:47 +0000935 DstTy = CGF.FloatTy;
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000936 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000937
938 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000939 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anastasia Stulovab02e7832015-10-05 11:27:41 +0000940 if (SrcType->isBooleanType() && TreatBooleanAsSigned) {
941 InputSigned = true;
942 }
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000943 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000944 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000945 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000946 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000947 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000948 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
949 } else if (isa<llvm::IntegerType>(DstTy)) {
950 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000951 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000952 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000953 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000954 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
955 } else {
956 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
957 "Unknown real conversion");
958 if (DstTy->getTypeID() < SrcTy->getTypeID())
959 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
960 else
961 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000962 }
963
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000964 if (DstTy != ResTy) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000965 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
966 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
967 Res = Builder.CreateCall(
Tim Northover6dbcbac2014-07-17 10:51:31 +0000968 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
969 Res);
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000970 } else {
971 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
972 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000973 }
974
975 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +0000976}
977
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000978/// Emit a conversion from the specified complex type to the specified
979/// destination type, where the destination type is an LLVM scalar type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000980Value *ScalarExprEmitter::EmitComplexToScalarConversion(
981 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
982 SourceLocation Loc) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000983 // Get the source element type.
John McCall47fb9502013-03-07 21:37:08 +0000984 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +0000985
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000986 // Handle conversions to bool first, they are special: comparisons against 0.
987 if (DstTy->isBooleanType()) {
988 // Complex != 0 -> (Real != 0) | (Imag != 0)
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000989 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
990 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000991 return Builder.CreateOr(Src.first, Src.second, "tobool");
992 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000993
Chris Lattner42e6b812007-08-26 16:34:22 +0000994 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
995 // the imaginary part of the complex value is discarded and the value of the
996 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +0000997 // corresponding real type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000998 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +0000999}
1000
Anders Carlsson5b944432010-05-22 17:45:10 +00001001Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001002 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlsson5b944432010-05-22 17:45:10 +00001003}
Chris Lattner42e6b812007-08-26 16:34:22 +00001004
Richard Smithe30752c2012-10-09 19:52:38 +00001005/// \brief Emit a sanitization check for the given "binary" operation (which
1006/// might actually be a unary increment which has been lowered to a binary
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001007/// operation). The check passes if all values in \p Checks (which are \c i1),
1008/// are \c true.
1009void ScalarExprEmitter::EmitBinOpCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001010 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001011 assert(CGF.IsSanitizerScope);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001012 SanitizerHandler Check;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001013 SmallVector<llvm::Constant *, 4> StaticData;
1014 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smithe30752c2012-10-09 19:52:38 +00001015
1016 BinaryOperatorKind Opcode = Info.Opcode;
1017 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1018 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1019
1020 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1021 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1022 if (UO && UO->getOpcode() == UO_Minus) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001023 Check = SanitizerHandler::NegateOverflow;
Richard Smithe30752c2012-10-09 19:52:38 +00001024 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1025 DynamicData.push_back(Info.RHS);
1026 } else {
1027 if (BinaryOperator::isShiftOp(Opcode)) {
1028 // Shift LHS negative or too large, or RHS out of bounds.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001029 Check = SanitizerHandler::ShiftOutOfBounds;
Richard Smithe30752c2012-10-09 19:52:38 +00001030 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1031 StaticData.push_back(
1032 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1033 StaticData.push_back(
1034 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1035 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1036 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001037 Check = SanitizerHandler::DivremOverflow;
Will Dietzcefb4482013-01-07 22:25:52 +00001038 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001039 } else {
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001040 // Arithmetic overflow (+, -, *).
Richard Smithe30752c2012-10-09 19:52:38 +00001041 switch (Opcode) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001042 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1043 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1044 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
Richard Smithe30752c2012-10-09 19:52:38 +00001045 default: llvm_unreachable("unexpected opcode for bin op check");
1046 }
Will Dietzcefb4482013-01-07 22:25:52 +00001047 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001048 }
1049 DynamicData.push_back(Info.LHS);
1050 DynamicData.push_back(Info.RHS);
1051 }
1052
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001053 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
Richard Smithe30752c2012-10-09 19:52:38 +00001054}
1055
Chris Lattner2da04b32007-08-24 05:35:26 +00001056//===----------------------------------------------------------------------===//
1057// Visitor Methods
1058//===----------------------------------------------------------------------===//
1059
1060Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001061 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +00001062 if (E->getType()->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001063 return nullptr;
Owen Anderson7ec07a52009-07-30 23:11:26 +00001064 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +00001065}
1066
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001067Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +00001068 // Vector Mask Case
Craig Topperb3174a82016-05-18 04:11:25 +00001069 if (E->getNumSubExprs() == 2) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00001070 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1071 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1072 Value *Mask;
Craig Toppera97d7e72013-07-26 06:16:11 +00001073
Chris Lattner2192fe52011-07-18 04:24:23 +00001074 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +00001075 unsigned LHSElts = LTy->getNumElements();
1076
Craig Topperb3174a82016-05-18 04:11:25 +00001077 Mask = RHS;
Craig Toppera97d7e72013-07-26 06:16:11 +00001078
Chris Lattner2192fe52011-07-18 04:24:23 +00001079 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001080
Nate Begemana0110022010-06-08 00:16:34 +00001081 // Mask off the high bits of each shuffle index.
Benjamin Kramer99383102015-07-28 16:25:32 +00001082 Value *MaskBits =
1083 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
Nate Begemana0110022010-06-08 00:16:34 +00001084 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Toppera97d7e72013-07-26 06:16:11 +00001085
Nate Begemana0110022010-06-08 00:16:34 +00001086 // newv = undef
1087 // mask = mask & maskbits
1088 // for each elt
1089 // n = extract mask i
1090 // x = extract val n
1091 // newv = insert newv, x, i
Chris Lattner2192fe52011-07-18 04:24:23 +00001092 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper18243fb2013-07-27 05:00:42 +00001093 MTy->getNumElements());
Nate Begemana0110022010-06-08 00:16:34 +00001094 Value* NewV = llvm::UndefValue::get(RTy);
1095 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Michael J. Spencerdd597752014-05-31 00:22:12 +00001096 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman1fa36052012-04-05 21:48:40 +00001097 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Toppera97d7e72013-07-26 06:16:11 +00001098
Nate Begemana0110022010-06-08 00:16:34 +00001099 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +00001100 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +00001101 }
1102 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001103 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001104
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001105 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1106 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Toppera97d7e72013-07-26 06:16:11 +00001107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001108 SmallVector<llvm::Constant*, 32> indices;
Craig Topper0ed37bd2013-08-01 04:51:48 +00001109 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper50ad5b72013-08-03 17:40:38 +00001110 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1111 // Check for -1 and output it as undef in the IR.
1112 if (Idx.isSigned() && Idx.isAllOnesValue())
1113 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1114 else
1115 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begemana0110022010-06-08 00:16:34 +00001116 }
1117
Chris Lattner91c08ad2011-02-15 00:14:06 +00001118 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001119 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1120}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001121
1122Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1123 QualType SrcType = E->getSrcExpr()->getType(),
1124 DstType = E->getType();
1125
1126 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1127
1128 SrcType = CGF.getContext().getCanonicalType(SrcType);
1129 DstType = CGF.getContext().getCanonicalType(DstType);
1130 if (SrcType == DstType) return Src;
1131
1132 assert(SrcType->isVectorType() &&
1133 "ConvertVector source type must be a vector");
1134 assert(DstType->isVectorType() &&
1135 "ConvertVector destination type must be a vector");
1136
1137 llvm::Type *SrcTy = Src->getType();
1138 llvm::Type *DstTy = ConvertType(DstType);
1139
1140 // Ignore conversions like int -> uint.
1141 if (SrcTy == DstTy)
1142 return Src;
1143
1144 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1145 DstEltType = DstType->getAs<VectorType>()->getElementType();
1146
1147 assert(SrcTy->isVectorTy() &&
1148 "ConvertVector source IR type must be a vector");
1149 assert(DstTy->isVectorTy() &&
1150 "ConvertVector destination IR type must be a vector");
1151
1152 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1153 *DstEltTy = DstTy->getVectorElementType();
1154
1155 if (DstEltType->isBooleanType()) {
1156 assert((SrcEltTy->isFloatingPointTy() ||
1157 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1158
1159 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1160 if (SrcEltTy->isFloatingPointTy()) {
1161 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1162 } else {
1163 return Builder.CreateICmpNE(Src, Zero, "tobool");
1164 }
1165 }
1166
1167 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001168 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001169
1170 if (isa<llvm::IntegerType>(SrcEltTy)) {
1171 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1172 if (isa<llvm::IntegerType>(DstEltTy))
1173 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1174 else if (InputSigned)
1175 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1176 else
1177 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1178 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1179 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1180 if (DstEltType->isSignedIntegerOrEnumerationType())
1181 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1182 else
1183 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1184 } else {
1185 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1186 "Unknown real conversion");
1187 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1188 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1189 else
1190 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1191 }
1192
1193 return Res;
1194}
1195
Eli Friedmancb422f12009-11-26 03:22:21 +00001196Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith5fab0c92011-12-28 19:48:30 +00001197 llvm::APSInt Value;
1198 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedmancb422f12009-11-26 03:22:21 +00001199 if (E->isArrow())
1200 CGF.EmitScalarExpr(E->getBase());
1201 else
1202 EmitLValue(E->getBase());
Richard Smith5fab0c92011-12-28 19:48:30 +00001203 return Builder.getInt(Value);
Eli Friedmancb422f12009-11-26 03:22:21 +00001204 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001205
Eli Friedmancb422f12009-11-26 03:22:21 +00001206 return EmitLoadOfLValue(E);
1207}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001208
Chris Lattner2da04b32007-08-24 05:35:26 +00001209Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001210 TestAndClearIgnoreResultAssign();
1211
Chris Lattner2da04b32007-08-24 05:35:26 +00001212 // Emit subscript expressions in rvalue context's. For most cases, this just
1213 // loads the lvalue formed by the subscript expr. However, we have to be
1214 // careful, because the base of a vector subscript is occasionally an rvalue,
1215 // so we can't get it as an lvalue.
1216 if (!E->getBase()->getType()->isVectorType())
1217 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001218
Chris Lattner2da04b32007-08-24 05:35:26 +00001219 // Handle the vector case. The base must be a vector, the index must be an
1220 // integer value.
1221 Value *Base = Visit(E->getBase());
1222 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001223 QualType IdxTy = E->getIdx()->getType();
1224
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001225 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001226 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1227
Chris Lattner2da04b32007-08-24 05:35:26 +00001228 return Builder.CreateExtractElement(Base, Idx, "vecext");
1229}
1230
Nate Begeman19351632009-10-18 20:10:40 +00001231static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +00001232 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +00001233 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001234 if (MV == -1)
Nate Begeman19351632009-10-18 20:10:40 +00001235 return llvm::UndefValue::get(I32Ty);
1236 return llvm::ConstantInt::get(I32Ty, Off+MV);
1237}
1238
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001239static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1240 if (C->getBitWidth() != 32) {
1241 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1242 C->getZExtValue()) &&
1243 "Index operand too large for shufflevector mask!");
1244 return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1245 }
1246 return C;
1247}
1248
Nate Begeman19351632009-10-18 20:10:40 +00001249Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1250 bool Ignore = TestAndClearIgnoreResultAssign();
1251 (void)Ignore;
1252 assert (Ignore == false && "init list ignored");
1253 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001254
Nate Begeman19351632009-10-18 20:10:40 +00001255 if (E->hadArrayRangeDesignator())
1256 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001257
Chris Lattner2192fe52011-07-18 04:24:23 +00001258 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001259 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001260
Sebastian Redl12757ab2011-09-24 17:48:14 +00001261 if (!VType) {
1262 if (NumInitElements == 0) {
1263 // C++11 value-initialization for the scalar.
1264 return EmitNullValue(E->getType());
1265 }
1266 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001267 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001268 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001269
Nate Begeman19351632009-10-18 20:10:40 +00001270 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001271
1272 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001273 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1274 // us to fold the shuffle for the swizzle into the shuffle for the vector
1275 // initializer, since LLVM optimizers generally do not want to touch
1276 // shuffles.
1277 unsigned CurIdx = 0;
1278 bool VIsUndefShuffle = false;
1279 llvm::Value *V = llvm::UndefValue::get(VType);
1280 for (unsigned i = 0; i != NumInitElements; ++i) {
1281 Expr *IE = E->getInit(i);
1282 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001283 SmallVector<llvm::Constant*, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001284
Chris Lattner2192fe52011-07-18 04:24:23 +00001285 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001286
Nate Begeman19351632009-10-18 20:10:40 +00001287 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001288 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001289 // extract+insert.
1290 if (!VVT) {
1291 if (isa<ExtVectorElementExpr>(IE)) {
1292 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1293
1294 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1295 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001296 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001297 if (CurIdx == 0) {
1298 // insert into undef -> shuffle (src, undef)
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001299 // shufflemask must use an i32
1300 Args.push_back(getAsInt32(C, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001301 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001302
1303 LHS = EI->getVectorOperand();
1304 RHS = V;
1305 VIsUndefShuffle = true;
1306 } else if (VIsUndefShuffle) {
1307 // insert into undefshuffle && size match -> shuffle (v, src)
1308 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1309 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001310 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +00001311 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001312 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1313
Nate Begeman19351632009-10-18 20:10:40 +00001314 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1315 RHS = EI->getVectorOperand();
1316 VIsUndefShuffle = false;
1317 }
1318 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +00001319 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001320 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1321 ++CurIdx;
1322 continue;
1323 }
1324 }
1325 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001326 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1327 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001328 VIsUndefShuffle = false;
1329 ++CurIdx;
1330 continue;
1331 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001332
Nate Begeman19351632009-10-18 20:10:40 +00001333 unsigned InitElts = VVT->getNumElements();
1334
Craig Toppera97d7e72013-07-26 06:16:11 +00001335 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001336 // input is the same width as the vector being constructed, generate an
1337 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001338 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001339 if (isa<ExtVectorElementExpr>(IE)) {
1340 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1341 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001342 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001343
Nate Begeman19351632009-10-18 20:10:40 +00001344 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001345 for (unsigned j = 0; j != CurIdx; ++j) {
1346 // If the current vector initializer is a shuffle with undef, merge
1347 // this shuffle directly into it.
1348 if (VIsUndefShuffle) {
1349 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +00001350 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001351 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001352 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001353 }
1354 }
1355 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001356 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001357 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001358
1359 if (VIsUndefShuffle)
1360 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1361
1362 Init = SVOp;
1363 }
1364 }
1365
1366 // Extend init to result vector length, and then shuffle its contribution
1367 // to the vector initializer into V.
1368 if (Args.empty()) {
1369 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001370 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001371 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001372 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001373 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +00001374 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001375
1376 Args.clear();
1377 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001378 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001379 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001380 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001381 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001382 }
1383
1384 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1385 // merging subsequent shuffles into this one.
1386 if (CurIdx == 0)
1387 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001388 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001389 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1390 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1391 CurIdx += InitElts;
1392 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001393
Nate Begeman19351632009-10-18 20:10:40 +00001394 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1395 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001396 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001397
Nate Begeman19351632009-10-18 20:10:40 +00001398 // Emit remaining default initializers
1399 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001400 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001401 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1402 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1403 }
1404 return V;
1405}
1406
John McCall7f416cc2015-09-08 08:05:57 +00001407bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001408 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001409
John McCalle3027922010-08-25 11:45:40 +00001410 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001411 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001412
John McCall7f416cc2015-09-08 08:05:57 +00001413 if (isa<CXXThisExpr>(E->IgnoreParens())) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001414 // We always assume that 'this' is never null.
1415 return false;
1416 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001417
Anders Carlsson8c793172009-11-23 17:57:54 +00001418 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001419 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001420 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001421 return false;
1422 }
1423
1424 return true;
1425}
1426
Chris Lattner2da04b32007-08-24 05:35:26 +00001427// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1428// have to handle a more broad range of conversions than explicit casts, as they
1429// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001430Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001431 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001432 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001433 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001434
John McCalle399e5b2016-01-27 18:32:30 +00001435 // These cases are generally not written to ignore the result of
1436 // evaluating their sub-expressions, so we clear this now.
1437 bool Ignored = TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001438
Eli Friedman0dfc6802009-11-27 02:07:44 +00001439 // Since almost all cast kinds apply to scalars, this switch doesn't have
1440 // a default case, so the compiler will warn on a missing case. The cases
1441 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001442 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001443 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001444 case CK_BuiltinFnToFnPtr:
1445 llvm_unreachable("builtin functions are handled elsewhere");
1446
Craig Toppera97d7e72013-07-26 06:16:11 +00001447 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00001448 case CK_ObjCObjectLValueCast: {
John McCall7f416cc2015-09-08 08:05:57 +00001449 Address Addr = EmitLValue(E).getAddress();
Alexey Bataevf2440332015-10-07 10:22:08 +00001450 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
John McCall7f416cc2015-09-08 08:05:57 +00001451 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1452 return EmitLoadOfLValue(LV, CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00001453 }
John McCallcd78e802011-09-10 01:16:55 +00001454
John McCall9320b872011-09-09 05:25:32 +00001455 case CK_CPointerToObjCPointerCast:
1456 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001457 case CK_AnyPointerToBlockPointerCast:
1458 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001459 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00001460 llvm::Type *SrcTy = Src->getType();
1461 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00001462 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00001463 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00001464 llvm_unreachable("wrong cast for pointers in different address spaces"
1465 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00001466 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00001467
1468 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
1469 if (auto PT = DestTy->getAs<PointerType>())
1470 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001471 /*MayBeNull=*/true,
1472 CodeGenFunction::CFITCK_UnrelatedCast,
1473 CE->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00001474 }
1475
David Tweede1468322013-12-11 13:39:46 +00001476 return Builder.CreateBitCast(Src, DstTy);
1477 }
1478 case CK_AddressSpaceConversion: {
Yaxun Liu402804b2016-12-15 08:09:08 +00001479 Expr::EvalResult Result;
1480 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
1481 Result.Val.isNullPointer()) {
1482 // If E has side effect, it is emitted even if its final result is a
1483 // null pointer. In that case, a DCE pass should be able to
1484 // eliminate the useless instructions emitted during translating E.
1485 if (Result.HasSideEffects)
1486 Visit(E);
1487 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
1488 ConvertType(DestTy)), DestTy);
1489 }
Yaxun Liub7b6d0f2016-04-12 19:03:49 +00001490 // Since target may map different address spaces in AST to the same address
1491 // space, an address space conversion may end up as a bitcast.
Yaxun Liu402804b2016-12-15 08:09:08 +00001492 auto *Src = Visit(E);
1493 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGF, Src,
1494 E->getType(),
1495 DestTy);
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001496 }
David Chisnallfa35df62012-01-16 17:27:18 +00001497 case CK_AtomicToNonAtomic:
1498 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00001499 case CK_NoOp:
1500 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001501 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001502
John McCalle3027922010-08-25 11:45:40 +00001503 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00001504 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1505 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1506
John McCall7f416cc2015-09-08 08:05:57 +00001507 Address Base = CGF.EmitPointerWithAlignment(E);
1508 Address Derived =
1509 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001510 CE->path_begin(), CE->path_end(),
John McCall7f416cc2015-09-08 08:05:57 +00001511 CGF.ShouldNullCheckClassCastValue(CE));
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001512
Richard Smith2c5868c2013-02-13 21:18:23 +00001513 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1514 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00001515 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00001516 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00001517 Derived.getPointer(), DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00001518
Peter Collingbourned2926c92015-03-14 02:42:25 +00001519 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00001520 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(),
1521 Derived.getPointer(),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001522 /*MayBeNull=*/true,
1523 CodeGenFunction::CFITCK_DerivedCast,
1524 CE->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00001525
John McCall7f416cc2015-09-08 08:05:57 +00001526 return Derived.getPointer();
Anders Carlsson8c793172009-11-23 17:57:54 +00001527 }
John McCalle3027922010-08-25 11:45:40 +00001528 case CK_UncheckedDerivedToBase:
1529 case CK_DerivedToBase: {
John McCall7f416cc2015-09-08 08:05:57 +00001530 // The EmitPointerWithAlignment path does this fine; just discard
1531 // the alignment.
1532 return CGF.EmitPointerWithAlignment(CE).getPointer();
Anders Carlsson12f5a252009-09-12 04:57:16 +00001533 }
John McCall7f416cc2015-09-08 08:05:57 +00001534
Anders Carlsson8a01a752011-04-11 02:03:26 +00001535 case CK_Dynamic: {
John McCall7f416cc2015-09-08 08:05:57 +00001536 Address V = CGF.EmitPointerWithAlignment(E);
Eli Friedman0dfc6802009-11-27 02:07:44 +00001537 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1538 return CGF.EmitDynamicCast(V, DCE);
1539 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00001540
John McCall7f416cc2015-09-08 08:05:57 +00001541 case CK_ArrayToPointerDecay:
1542 return CGF.EmitArrayToPointerDecay(E).getPointer();
John McCalle3027922010-08-25 11:45:40 +00001543 case CK_FunctionToPointerDecay:
John McCall7f416cc2015-09-08 08:05:57 +00001544 return EmitLValue(E).getPointer();
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001545
John McCalle84af4e2010-11-13 01:35:44 +00001546 case CK_NullToPointer:
1547 if (MustVisitNullValue(E))
1548 (void) Visit(E);
1549
Yaxun Liu402804b2016-12-15 08:09:08 +00001550 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
1551 DestTy);
John McCalle84af4e2010-11-13 01:35:44 +00001552
John McCalle3027922010-08-25 11:45:40 +00001553 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00001554 if (MustVisitNullValue(E))
John McCalla1dee5302010-08-22 10:59:02 +00001555 (void) Visit(E);
1556
John McCall7a9aac22010-08-23 01:21:21 +00001557 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1558 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1559 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00001560
John McCallc62bb392012-02-15 01:22:51 +00001561 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00001562 case CK_BaseToDerivedMemberPointer:
1563 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001564 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00001565
John McCalla1dee5302010-08-22 10:59:02 +00001566 // Note that the AST doesn't distinguish between checked and
1567 // unchecked member pointer conversions, so we always have to
1568 // implement checked conversions here. This is inefficient when
1569 // actual control flow may be required in order to perform the
1570 // check, which it is for data member pointers (but not member
1571 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00001572 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00001573 }
John McCall31168b02011-06-15 23:02:42 +00001574
John McCall2d637d22011-09-10 06:18:15 +00001575 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00001576 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00001577 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00001578 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCalle399e5b2016-01-27 18:32:30 +00001579 case CK_ARCReclaimReturnedObject:
1580 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
John McCallff613032011-10-04 06:23:45 +00001581 case CK_ARCExtendBlockObject:
1582 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00001583
Douglas Gregored90df32012-02-22 05:02:47 +00001584 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00001585 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001586
John McCallc5e62b42010-11-13 09:02:35 +00001587 case CK_FloatingRealToComplex:
1588 case CK_FloatingComplexCast:
1589 case CK_IntegralRealToComplex:
1590 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00001591 case CK_IntegralComplexToFloatingComplex:
1592 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00001593 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00001594 case CK_ToUnion:
1595 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00001596
John McCallf3735e02010-12-01 04:43:34 +00001597 case CK_LValueToRValue:
1598 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00001599 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00001600 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00001601
John McCalle3027922010-08-25 11:45:40 +00001602 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001603 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001604
Anders Carlsson094c4592009-10-18 18:12:03 +00001605 // First, convert to the correct width so that we control the kind of
1606 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00001607 auto DestLLVMTy = ConvertType(DestTy);
1608 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001609 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00001610 llvm::Value* IntResult =
1611 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001612
Yaxun Liu26f75662016-08-19 05:17:25 +00001613 return Builder.CreateIntToPtr(IntResult, DestLLVMTy);
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001614 }
Eli Friedman58368522011-06-25 02:58:47 +00001615 case CK_PointerToIntegral:
1616 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1617 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001618
John McCalle3027922010-08-25 11:45:40 +00001619 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00001620 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00001621 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001622 }
John McCalle3027922010-08-25 11:45:40 +00001623 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00001624 llvm::Type *DstTy = ConvertType(DestTy);
George Burgess IVdf1ed002016-01-13 01:52:39 +00001625 Value *Elt = Visit(const_cast<Expr*>(E));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001626 // Splat the element across to all elements
Craig Topperf2f1a092016-07-08 02:17:35 +00001627 unsigned NumElements = DstTy->getVectorNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00001628 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001629 }
John McCall8cb679e2010-11-15 09:13:47 +00001630
John McCalle3027922010-08-25 11:45:40 +00001631 case CK_IntegralCast:
1632 case CK_IntegralToFloating:
1633 case CK_FloatingToIntegral:
1634 case CK_FloatingCast:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001635 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
1636 CE->getExprLoc());
George Burgess IVdf1ed002016-01-13 01:52:39 +00001637 case CK_BooleanToSignedIntegral:
1638 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
1639 CE->getExprLoc(),
1640 /*TreatBooleanAsSigned=*/true);
John McCall8cb679e2010-11-15 09:13:47 +00001641 case CK_IntegralToBoolean:
1642 return EmitIntToBoolConversion(Visit(E));
1643 case CK_PointerToBoolean:
Yaxun Liu402804b2016-12-15 08:09:08 +00001644 return EmitPointerToBoolConversion(Visit(E), E->getType());
John McCall8cb679e2010-11-15 09:13:47 +00001645 case CK_FloatingToBoolean:
1646 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00001647 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00001648 llvm::Value *MemPtr = Visit(E);
1649 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1650 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001651 }
John McCalld7646252010-11-14 08:17:51 +00001652
1653 case CK_FloatingComplexToReal:
1654 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00001655 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00001656
1657 case CK_FloatingComplexToBoolean:
1658 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00001659 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00001660
1661 // TODO: kill this function off, inline appropriate case here
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001662 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
1663 CE->getExprLoc());
John McCalld7646252010-11-14 08:17:51 +00001664 }
1665
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001666 case CK_ZeroToOCLEvent: {
Alp Tokerd4733632013-12-05 04:47:09 +00001667 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001668 return llvm::Constant::getNullValue(ConvertType(DestTy));
1669 }
1670
Egor Churaev89831422016-12-23 14:55:49 +00001671 case CK_ZeroToOCLQueue: {
1672 assert(DestTy->isQueueT() && "CK_ZeroToOCLQueue cast on non queue_t type");
1673 return llvm::Constant::getNullValue(ConvertType(DestTy));
1674 }
1675
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001676 case CK_IntToOCLSampler:
1677 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
1678
1679 } // end of switch
Mike Stump4a3999f2009-09-09 13:00:44 +00001680
John McCall3eba6e62010-11-16 06:21:14 +00001681 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00001682}
1683
Chris Lattner04a913b2007-08-31 22:09:40 +00001684Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00001685 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001686 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1687 !E->getType()->isVoidType());
1688 if (!RetAlloca.isValid())
Craig Topper8a13c412014-05-21 05:09:00 +00001689 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001690 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1691 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00001692}
1693
Chris Lattner2da04b32007-08-24 05:35:26 +00001694//===----------------------------------------------------------------------===//
1695// Unary Operators
1696//===----------------------------------------------------------------------===//
1697
Alexey Samsonovf6246502015-04-23 01:50:45 +00001698static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
1699 llvm::Value *InVal, bool IsInc) {
1700 BinOpInfo BinOp;
1701 BinOp.LHS = InVal;
1702 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
1703 BinOp.Ty = E->getType();
1704 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
1705 BinOp.FPContractable = false;
1706 BinOp.E = E;
1707 return BinOp;
1708}
1709
1710llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
1711 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
1712 llvm::Value *Amount =
1713 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
1714 StringRef Name = IsInc ? "inc" : "dec";
Richard Smith9c6890a2012-11-01 22:30:59 +00001715 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00001716 case LangOptions::SOB_Defined:
Alexey Samsonovf6246502015-04-23 01:50:45 +00001717 return Builder.CreateAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00001718 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001719 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Alexey Samsonovf6246502015-04-23 01:50:45 +00001720 return Builder.CreateNSWAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00001721 // Fall through.
Anton Yartsev85129b82011-02-07 02:17:30 +00001722 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00001723 if (IsWidenedIntegerOp(CGF.getContext(), E->getSubExpr()))
1724 return Builder.CreateNSWAdd(InVal, Amount, Name);
Alexey Samsonovf6246502015-04-23 01:50:45 +00001725 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
Anton Yartsev85129b82011-02-07 02:17:30 +00001726 }
David Blaikie83d382b2011-09-23 05:06:16 +00001727 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00001728}
1729
John McCalle3dc1702011-02-15 09:22:45 +00001730llvm::Value *
1731ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1732 bool isInc, bool isPre) {
Craig Toppera97d7e72013-07-26 06:16:11 +00001733
John McCalle3dc1702011-02-15 09:22:45 +00001734 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00001735 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00001736 llvm::Value *value;
1737 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00001738
John McCalle3dc1702011-02-15 09:22:45 +00001739 int amount = (isInc ? 1 : -1);
1740
David Chisnallfa35df62012-01-16 17:27:18 +00001741 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00001742 type = atomicTy->getValueType();
1743 if (isInc && type->isBooleanType()) {
1744 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1745 if (isPre) {
John McCall7f416cc2015-09-08 08:05:57 +00001746 Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
JF Bastien92f4ef12016-04-06 17:26:42 +00001747 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00001748 return Builder.getTrue();
1749 }
1750 // For atomic bool increment, we just store true and return it for
1751 // preincrement, do an atomic swap with true for postincrement
JF Bastien92f4ef12016-04-06 17:26:42 +00001752 return Builder.CreateAtomicRMW(
1753 llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
1754 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00001755 }
1756 // Special case for atomic increment / decrement on integers, emit
1757 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00001758 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00001759 if (!type->isBooleanType() && type->isIntegerType() &&
1760 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001761 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00001762 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001763 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00001764 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1765 llvm::AtomicRMWInst::Sub;
1766 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1767 llvm::Instruction::Sub;
1768 llvm::Value *amt = CGF.EmitToMemory(
1769 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1770 llvm::Value *old = Builder.CreateAtomicRMW(aop,
JF Bastien92f4ef12016-04-06 17:26:42 +00001771 LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00001772 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1773 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001774 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00001775 input = value;
1776 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00001777 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1778 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00001779 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00001780 Builder.CreateBr(opBB);
1781 Builder.SetInsertPoint(opBB);
1782 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1783 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001784 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00001785 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001786 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00001787 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00001788 }
1789
John McCalle3dc1702011-02-15 09:22:45 +00001790 // Special case of integer increment that we have to check first: bool++.
1791 // Due to promotion rules, we get:
1792 // bool++ -> bool = bool + 1
1793 // -> bool = (int)bool + 1
1794 // -> bool = ((int)bool + 1 != 0)
1795 // An interesting aspect of this is that increment is always true.
1796 // Decrement does not have this property.
1797 if (isInc && type->isBooleanType()) {
1798 value = Builder.getTrue();
1799
1800 // Most common case by far: integer increment.
1801 } else if (type->isIntegerType()) {
Eli Friedman846ded22011-03-02 01:49:12 +00001802 // Note that signed integer inc/dec with width less than int can't
1803 // overflow because of promotion rules; we're just eliding a few steps here.
Richard Smith45d099b2014-07-07 05:36:14 +00001804 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1805 CGF.IntTy->getIntegerBitWidth();
1806 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
Alexey Samsonovf6246502015-04-23 01:50:45 +00001807 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
Richard Smith45d099b2014-07-07 05:36:14 +00001808 } else if (CanOverflow && type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001809 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
Alexey Samsonovf6246502015-04-23 01:50:45 +00001810 value =
1811 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
1812 } else {
1813 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00001814 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Alexey Samsonovf6246502015-04-23 01:50:45 +00001815 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001816
John McCalle3dc1702011-02-15 09:22:45 +00001817 // Next most common: pointer increment.
1818 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1819 QualType type = ptr->getPointeeType();
1820
1821 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00001822 if (const VariableArrayType *vla
1823 = CGF.getContext().getAsVariableArrayType(type)) {
1824 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCall23c29fe2011-06-24 21:55:10 +00001825 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00001826 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00001827 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00001828 else
John McCall23c29fe2011-06-24 21:55:10 +00001829 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00001830
John McCalle3dc1702011-02-15 09:22:45 +00001831 // Arithmetic on function pointers (!) is just +-1.
1832 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001833 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00001834
1835 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00001836 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001837 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1838 else
1839 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00001840 value = Builder.CreateBitCast(value, input->getType());
1841
1842 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00001843 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001844 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00001845 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001846 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1847 else
1848 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00001849 }
1850
1851 // Vector increment/decrement.
1852 } else if (type->isVectorType()) {
1853 if (type->hasIntegerRepresentation()) {
1854 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1855
Eli Friedman409943e2011-05-06 18:04:18 +00001856 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00001857 } else {
1858 value = Builder.CreateFAdd(
1859 value,
1860 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00001861 isInc ? "inc" : "dec");
1862 }
Anton Yartsev85129b82011-02-07 02:17:30 +00001863
John McCalle3dc1702011-02-15 09:22:45 +00001864 // Floating point.
1865 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00001866 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00001867 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001868
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001869 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001870 // Another special case: half FP increment should be done via float
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001871 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1872 value = Builder.CreateCall(
1873 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1874 CGF.CGM.FloatTy),
1875 input, "incdec.conv");
1876 } else {
1877 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
1878 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001879 }
1880
John McCalle3dc1702011-02-15 09:22:45 +00001881 if (value->getType()->isFloatTy())
1882 amt = llvm::ConstantFP::get(VMContext,
1883 llvm::APFloat(static_cast<float>(amount)));
1884 else if (value->getType()->isDoubleTy())
1885 amt = llvm::ConstantFP::get(VMContext,
1886 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001887 else {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001888 // Remaining types are Half, LongDouble or __float128. Convert from float.
John McCalle3dc1702011-02-15 09:22:45 +00001889 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001890 bool ignored;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001891 const llvm::fltSemantics *FS;
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00001892 // Don't use getFloatTypeSemantics because Half isn't
1893 // necessarily represented using the "half" LLVM type.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001894 if (value->getType()->isFP128Ty())
1895 FS = &CGF.getTarget().getFloat128Format();
1896 else if (value->getType()->isHalfTy())
1897 FS = &CGF.getTarget().getHalfFormat();
1898 else
1899 FS = &CGF.getTarget().getLongDoubleFormat();
1900 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00001901 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001902 }
John McCalle3dc1702011-02-15 09:22:45 +00001903 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1904
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001905 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1906 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1907 value = Builder.CreateCall(
1908 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1909 CGF.CGM.FloatTy),
1910 value, "incdec.conv");
1911 } else {
1912 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
1913 }
1914 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001915
John McCalle3dc1702011-02-15 09:22:45 +00001916 // Objective-C pointer types.
1917 } else {
1918 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1919 value = CGF.EmitCastToVoidPtr(value);
1920
1921 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1922 if (!isInc) size = -size;
1923 llvm::Value *sizeValue =
1924 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1925
Richard Smith9c6890a2012-11-01 22:30:59 +00001926 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001927 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1928 else
1929 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00001930 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00001931 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001932
David Chisnallfa35df62012-01-16 17:27:18 +00001933 if (atomicPHI) {
1934 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1935 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001936 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00001937 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
1938 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
1939 llvm::Value *success = Pair.second;
David Chisnallfa35df62012-01-16 17:27:18 +00001940 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001941 Builder.CreateCondBr(success, contBB, opBB);
1942 Builder.SetInsertPoint(contBB);
1943 return isPre ? value : input;
1944 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001945
Chris Lattner05dc78c2010-06-26 22:09:34 +00001946 // Store the updated result through the lvalue.
1947 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00001948 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001949 else
John McCall55e1fbc2011-06-25 02:11:03 +00001950 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001951
Chris Lattner05dc78c2010-06-26 22:09:34 +00001952 // If this is a postinc, return the value read from memory, otherwise use the
1953 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00001954 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00001955}
1956
1957
1958
Chris Lattner2da04b32007-08-24 05:35:26 +00001959Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001960 TestAndClearIgnoreResultAssign();
Chris Lattner0bf27622010-06-26 21:48:21 +00001961 // Emit unary minus with EmitSub so we handle overflow cases etc.
1962 BinOpInfo BinOp;
Chris Lattnerc1028f62010-06-28 17:12:37 +00001963 BinOp.RHS = Visit(E->getSubExpr());
Craig Toppera97d7e72013-07-26 06:16:11 +00001964
Chris Lattnerc1028f62010-06-28 17:12:37 +00001965 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1966 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001967 else
Chris Lattnerc1028f62010-06-28 17:12:37 +00001968 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00001969 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00001970 BinOp.Opcode = BO_Sub;
Benjamin Kramerb15b97e2012-10-03 20:58:04 +00001971 BinOp.FPContractable = false;
Chris Lattner0bf27622010-06-26 21:48:21 +00001972 BinOp.E = E;
1973 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00001974}
1975
1976Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001977 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00001978 Value *Op = Visit(E->getSubExpr());
1979 return Builder.CreateNot(Op, "neg");
1980}
1981
1982Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00001983 // Perform vector logical not on comparison with zero vector.
1984 if (E->getType()->isExtVectorType()) {
1985 Value *Oper = Visit(E->getSubExpr());
1986 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00001987 Value *Result;
1988 if (Oper->getType()->isFPOrFPVectorTy())
1989 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1990 else
1991 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00001992 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1993 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001994
Chris Lattner2da04b32007-08-24 05:35:26 +00001995 // Compare operand to zero.
1996 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001997
Chris Lattner2da04b32007-08-24 05:35:26 +00001998 // Invert value.
1999 // TODO: Could dynamically modify easy computations here. For example, if
2000 // the operand is an icmp ne, turn into icmp eq.
2001 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00002002
Anders Carlsson775640d2009-05-19 18:44:53 +00002003 // ZExt result to the expr type.
2004 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002005}
2006
Eli Friedmand7c72322010-08-05 09:58:49 +00002007Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2008 // Try folding the offsetof to a constant.
Richard Smith5fab0c92011-12-28 19:48:30 +00002009 llvm::APSInt Value;
2010 if (E->EvaluateAsInt(Value, CGF.getContext()))
2011 return Builder.getInt(Value);
Eli Friedmand7c72322010-08-05 09:58:49 +00002012
2013 // Loop over the components of the offsetof to compute the value.
2014 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00002015 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00002016 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2017 QualType CurrentType = E->getTypeSourceInfo()->getType();
2018 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00002019 OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00002020 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00002021 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00002022 case OffsetOfNode::Array: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002023 // Compute the index
2024 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2025 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002026 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00002027 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2028
2029 // Save the element type
2030 CurrentType =
2031 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2032
2033 // Compute the element size
2034 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2035 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2036
2037 // Multiply out to compute the result
2038 Offset = Builder.CreateMul(Idx, ElemSize);
2039 break;
2040 }
2041
James Y Knight7281c352015-12-29 22:31:18 +00002042 case OffsetOfNode::Field: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002043 FieldDecl *MemberDecl = ON.getField();
2044 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2045 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2046
2047 // Compute the index of the field in its parent.
2048 unsigned i = 0;
2049 // FIXME: It would be nice if we didn't have to loop here!
2050 for (RecordDecl::field_iterator Field = RD->field_begin(),
2051 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00002052 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002053 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00002054 break;
2055 }
2056 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2057
2058 // Compute the offset to the field
2059 int64_t OffsetInt = RL.getFieldOffset(i) /
2060 CGF.getContext().getCharWidth();
2061 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2062
2063 // Save the element type.
2064 CurrentType = MemberDecl->getType();
2065 break;
2066 }
Eli Friedman165301d2010-08-06 16:37:05 +00002067
James Y Knight7281c352015-12-29 22:31:18 +00002068 case OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00002069 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00002070
James Y Knight7281c352015-12-29 22:31:18 +00002071 case OffsetOfNode::Base: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002072 if (ON.getBase()->isVirtual()) {
2073 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2074 continue;
2075 }
2076
2077 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2078 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2079
2080 // Save the element type.
2081 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00002082
Eli Friedmand7c72322010-08-05 09:58:49 +00002083 // Compute the offset to the base.
2084 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2085 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002086 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2087 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00002088 break;
2089 }
2090 }
2091 Result = Builder.CreateAdd(Result, Offset);
2092 }
2093 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00002094}
2095
Peter Collingbournee190dee2011-03-11 19:24:49 +00002096/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00002097/// argument of the sizeof expression as an integer.
2098Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00002099ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2100 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00002101 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002102 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002103 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002104 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2105 if (E->isArgumentType()) {
2106 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00002107 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00002108 } else {
2109 // C99 6.5.3.4p2: If the argument is an expression of type
2110 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00002111 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002112 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002113
John McCall23c29fe2011-06-24 21:55:10 +00002114 QualType eltType;
2115 llvm::Value *numElts;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002116 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
John McCall23c29fe2011-06-24 21:55:10 +00002117
2118 llvm::Value *size = numElts;
2119
2120 // Scale the number of non-VLA elements by the non-VLA element size.
2121 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2122 if (!eltSize.isOne())
2123 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
2124
2125 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002126 }
Alexey Bataev00396512015-07-02 03:40:19 +00002127 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2128 auto Alignment =
2129 CGF.getContext()
2130 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2131 E->getTypeOfArgument()->getPointeeType()))
2132 .getQuantity();
2133 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
Anders Carlsson30032882008-12-12 07:38:43 +00002134 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002135
Mike Stump4a3999f2009-09-09 13:00:44 +00002136 // If this isn't sizeof(vla), the result must be constant; use the constant
2137 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002138 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002139}
2140
Chris Lattner9f0ad962007-08-24 21:20:17 +00002141Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2142 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002143 if (Op->getType()->isAnyComplexType()) {
2144 // If it's an l-value, load through the appropriate subobject l-value.
2145 // Note that we have to ask E because Op might be an l-value that
2146 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002147 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002148 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2149 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002150
2151 // Otherwise, calculate and project.
2152 return CGF.EmitComplexExpr(Op, false, true).first;
2153 }
2154
Chris Lattner9f0ad962007-08-24 21:20:17 +00002155 return Visit(Op);
2156}
John McCall07bb1962010-11-16 10:08:07 +00002157
Chris Lattner9f0ad962007-08-24 21:20:17 +00002158Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2159 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002160 if (Op->getType()->isAnyComplexType()) {
2161 // If it's an l-value, load through the appropriate subobject l-value.
2162 // Note that we have to ask E because Op might be an l-value that
2163 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002164 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002165 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2166 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002167
2168 // Otherwise, calculate and project.
2169 return CGF.EmitComplexExpr(Op, true, false).second;
2170 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002171
Mike Stumpdf0fe272009-05-29 15:46:01 +00002172 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2173 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002174 if (Op->isGLValue())
2175 CGF.EmitLValue(Op);
2176 else
2177 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002178 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002179}
2180
Chris Lattner2da04b32007-08-24 05:35:26 +00002181//===----------------------------------------------------------------------===//
2182// Binary Operators
2183//===----------------------------------------------------------------------===//
2184
2185BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002186 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002187 BinOpInfo Result;
2188 Result.LHS = Visit(E->getLHS());
2189 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002190 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002191 Result.Opcode = E->getOpcode();
Lang Hames5de91cc2012-10-02 04:45:10 +00002192 Result.FPContractable = E->isFPContractable();
Chris Lattner2da04b32007-08-24 05:35:26 +00002193 Result.E = E;
2194 return Result;
2195}
2196
Douglas Gregor914af212010-04-23 04:16:32 +00002197LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2198 const CompoundAssignOperator *E,
2199 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002200 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002201 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002202 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002203
Eli Friedmanf0450072013-06-12 01:40:06 +00002204 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002205 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002206
Mike Stumpc63428b2009-05-22 19:07:20 +00002207 // Emit the RHS first. __block variables need to have the rhs evaluated
2208 // first, plus this should improve codegen a little.
2209 OpInfo.RHS = Visit(E->getRHS());
2210 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002211 OpInfo.Opcode = E->getOpcode();
Stephen Canon74f9c1a2015-11-04 15:25:38 +00002212 OpInfo.FPContractable = E->isFPContractable();
Mike Stumpc63428b2009-05-22 19:07:20 +00002213 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002214 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002215 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002216
Craig Topper8a13c412014-05-21 05:09:00 +00002217 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002218 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2219 QualType type = atomicTy->getValueType();
2220 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002221 !(type->isUnsignedIntegerType() &&
2222 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2223 CGF.getLangOpts().getSignedOverflowBehavior() !=
2224 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002225 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2226 switch (OpInfo.Opcode) {
2227 // We don't have atomicrmw operands for *, %, /, <<, >>
2228 case BO_MulAssign: case BO_DivAssign:
2229 case BO_RemAssign:
2230 case BO_ShlAssign:
2231 case BO_ShrAssign:
2232 break;
2233 case BO_AddAssign:
2234 aop = llvm::AtomicRMWInst::Add;
2235 break;
2236 case BO_SubAssign:
2237 aop = llvm::AtomicRMWInst::Sub;
2238 break;
2239 case BO_AndAssign:
2240 aop = llvm::AtomicRMWInst::And;
2241 break;
2242 case BO_XorAssign:
2243 aop = llvm::AtomicRMWInst::Xor;
2244 break;
2245 case BO_OrAssign:
2246 aop = llvm::AtomicRMWInst::Or;
2247 break;
2248 default:
2249 llvm_unreachable("Invalid compound assignment type");
2250 }
2251 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002252 llvm::Value *amt = CGF.EmitToMemory(
2253 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
2254 E->getExprLoc()),
2255 LHSTy);
John McCall7f416cc2015-09-08 08:05:57 +00002256 Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
JF Bastien92f4ef12016-04-06 17:26:42 +00002257 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002258 return LHSLV;
2259 }
2260 }
David Chisnallfa35df62012-01-16 17:27:18 +00002261 // FIXME: For floating point types, we should be saving and restoring the
2262 // floating point environment in the loop.
2263 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2264 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002265 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002266 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002267 Builder.CreateBr(opBB);
2268 Builder.SetInsertPoint(opBB);
2269 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2270 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002271 OpInfo.LHS = atomicPHI;
2272 }
David Chisnallef78c302013-03-03 16:02:42 +00002273 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00002274 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002275
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002276 SourceLocation Loc = E->getExprLoc();
2277 OpInfo.LHS =
2278 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002279
Chris Lattner3d966d62007-08-24 21:00:35 +00002280 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002281 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00002282
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00002283 // Convert the result back to the LHS type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002284 Result =
2285 EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, Loc);
David Chisnallfa35df62012-01-16 17:27:18 +00002286
2287 if (atomicPHI) {
2288 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2289 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002290 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002291 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
2292 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
2293 llvm::Value *success = Pair.second;
David Chisnallfa35df62012-01-16 17:27:18 +00002294 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002295 Builder.CreateCondBr(success, contBB, opBB);
2296 Builder.SetInsertPoint(contBB);
2297 return LHSLV;
2298 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002299
Mike Stump4a3999f2009-09-09 13:00:44 +00002300 // Store the result value into the LHS lvalue. Bit-fields are handled
2301 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2302 // 'An assignment expression has the value of the left operand after the
2303 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002304 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002305 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002306 else
John McCall55e1fbc2011-06-25 02:11:03 +00002307 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002308
Douglas Gregor914af212010-04-23 04:16:32 +00002309 return LHSLV;
2310}
2311
2312Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2313 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2314 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002315 Value *RHS;
2316 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2317
2318 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002319 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00002320 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002321
John McCall07bb1962010-11-16 10:08:07 +00002322 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00002323 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00002324 return RHS;
2325
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002326 // If the lvalue is non-volatile, return the computed value of the assignment.
2327 if (!LHS.isVolatileQualified())
2328 return RHS;
2329
2330 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002331 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00002332}
2333
Chris Lattner8ee6a412010-09-11 21:47:09 +00002334void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00002335 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002336 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00002337
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002338 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002339 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2340 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002341 }
Richard Smithc86a1142012-11-06 02:30:30 +00002342
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002343 const auto *BO = cast<BinaryOperator>(Ops.E);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002344 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002345 Ops.Ty->hasSignedIntegerRepresentation() &&
2346 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS())) {
Richard Smithc86a1142012-11-06 02:30:30 +00002347 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2348
Chris Lattner8ee6a412010-09-11 21:47:09 +00002349 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00002350 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002351 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2352
Richard Smith4d1458e2012-09-08 02:08:36 +00002353 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2354 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002355 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2356 Checks.push_back(
2357 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002358 }
Richard Smithc86a1142012-11-06 02:30:30 +00002359
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002360 if (Checks.size() > 0)
2361 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002362}
Chris Lattner3d966d62007-08-24 21:00:35 +00002363
Chris Lattner2da04b32007-08-24 05:35:26 +00002364Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002365 {
2366 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002367 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2368 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Alexey Samsonov24cad992014-07-17 18:46:27 +00002369 Ops.Ty->isIntegerType()) {
2370 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2371 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002372 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Alexey Samsonov24cad992014-07-17 18:46:27 +00002373 Ops.Ty->isRealFloatingType()) {
2374 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002375 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2376 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2377 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002378 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00002379 }
Will Dietz1897cb32012-11-27 15:01:55 +00002380
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002381 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2382 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Yaxun Liuffb60902016-08-09 20:10:18 +00002383 if (CGF.getLangOpts().OpenCL &&
2384 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
2385 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
2386 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
2387 // build option allows an application to specify that single precision
2388 // floating-point divide (x/y and 1/x) and sqrt used in the program
2389 // source are correctly rounded.
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002390 llvm::Type *ValTy = Val->getType();
2391 if (ValTy->isFloatTy() ||
2392 (isa<llvm::VectorType>(ValTy) &&
2393 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00002394 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002395 }
2396 return Val;
2397 }
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002398 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002399 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2400 else
2401 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2402}
2403
2404Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2405 // Rem in C can't be a floating point type: C99 6.5.5p2.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002406 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002407 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002408 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2409
Will Dietz1897cb32012-11-27 15:01:55 +00002410 if (Ops.Ty->isIntegerType())
Chris Lattner8ee6a412010-09-11 21:47:09 +00002411 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2412 }
2413
Eli Friedman493c34a2011-04-10 04:44:11 +00002414 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002415 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2416 else
2417 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2418}
2419
Mike Stump0c61b732009-04-01 20:28:16 +00002420Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2421 unsigned IID;
2422 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00002423
Will Dietz1897cb32012-11-27 15:01:55 +00002424 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002425 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00002426 case BO_Add:
2427 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002428 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00002429 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2430 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002431 break;
John McCalle3027922010-08-25 11:45:40 +00002432 case BO_Sub:
2433 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002434 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00002435 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2436 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002437 break;
John McCalle3027922010-08-25 11:45:40 +00002438 case BO_Mul:
2439 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002440 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00002441 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2442 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002443 break;
2444 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002445 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00002446 }
Mike Stumpd3e38852009-04-02 18:15:54 +00002447 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00002448 if (isSigned)
2449 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00002450
Chris Lattnera5f58b02011-07-09 17:41:47 +00002451 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00002452
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002453 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00002454
David Blaikie43f9bb72015-05-18 22:14:03 +00002455 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Mike Stump0c61b732009-04-01 20:28:16 +00002456 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2457 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2458
Richard Smith4d1458e2012-09-08 02:08:36 +00002459 // Handle overflow with llvm.trap if no custom handler has been specified.
2460 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00002461 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00002462 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00002463 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00002464 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002465 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002466 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002467 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002468 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002469 : SanitizerKind::UnsignedIntegerOverflow;
2470 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002471 } else
Chad Rosierae229d52013-01-29 23:31:22 +00002472 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00002473 return result;
2474 }
2475
Mike Stump0c61b732009-04-01 20:28:16 +00002476 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00002477 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Duncan P. N. Exon Smith01f574c2016-08-17 03:15:29 +00002478 llvm::BasicBlock *continueBB =
2479 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
Chris Lattner8139c982010-08-07 00:20:46 +00002480 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00002481
2482 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2483
David Chisnalldd84ef12010-09-17 18:29:54 +00002484 // If an overflow handler is set, then we want to call it and then use its
2485 // result, if it returns.
2486 Builder.SetInsertPoint(overflowBB);
2487
2488 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00002489 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002490 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00002491 llvm::FunctionType *handlerTy =
2492 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2493 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2494
2495 // Sign extend the args to 64-bit, so that we can use the same handler for
2496 // all types of overflow.
2497 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2498 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2499
2500 // Call the handler with the two arguments, the operation, and the size of
2501 // the result.
John McCall882987f2013-02-28 19:01:20 +00002502 llvm::Value *handlerArgs[] = {
2503 lhs,
2504 rhs,
2505 Builder.getInt8(OpID),
2506 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2507 };
2508 llvm::Value *handlerResult =
2509 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00002510
2511 // Truncate the result back to the desired size.
2512 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2513 Builder.CreateBr(continueBB);
2514
Mike Stump0c61b732009-04-01 20:28:16 +00002515 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002516 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00002517 phi->addIncoming(result, initialBB);
2518 phi->addIncoming(handlerResult, overflowBB);
2519
2520 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00002521}
Chris Lattner2da04b32007-08-24 05:35:26 +00002522
John McCall77527a82011-06-25 01:32:37 +00002523/// Emit pointer + index arithmetic.
2524static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2525 const BinOpInfo &op,
2526 bool isSubtraction) {
2527 // Must have binary (not unary) expr here. Unary pointer
2528 // increment/decrement doesn't use this path.
2529 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002530
John McCall77527a82011-06-25 01:32:37 +00002531 Value *pointer = op.LHS;
2532 Expr *pointerOperand = expr->getLHS();
2533 Value *index = op.RHS;
2534 Expr *indexOperand = expr->getRHS();
2535
2536 // In a subtraction, the LHS is always the pointer.
2537 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2538 std::swap(pointer, index);
2539 std::swap(pointerOperand, indexOperand);
2540 }
2541
2542 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
Yaxun Liu26f75662016-08-19 05:17:25 +00002543 auto &DL = CGF.CGM.getDataLayout();
2544 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
2545 if (width != DL.getTypeSizeInBits(PtrTy)) {
John McCall77527a82011-06-25 01:32:37 +00002546 // Zero-extend or sign-extend the pointer value according to
2547 // whether the index is signed or not.
2548 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
Yaxun Liu26f75662016-08-19 05:17:25 +00002549 index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
John McCall77527a82011-06-25 01:32:37 +00002550 "idx.ext");
2551 }
2552
2553 // If this is subtraction, negate the index.
2554 if (isSubtraction)
2555 index = CGF.Builder.CreateNeg(index, "idx.neg");
2556
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002557 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002558 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2559 /*Accessed*/ false);
2560
John McCall77527a82011-06-25 01:32:37 +00002561 const PointerType *pointerType
2562 = pointerOperand->getType()->getAs<PointerType>();
2563 if (!pointerType) {
2564 QualType objectType = pointerOperand->getType()
2565 ->castAs<ObjCObjectPointerType>()
2566 ->getPointeeType();
2567 llvm::Value *objectSize
2568 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2569
2570 index = CGF.Builder.CreateMul(index, objectSize);
2571
2572 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2573 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2574 return CGF.Builder.CreateBitCast(result, pointer->getType());
2575 }
2576
2577 QualType elementType = pointerType->getPointeeType();
2578 if (const VariableArrayType *vla
2579 = CGF.getContext().getAsVariableArrayType(elementType)) {
2580 // The element count here is the total number of non-VLA elements.
2581 llvm::Value *numElements = CGF.getVLASize(vla).first;
2582
2583 // Effectively, the multiply by the VLA size is part of the GEP.
2584 // GEP indexes are signed, and scaling an index isn't permitted to
2585 // signed-overflow, so we use the same semantics for our explicit
2586 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002587 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002588 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2589 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2590 } else {
2591 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2592 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00002593 }
John McCall77527a82011-06-25 01:32:37 +00002594 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00002595 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002596
Mike Stump4a3999f2009-09-09 13:00:44 +00002597 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2598 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2599 // future proof.
John McCall77527a82011-06-25 01:32:37 +00002600 if (elementType->isVoidType() || elementType->isFunctionType()) {
2601 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2602 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2603 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00002604 }
2605
David Blaikiebbafb8a2012-03-11 07:00:24 +00002606 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00002607 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2608
2609 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00002610}
2611
Lang Hames5de91cc2012-10-02 04:45:10 +00002612// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2613// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2614// the add operand respectively. This allows fmuladd to represent a*b-c, or
2615// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2616// efficient operations.
2617static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2618 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2619 bool negMul, bool negAdd) {
2620 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00002621
Lang Hames5de91cc2012-10-02 04:45:10 +00002622 Value *MulOp0 = MulOp->getOperand(0);
2623 Value *MulOp1 = MulOp->getOperand(1);
2624 if (negMul) {
2625 MulOp0 =
2626 Builder.CreateFSub(
2627 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2628 "neg");
2629 } else if (negAdd) {
2630 Addend =
2631 Builder.CreateFSub(
2632 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2633 "neg");
2634 }
2635
David Blaikie43f9bb72015-05-18 22:14:03 +00002636 Value *FMulAdd = Builder.CreateCall(
Lang Hames5de91cc2012-10-02 04:45:10 +00002637 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
David Blaikie43f9bb72015-05-18 22:14:03 +00002638 {MulOp0, MulOp1, Addend});
Lang Hames5de91cc2012-10-02 04:45:10 +00002639 MulOp->eraseFromParent();
2640
2641 return FMulAdd;
2642}
2643
2644// Check whether it would be legal to emit an fmuladd intrinsic call to
2645// represent op and if so, build the fmuladd.
2646//
2647// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2648// Does NOT check the type of the operation - it's assumed that this function
2649// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00002650static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00002651 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2652 bool isSub=false) {
2653
2654 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2655 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2656 "Only fadd/fsub can be the root of an fmuladd.");
2657
2658 // Check whether this op is marked as fusable.
2659 if (!op.FPContractable)
Craig Topper8a13c412014-05-21 05:09:00 +00002660 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002661
2662 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2663 // either disabled, or handled entirely by the LLVM backend).
Lang Hames65992f42012-11-15 07:51:26 +00002664 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Craig Topper8a13c412014-05-21 05:09:00 +00002665 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002666
2667 // We have a potentially fusable op. Look for a mul on one of the operands.
Sanjay Patela30cee62015-12-03 01:25:12 +00002668 // Also, make sure that the mul result isn't used directly. In that case,
2669 // there's no point creating a muladd operation.
2670 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2671 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
2672 LHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00002673 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
Sanjay Patela30cee62015-12-03 01:25:12 +00002674 }
2675 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2676 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
2677 RHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00002678 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
Lang Hames5de91cc2012-10-02 04:45:10 +00002679 }
2680
Craig Topper8a13c412014-05-21 05:09:00 +00002681 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002682}
2683
John McCall77527a82011-06-25 01:32:37 +00002684Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2685 if (op.LHS->getType()->isPointerTy() ||
2686 op.RHS->getType()->isPointerTy())
2687 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2688
2689 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002690 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00002691 case LangOptions::SOB_Defined:
2692 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00002693 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002694 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00002695 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2696 // Fall through.
John McCall77527a82011-06-25 01:32:37 +00002697 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002698 if (CanElideOverflowCheck(CGF.getContext(), op))
2699 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
John McCall77527a82011-06-25 01:32:37 +00002700 return EmitOverflowCheckedBinOp(op);
2701 }
2702 }
Will Dietz1897cb32012-11-27 15:01:55 +00002703
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002704 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002705 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2706 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00002707 return EmitOverflowCheckedBinOp(op);
2708
Lang Hames5de91cc2012-10-02 04:45:10 +00002709 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2710 // Try to form an fmuladd.
2711 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2712 return FMulAdd;
2713
John McCall77527a82011-06-25 01:32:37 +00002714 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hames5de91cc2012-10-02 04:45:10 +00002715 }
John McCall77527a82011-06-25 01:32:37 +00002716
2717 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2718}
2719
2720Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2721 // The LHS is always a pointer if either side is.
2722 if (!op.LHS->getType()->isPointerTy()) {
2723 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002724 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00002725 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00002726 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00002727 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002728 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00002729 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2730 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +00002731 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002732 if (CanElideOverflowCheck(CGF.getContext(), op))
2733 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
John McCall77527a82011-06-25 01:32:37 +00002734 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00002735 }
2736 }
Will Dietz1897cb32012-11-27 15:01:55 +00002737
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002738 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002739 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2740 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00002741 return EmitOverflowCheckedBinOp(op);
2742
Lang Hames5de91cc2012-10-02 04:45:10 +00002743 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2744 // Try to form an fmuladd.
2745 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2746 return FMulAdd;
John McCall77527a82011-06-25 01:32:37 +00002747 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hames5de91cc2012-10-02 04:45:10 +00002748 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00002749
John McCall77527a82011-06-25 01:32:37 +00002750 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00002751 }
Chris Lattner3d966d62007-08-24 21:00:35 +00002752
John McCall77527a82011-06-25 01:32:37 +00002753 // If the RHS is not a pointer, then we have normal pointer
2754 // arithmetic.
2755 if (!op.RHS->getType()->isPointerTy())
2756 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmane381f7e2009-03-28 02:45:41 +00002757
John McCall77527a82011-06-25 01:32:37 +00002758 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00002759
John McCall77527a82011-06-25 01:32:37 +00002760 // Do the raw subtraction part.
2761 llvm::Value *LHS
2762 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2763 llvm::Value *RHS
2764 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2765 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002766
John McCall77527a82011-06-25 01:32:37 +00002767 // Okay, figure out the element size.
2768 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2769 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002770
Craig Topper8a13c412014-05-21 05:09:00 +00002771 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00002772
2773 // For a variable-length array, this is going to be non-constant.
2774 if (const VariableArrayType *vla
2775 = CGF.getContext().getAsVariableArrayType(elementType)) {
2776 llvm::Value *numElements;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002777 std::tie(numElements, elementType) = CGF.getVLASize(vla);
John McCall77527a82011-06-25 01:32:37 +00002778
2779 divisor = numElements;
2780
2781 // Scale the number of non-VLA elements by the non-VLA element size.
2782 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2783 if (!eltSize.isOne())
2784 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2785
2786 // For everything elese, we can just compute it, safe in the
2787 // assumption that Sema won't let anything through that we can't
2788 // safely compute the size of.
2789 } else {
2790 CharUnits elementSize;
2791 // Handle GCC extension for pointer arithmetic on void* and
2792 // function pointer types.
2793 if (elementType->isVoidType() || elementType->isFunctionType())
2794 elementSize = CharUnits::One();
2795 else
2796 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2797
2798 // Don't even emit the divide for element size of 1.
2799 if (elementSize.isOne())
2800 return diffInChars;
2801
2802 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00002803 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002804
Chris Lattner2e72da942011-03-01 00:03:48 +00002805 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2806 // pointer difference in C is only defined in the case where both operands
2807 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00002808 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00002809}
2810
David Tweed042e0882013-01-07 16:43:27 +00002811Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00002812 llvm::IntegerType *Ty;
2813 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2814 Ty = cast<llvm::IntegerType>(VT->getElementType());
2815 else
2816 Ty = cast<llvm::IntegerType>(LHS->getType());
2817 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00002818}
2819
Chris Lattner2da04b32007-08-24 05:35:26 +00002820Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2821 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2822 // RHS to the same size as the LHS.
2823 Value *RHS = Ops.RHS;
2824 if (Ops.LHS->getType() != RHS->getType())
2825 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002826
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002827 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
James Molloy59802322016-08-16 09:45:36 +00002828 Ops.Ty->hasSignedIntegerRepresentation() &&
2829 !CGF.getLangOpts().isSignedOverflowDefined();
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002830 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
2831 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2832 if (CGF.getLangOpts().OpenCL)
2833 RHS =
2834 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2835 else if ((SanitizeBase || SanitizeExponent) &&
2836 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002837 CodeGenFunction::SanitizerScope SanScope(&CGF);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002838 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
Vedant Kumard3a601b2017-01-30 23:38:54 +00002839 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
2840 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00002841
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002842 if (SanitizeExponent) {
2843 Checks.push_back(
2844 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
2845 }
2846
2847 if (SanitizeBase) {
2848 // Check whether we are shifting any non-zero bits off the top of the
2849 // integer. We only emit this check if exponent is valid - otherwise
2850 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002851 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2852 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002853 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
2854 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
Vedant Kumard3a601b2017-01-30 23:38:54 +00002855 llvm::Value *PromotedWidthMinusOne =
2856 (RHS == Ops.RHS) ? WidthMinusOne
2857 : GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002858 CGF.EmitBlock(CheckShiftBase);
Vedant Kumard3a601b2017-01-30 23:38:54 +00002859 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
2860 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
2861 /*NUW*/ true, /*NSW*/ true),
2862 "shl.check");
Richard Smith3e056de2012-08-25 00:32:28 +00002863 if (CGF.getLangOpts().CPlusPlus) {
2864 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2865 // Under C++11's rules, shifting a 1 bit into the sign bit is
2866 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2867 // define signed left shifts, so we use the C99 and C++11 rules there).
2868 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2869 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2870 }
2871 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002872 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002873 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002874 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
2875 BaseCheck->addIncoming(Builder.getTrue(), Orig);
2876 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
2877 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00002878 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00002879
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002880 assert(!Checks.empty());
2881 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00002882 }
2883
Chris Lattner2da04b32007-08-24 05:35:26 +00002884 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2885}
2886
2887Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2888 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2889 // RHS to the same size as the LHS.
2890 Value *RHS = Ops.RHS;
2891 if (Ops.LHS->getType() != RHS->getType())
2892 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002893
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002894 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2895 if (CGF.getLangOpts().OpenCL)
2896 RHS =
2897 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2898 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
2899 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002900 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002901 llvm::Value *Valid =
2902 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002903 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002904 }
David Tweed042e0882013-01-07 16:43:27 +00002905
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002906 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002907 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2908 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2909}
2910
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002911enum IntrinsicType { VCMPEQ, VCMPGT };
2912// return corresponding comparison intrinsic for given vector type
2913static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2914 BuiltinType::Kind ElemKind) {
2915 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002916 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002917 case BuiltinType::Char_U:
2918 case BuiltinType::UChar:
2919 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2920 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002921 case BuiltinType::Char_S:
2922 case BuiltinType::SChar:
2923 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2924 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002925 case BuiltinType::UShort:
2926 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2927 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002928 case BuiltinType::Short:
2929 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2930 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002931 case BuiltinType::UInt:
2932 case BuiltinType::ULong:
2933 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2934 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002935 case BuiltinType::Int:
2936 case BuiltinType::Long:
2937 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2938 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002939 case BuiltinType::Float:
2940 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2941 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002942 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002943}
2944
Craig Topperc82f8962015-12-16 06:24:28 +00002945Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
2946 llvm::CmpInst::Predicate UICmpOpc,
2947 llvm::CmpInst::Predicate SICmpOpc,
2948 llvm::CmpInst::Predicate FCmpOpc) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002949 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00002950 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00002951 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00002952 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00002953 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00002954 assert(E->getOpcode() == BO_EQ ||
2955 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00002956 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2957 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00002958 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00002959 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00002960 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002961 Value *LHS = Visit(E->getLHS());
2962 Value *RHS = Visit(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00002963
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002964 // If AltiVec, the comparison results in a numeric type, so we use
2965 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00002966 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002967 // constants for mapping CR6 register bits to predicate result
2968 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2969
2970 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2971
2972 // in several cases vector arguments order will be reversed
2973 Value *FirstVecArg = LHS,
2974 *SecondVecArg = RHS;
2975
2976 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCall424cec92011-01-19 06:33:43 +00002977 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002978 BuiltinType::Kind ElementKind = BTy->getKind();
2979
2980 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002981 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002982 case BO_EQ:
2983 CR6 = CR6_LT;
2984 ID = GetIntrinsic(VCMPEQ, ElementKind);
2985 break;
2986 case BO_NE:
2987 CR6 = CR6_EQ;
2988 ID = GetIntrinsic(VCMPEQ, ElementKind);
2989 break;
2990 case BO_LT:
2991 CR6 = CR6_LT;
2992 ID = GetIntrinsic(VCMPGT, ElementKind);
2993 std::swap(FirstVecArg, SecondVecArg);
2994 break;
2995 case BO_GT:
2996 CR6 = CR6_LT;
2997 ID = GetIntrinsic(VCMPGT, ElementKind);
2998 break;
2999 case BO_LE:
3000 if (ElementKind == BuiltinType::Float) {
3001 CR6 = CR6_LT;
3002 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3003 std::swap(FirstVecArg, SecondVecArg);
3004 }
3005 else {
3006 CR6 = CR6_EQ;
3007 ID = GetIntrinsic(VCMPGT, ElementKind);
3008 }
3009 break;
3010 case BO_GE:
3011 if (ElementKind == BuiltinType::Float) {
3012 CR6 = CR6_LT;
3013 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3014 }
3015 else {
3016 CR6 = CR6_EQ;
3017 ID = GetIntrinsic(VCMPGT, ElementKind);
3018 std::swap(FirstVecArg, SecondVecArg);
3019 }
3020 break;
3021 }
3022
Chris Lattner2531eb42011-04-19 22:55:03 +00003023 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003024 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
David Blaikie43f9bb72015-05-18 22:14:03 +00003025 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003026 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3027 E->getExprLoc());
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003028 }
3029
Duncan Sands998f9d92010-02-15 16:14:01 +00003030 if (LHS->getType()->isFPOrFPVectorTy()) {
Craig Topperc82f8962015-12-16 06:24:28 +00003031 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003032 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Craig Topperc82f8962015-12-16 06:24:28 +00003033 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00003034 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00003035 // Unsigned integers and pointers.
Craig Topperc82f8962015-12-16 06:24:28 +00003036 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00003037 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00003038
3039 // If this is a vector comparison, sign extend the result to the appropriate
3040 // vector integer type and return it (don't convert to bool).
3041 if (LHSTy->isVectorType())
3042 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00003043
Chris Lattner2da04b32007-08-24 05:35:26 +00003044 } else {
3045 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00003046 CodeGenFunction::ComplexPairTy LHS, RHS;
3047 QualType CETy;
3048 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
3049 LHS = CGF.EmitComplexExpr(E->getLHS());
3050 CETy = CTy->getElementType();
3051 } else {
3052 LHS.first = Visit(E->getLHS());
3053 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
3054 CETy = LHSTy;
3055 }
3056 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
3057 RHS = CGF.EmitComplexExpr(E->getRHS());
3058 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
3059 CTy->getElementType()) &&
3060 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00003061 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00003062 } else {
3063 RHS.first = Visit(E->getRHS());
3064 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
3065 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
3066 "The element types must always match.");
3067 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003068
Chris Lattner42e6b812007-08-26 16:34:22 +00003069 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00003070 if (CETy->isRealFloatingType()) {
Craig Topperc82f8962015-12-16 06:24:28 +00003071 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
3072 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00003073 } else {
3074 // Complex comparisons can only be equality comparisons. As such, signed
3075 // and unsigned opcodes are the same.
Craig Topperc82f8962015-12-16 06:24:28 +00003076 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
3077 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00003078 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003079
John McCalle3027922010-08-25 11:45:40 +00003080 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00003081 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
3082 } else {
John McCalle3027922010-08-25 11:45:40 +00003083 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00003084 "Complex comparison other than == or != ?");
3085 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
3086 }
3087 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00003088
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003089 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3090 E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00003091}
3092
3093Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003094 bool Ignore = TestAndClearIgnoreResultAssign();
3095
John McCall31168b02011-06-15 23:02:42 +00003096 Value *RHS;
3097 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003098
John McCall31168b02011-06-15 23:02:42 +00003099 switch (E->getLHS()->getType().getObjCLifetime()) {
3100 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003101 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00003102 break;
3103
3104 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003105 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00003106 break;
3107
John McCalle399e5b2016-01-27 18:32:30 +00003108 case Qualifiers::OCL_ExplicitNone:
3109 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
3110 break;
3111
John McCall31168b02011-06-15 23:02:42 +00003112 case Qualifiers::OCL_Weak:
3113 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00003114 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00003115 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
3116 break;
3117
John McCall31168b02011-06-15 23:02:42 +00003118 case Qualifiers::OCL_None:
John McCall31168b02011-06-15 23:02:42 +00003119 // __block variables need to have the rhs evaluated first, plus
3120 // this should improve codegen just a little.
3121 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00003122 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00003123
3124 // Store the value into the LHS. Bit-fields are handled specially
3125 // because the result is altered by the store, i.e., [C99 6.5.16p1]
3126 // 'An assignment expression has the value of the left operand after
3127 // the assignment...'.
3128 if (LHS.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00003129 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCall31168b02011-06-15 23:02:42 +00003130 else
John McCall55e1fbc2011-06-25 02:11:03 +00003131 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCall31168b02011-06-15 23:02:42 +00003132 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003133
3134 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003135 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00003136 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003137
John McCall07bb1962010-11-16 10:08:07 +00003138 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00003139 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00003140 return RHS;
3141
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003142 // If the lvalue is non-volatile, return the computed value of the assignment.
3143 if (!LHS.isVolatileQualified())
3144 return RHS;
3145
3146 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003147 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00003148}
3149
3150Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00003151 // Perform vector logical and on comparisons with zero vectors.
3152 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003153 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003154
Tanya Lattner20248222012-01-16 21:02:28 +00003155 Value *LHS = Visit(E->getLHS());
3156 Value *RHS = Visit(E->getRHS());
3157 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003158 if (LHS->getType()->isFPOrFPVectorTy()) {
3159 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3160 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3161 } else {
3162 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3163 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3164 }
Tanya Lattner20248222012-01-16 21:02:28 +00003165 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003166 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003167 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003168
Chris Lattner2192fe52011-07-18 04:24:23 +00003169 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003170
Chris Lattner8b084582008-11-12 08:26:50 +00003171 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3172 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003173 bool LHSCondVal;
3174 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3175 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00003176 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003177
Chris Lattner5b1964b2008-11-11 07:41:27 +00003178 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003179 // ZExt result to int or bool.
3180 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003181 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003182
Chris Lattner671fec82009-10-17 04:24:20 +00003183 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00003184 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003185 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003186 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003187
Daniel Dunbara612e792008-11-13 01:38:36 +00003188 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3189 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00003190
John McCallce1de612011-01-26 04:00:11 +00003191 CodeGenFunction::ConditionalEvaluation eval(CGF);
3192
Chris Lattner35710d182008-11-12 08:38:24 +00003193 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogner66242d62015-04-23 23:06:47 +00003194 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
3195 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00003196
3197 // Any edges into the ContBlock are now from an (indeterminate number of)
3198 // edges from this first condition. All of these values will be false. Start
3199 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003200 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003201 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003202 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3203 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003204 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00003205
John McCallce1de612011-01-26 04:00:11 +00003206 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00003207 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003208 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00003209 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00003210 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003211
Chris Lattner2da04b32007-08-24 05:35:26 +00003212 // Reaquire the RHS block, as there may be subblocks inserted.
3213 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00003214
David Blaikie1b5adb82014-07-10 20:42:59 +00003215 // Emit an unconditional branch from this block to ContBlock.
3216 {
Devang Patel4d761272011-03-30 00:08:31 +00003217 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00003218 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00003219 CGF.EmitBlock(ContBlock);
3220 }
3221 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00003222 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003223
Chris Lattner2da04b32007-08-24 05:35:26 +00003224 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00003225 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00003226}
3227
3228Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00003229 // Perform vector logical or on comparisons with zero vectors.
3230 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003231 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003232
Tanya Lattner20248222012-01-16 21:02:28 +00003233 Value *LHS = Visit(E->getLHS());
3234 Value *RHS = Visit(E->getRHS());
3235 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003236 if (LHS->getType()->isFPOrFPVectorTy()) {
3237 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3238 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3239 } else {
3240 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3241 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3242 }
Tanya Lattner20248222012-01-16 21:02:28 +00003243 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003244 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003245 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003246
Chris Lattner2192fe52011-07-18 04:24:23 +00003247 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003248
Chris Lattner8b084582008-11-12 08:26:50 +00003249 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3250 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003251 bool LHSCondVal;
3252 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3253 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00003254 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003255
Chris Lattner5b1964b2008-11-11 07:41:27 +00003256 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003257 // ZExt result to int or bool.
3258 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003259 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003260
Chris Lattner671fec82009-10-17 04:24:20 +00003261 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00003262 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003263 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003264 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003265
Daniel Dunbara612e792008-11-13 01:38:36 +00003266 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3267 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00003268
John McCallce1de612011-01-26 04:00:11 +00003269 CodeGenFunction::ConditionalEvaluation eval(CGF);
3270
Chris Lattner35710d182008-11-12 08:38:24 +00003271 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00003272 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00003273 CGF.getCurrentProfileCount() -
3274 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00003275
3276 // Any edges into the ContBlock are now from an (indeterminate number of)
3277 // edges from this first condition. All of these values will be true. Start
3278 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003279 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003280 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003281 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3282 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003283 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00003284
John McCallce1de612011-01-26 04:00:11 +00003285 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00003286
Chris Lattner35710d182008-11-12 08:38:24 +00003287 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00003288 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003289 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00003290 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00003291
John McCallce1de612011-01-26 04:00:11 +00003292 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003293
Chris Lattner2da04b32007-08-24 05:35:26 +00003294 // Reaquire the RHS block, as there may be subblocks inserted.
3295 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00003296
Chris Lattner35710d182008-11-12 08:38:24 +00003297 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3298 // into the phi node for the edge with the value of RHSCond.
3299 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00003300 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003301
Chris Lattner2da04b32007-08-24 05:35:26 +00003302 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00003303 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00003304}
3305
3306Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00003307 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00003308 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00003309 return Visit(E->getRHS());
3310}
3311
3312//===----------------------------------------------------------------------===//
3313// Other Operators
3314//===----------------------------------------------------------------------===//
3315
Chris Lattner3fd91f832008-11-12 08:55:54 +00003316/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3317/// expression is cheap enough and side-effect-free enough to evaluate
3318/// unconditionally instead of conditionally. This is used to convert control
3319/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00003320static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3321 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00003322 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00003323 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00003324
Nick Lewycky22e55a02013-11-08 23:00:12 +00003325 // Even non-volatile automatic variables can't be evaluated unconditionally.
3326 // Referencing a thread_local may cause non-trivial initialization work to
3327 // occur. If we're inside a lambda and one of the variables is from the scope
3328 // outside the lambda, that function may have returned already. Reading its
3329 // locals is a bad idea. Also, these reads may introduce races there didn't
3330 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00003331}
3332
3333
Chris Lattner2da04b32007-08-24 05:35:26 +00003334Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00003335VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003336 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00003337
3338 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00003339 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00003340
3341 Expr *condExpr = E->getCond();
3342 Expr *lhsExpr = E->getTrueExpr();
3343 Expr *rhsExpr = E->getFalseExpr();
3344
Chris Lattnercd439292008-11-12 08:04:58 +00003345 // If the condition constant folds and can be elided, try to avoid emitting
3346 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003347 bool CondExprBool;
3348 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003349 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00003350 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00003351
Eli Friedman27ef75b2011-10-15 02:10:40 +00003352 // If the dead side doesn't have labels we need, just emit the Live part.
3353 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00003354 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003355 CGF.incrementProfileCounter(E);
Eli Friedman27ef75b2011-10-15 02:10:40 +00003356 Value *Result = Visit(live);
3357
3358 // If the live part is a throw expression, it acts like it has a void
3359 // type, so evaluating it returns a null Value*. However, a conditional
3360 // with non-void type must return a non-null Value*.
3361 if (!Result && !E->getType()->isVoidType())
3362 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3363
3364 return Result;
3365 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00003366 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003367
Nate Begemanabb5a732010-09-20 22:41:17 +00003368 // OpenCL: If the condition is a vector, we can treat this condition like
3369 // the select function.
Craig Toppera97d7e72013-07-26 06:16:11 +00003370 if (CGF.getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00003371 && condExpr->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003372 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003373
John McCallc07a0c72011-02-17 10:25:35 +00003374 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3375 llvm::Value *LHS = Visit(lhsExpr);
3376 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00003377
Chris Lattner2192fe52011-07-18 04:24:23 +00003378 llvm::Type *condType = ConvertType(condExpr->getType());
3379 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00003380
3381 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00003382 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003383
Chris Lattner2d6b7b92012-01-25 05:34:41 +00003384 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00003385 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Toppera97d7e72013-07-26 06:16:11 +00003386 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begemanabb5a732010-09-20 22:41:17 +00003387 llvm::VectorType::get(elemType,
Craig Toppera97d7e72013-07-26 06:16:11 +00003388 numElem),
Nate Begemanabb5a732010-09-20 22:41:17 +00003389 "sext");
3390 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00003391
Nate Begemanabb5a732010-09-20 22:41:17 +00003392 // Cast float to int to perform ANDs if necessary.
3393 llvm::Value *RHSTmp = RHS;
3394 llvm::Value *LHSTmp = LHS;
3395 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00003396 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00003397 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00003398 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3399 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3400 wasCast = true;
3401 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003402
Nate Begemanabb5a732010-09-20 22:41:17 +00003403 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3404 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3405 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3406 if (wasCast)
3407 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3408
3409 return tmp5;
3410 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003411
Chris Lattner3fd91f832008-11-12 08:55:54 +00003412 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3413 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00003414 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00003415 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3416 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
Justin Bogner66242d62015-04-23 23:06:47 +00003417 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003418
John McCallc07a0c72011-02-17 10:25:35 +00003419 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3420 llvm::Value *LHS = Visit(lhsExpr);
3421 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00003422 if (!LHS) {
3423 // If the conditional has void type, make sure we return a null Value*.
3424 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00003425 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00003426 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00003427 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3428 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003429
Daniel Dunbard2a53a72008-11-12 10:13:37 +00003430 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3431 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00003432 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00003433
3434 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00003435 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
3436 CGF.getProfileCount(lhsExpr));
Anders Carlsson43c52cd2009-06-04 03:00:32 +00003437
Chris Lattner2da04b32007-08-24 05:35:26 +00003438 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003439 CGF.incrementProfileCounter(E);
John McCallce1de612011-01-26 04:00:11 +00003440 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00003441 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00003442 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003443
Chris Lattner2da04b32007-08-24 05:35:26 +00003444 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00003445 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003446
Chris Lattner2da04b32007-08-24 05:35:26 +00003447 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00003448 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00003449 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00003450 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003451
John McCallce1de612011-01-26 04:00:11 +00003452 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00003453 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003454
Eli Friedmanf6c175b2009-12-07 20:25:53 +00003455 // If the LHS or RHS is a throw expression, it will be legitimately null.
3456 if (!LHS)
3457 return RHS;
3458 if (!RHS)
3459 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003460
Chris Lattner2da04b32007-08-24 05:35:26 +00003461 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00003462 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00003463 PN->addIncoming(LHS, LHSBlock);
3464 PN->addIncoming(RHS, RHSBlock);
3465 return PN;
3466}
3467
3468Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00003469 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00003470}
3471
Chris Lattnerb6a7b582007-11-30 17:56:23 +00003472Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00003473 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00003474
Richard Smitha1a808c2014-04-14 23:47:48 +00003475 if (Ty->isVariablyModifiedType())
3476 CGF.EmitVariablyModifiedType(Ty);
3477
Charles Davisc7d5c942015-09-17 20:55:33 +00003478 Address ArgValue = Address::invalid();
3479 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
3480
Daniel Sanders59229dc2014-11-19 10:01:35 +00003481 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003482
James Y Knight29b5f082016-02-24 02:59:33 +00003483 // If EmitVAArg fails, emit an error.
3484 if (!ArgPtr.isValid()) {
3485 CGF.ErrorUnsupported(VE, "va_arg expression");
3486 return llvm::UndefValue::get(ArgTy);
3487 }
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003488
Mike Stumpdf0fe272009-05-29 15:46:01 +00003489 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00003490 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3491
3492 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00003493 if (ArgTy != Val->getType()) {
3494 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
3495 Val = Builder.CreateIntToPtr(Val, ArgTy);
3496 else
3497 Val = Builder.CreateTrunc(Val, ArgTy);
3498 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00003499
3500 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00003501}
3502
John McCall351762c2011-02-07 10:33:21 +00003503Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3504 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00003505}
3506
Yaxun Liuc5647012016-06-08 15:11:21 +00003507// Convert a vec3 to vec4, or vice versa.
3508static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
3509 Value *Src, unsigned NumElementsDst) {
3510 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3511 SmallVector<llvm::Constant*, 4> Args;
3512 Args.push_back(Builder.getInt32(0));
3513 Args.push_back(Builder.getInt32(1));
3514 Args.push_back(Builder.getInt32(2));
3515 if (NumElementsDst == 4)
3516 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3517 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3518 return Builder.CreateShuffleVector(Src, UnV, Mask);
3519}
3520
Yaxun Liuea6b7962016-10-03 14:41:50 +00003521// Create cast instructions for converting LLVM value \p Src to LLVM type \p
3522// DstTy. \p Src has the same size as \p DstTy. Both are single value types
3523// but could be scalar or vectors of different lengths, and either can be
3524// pointer.
3525// There are 4 cases:
3526// 1. non-pointer -> non-pointer : needs 1 bitcast
3527// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
3528// 3. pointer -> non-pointer
3529// a) pointer -> intptr_t : needs 1 ptrtoint
3530// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
3531// 4. non-pointer -> pointer
3532// a) intptr_t -> pointer : needs 1 inttoptr
3533// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
3534// Note: for cases 3b and 4b two casts are required since LLVM casts do not
3535// allow casting directly between pointer types and non-integer non-pointer
3536// types.
3537static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
3538 const llvm::DataLayout &DL,
3539 Value *Src, llvm::Type *DstTy,
3540 StringRef Name = "") {
3541 auto SrcTy = Src->getType();
3542
3543 // Case 1.
3544 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
3545 return Builder.CreateBitCast(Src, DstTy, Name);
3546
3547 // Case 2.
3548 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
3549 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
3550
3551 // Case 3.
3552 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
3553 // Case 3b.
3554 if (!DstTy->isIntegerTy())
3555 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
3556 // Cases 3a and 3b.
3557 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
3558 }
3559
3560 // Case 4b.
3561 if (!SrcTy->isIntegerTy())
3562 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
3563 // Cases 4a and 4b.
3564 return Builder.CreateIntToPtr(Src, DstTy, Name);
3565}
3566
Tanya Lattner55808c12011-06-04 00:47:47 +00003567Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3568 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00003569 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003570
Chris Lattner2192fe52011-07-18 04:24:23 +00003571 llvm::Type *SrcTy = Src->getType();
Yaxun Liuc5647012016-06-08 15:11:21 +00003572 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
3573 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
3574 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
3575 cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
Craig Toppera97d7e72013-07-26 06:16:11 +00003576
Yaxun Liuc5647012016-06-08 15:11:21 +00003577 // Going from vec3 to non-vec3 is a special case and requires a shuffle
3578 // vector to get a vec4, then a bitcast if the target type is different.
3579 if (NumElementsSrc == 3 && NumElementsDst != 3) {
3580 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
Yaxun Liuea6b7962016-10-03 14:41:50 +00003581 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
3582 DstTy);
Yaxun Liuc5647012016-06-08 15:11:21 +00003583 Src->setName("astype");
3584 return Src;
3585 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003586
Yaxun Liuc5647012016-06-08 15:11:21 +00003587 // Going from non-vec3 to vec3 is a special case and requires a bitcast
3588 // to vec4 if the original type is not vec4, then a shuffle vector to
3589 // get a vec3.
3590 if (NumElementsSrc != 3 && NumElementsDst == 3) {
3591 auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
Yaxun Liuea6b7962016-10-03 14:41:50 +00003592 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
3593 Vec4Ty);
Yaxun Liuc5647012016-06-08 15:11:21 +00003594 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
3595 Src->setName("astype");
3596 return Src;
Tanya Lattner55808c12011-06-04 00:47:47 +00003597 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003598
Yaxun Liuea6b7962016-10-03 14:41:50 +00003599 return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
3600 Src, DstTy, "astype");
Tanya Lattner55808c12011-06-04 00:47:47 +00003601}
3602
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003603Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3604 return CGF.EmitAtomicExpr(E).getScalarVal();
3605}
3606
Chris Lattner2da04b32007-08-24 05:35:26 +00003607//===----------------------------------------------------------------------===//
3608// Entry Point into this File
3609//===----------------------------------------------------------------------===//
3610
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003611/// Emit the computation of the specified expression of scalar type, ignoring
3612/// the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003613Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00003614 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00003615 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00003616
David Blaikie38b25912015-02-09 19:13:51 +00003617 return ScalarExprEmitter(*this, IgnoreResultAssign)
3618 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00003619}
Chris Lattner3474c202007-08-26 06:48:56 +00003620
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003621/// Emit a conversion from the specified type to the specified destination type,
3622/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00003623Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003624 QualType DstTy,
3625 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00003626 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00003627 "Invalid scalar expression to emit");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003628 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner3474c202007-08-26 06:48:56 +00003629}
Chris Lattner42e6b812007-08-26 16:34:22 +00003630
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003631/// Emit a conversion from the specified complex type to the specified
3632/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00003633Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3634 QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003635 QualType DstTy,
3636 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00003637 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00003638 "Invalid complex -> scalar conversion");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003639 return ScalarExprEmitter(*this)
3640 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00003641}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00003642
Chris Lattner05dc78c2010-06-26 22:09:34 +00003643
3644llvm::Value *CodeGenFunction::
3645EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3646 bool isInc, bool isPre) {
3647 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3648}
3649
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003650LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003651 // object->isa or (*object).isa
3652 // Generate code as for: *(Class*)object
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003653
3654 Expr *BaseExpr = E->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003655 Address Addr = Address::invalid();
John McCall086a4642010-11-24 05:12:34 +00003656 if (BaseExpr->isRValue()) {
John McCall7f416cc2015-09-08 08:05:57 +00003657 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003658 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003659 Addr = EmitLValue(BaseExpr).getAddress();
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003660 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003661
John McCall7f416cc2015-09-08 08:05:57 +00003662 // Cast the address to Class*.
3663 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
3664 return MakeAddrLValue(Addr, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003665}
3666
Douglas Gregor914af212010-04-23 04:16:32 +00003667
John McCalla2342eb2010-12-05 02:00:02 +00003668LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00003669 const CompoundAssignOperator *E) {
3670 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00003671 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00003672 switch (E->getOpcode()) {
3673#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00003674 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00003675 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003676 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00003677 COMPOUND_OP(Mul);
3678 COMPOUND_OP(Div);
3679 COMPOUND_OP(Rem);
3680 COMPOUND_OP(Add);
3681 COMPOUND_OP(Sub);
3682 COMPOUND_OP(Shl);
3683 COMPOUND_OP(Shr);
3684 COMPOUND_OP(And);
3685 COMPOUND_OP(Xor);
3686 COMPOUND_OP(Or);
3687#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00003688
John McCalle3027922010-08-25 11:45:40 +00003689 case BO_PtrMemD:
3690 case BO_PtrMemI:
3691 case BO_Mul:
3692 case BO_Div:
3693 case BO_Rem:
3694 case BO_Add:
3695 case BO_Sub:
3696 case BO_Shl:
3697 case BO_Shr:
3698 case BO_LT:
3699 case BO_GT:
3700 case BO_LE:
3701 case BO_GE:
3702 case BO_EQ:
3703 case BO_NE:
3704 case BO_And:
3705 case BO_Xor:
3706 case BO_Or:
3707 case BO_LAnd:
3708 case BO_LOr:
3709 case BO_Assign:
3710 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00003711 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00003712 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003713
Douglas Gregor914af212010-04-23 04:16:32 +00003714 llvm_unreachable("Unhandled compound assignment operator");
3715}