blob: 19d453d3caa4390e14515d57f9faf7cd8106ff3d [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner7f02f722007-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 McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Frontend/CodeGenOptions.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "llvm/IR/CFG.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalVariable.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Module.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Lang Hamesbe9af122012-10-02 04:45:10 +000048 bool FPContractable;
Chris Lattner9a207232010-06-26 21:48:21 +000049 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000050};
51
John McCall404cd162010-11-13 01:35:44 +000052static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
57}
58
Benjamin Kramer85b45212009-11-28 19:45:26 +000059class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000060 : public StmtVisitor<ScalarExprEmitter, Value*> {
61 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000062 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000064 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000065public:
66
Mike Stump7f79f9b2009-05-29 15:46:01 +000067 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000068 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000069 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000070 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000071
Chris Lattner7f02f722007-08-24 05:35:26 +000072 //===--------------------------------------------------------------------===//
73 // Utilities
74 //===--------------------------------------------------------------------===//
75
Mike Stump7f79f9b2009-05-29 15:46:01 +000076 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000077 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
79 return I;
80 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000081
Chris Lattner2acc6e32011-07-18 04:24:23 +000082 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000083 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith7ac9ef12012-09-08 02:08:36 +000084 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith2c9f87c2012-08-24 00:54:33 +000086 }
Chris Lattner7f02f722007-08-24 05:35:26 +000087
Stephen Hines176edba2014-12-01 14:53:08 -080088 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerKind>> Checks,
89 const BinOpInfo &Info);
Richard Smith4def70d2012-10-09 19:52:38 +000090
Nick Lewycky4ee7dc22013-10-02 02:29:49 +000091 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
92 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000093 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000094
Stephen Hines176edba2014-12-01 14:53:08 -080095 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
96 const AlignValueAttr *AVAttr = nullptr;
97 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
98 const ValueDecl *VD = DRE->getDecl();
99
100 if (VD->getType()->isReferenceType()) {
101 if (const auto *TTy =
102 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
103 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
104 } else {
105 // Assumptions for function parameters are emitted at the start of the
106 // function, so there is no need to repeat that here.
107 if (isa<ParmVarDecl>(VD))
108 return;
109
110 AVAttr = VD->getAttr<AlignValueAttr>();
111 }
112 }
113
114 if (!AVAttr)
115 if (const auto *TTy =
116 dyn_cast<TypedefType>(E->getType()))
117 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
118
119 if (!AVAttr)
120 return;
121
122 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
123 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
124 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
125 }
126
Chris Lattner7f02f722007-08-24 05:35:26 +0000127 /// EmitLoadOfLValue - Given an expression with complex type that represents a
128 /// value l-value, this method emits the address of the l-value, then loads
129 /// and returns the result.
130 Value *EmitLoadOfLValue(const Expr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -0800131 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
132 E->getExprLoc());
133
134 EmitLValueAlignmentAssumption(E, V);
135 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000136 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000137
Chris Lattner9abc84e2007-08-26 16:42:57 +0000138 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000139 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000140 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000141
Richard Smithb2aa66c2012-10-12 22:57:06 +0000142 /// \brief Emit a check that a conversion to or from a floating-point type
143 /// does not overflow.
144 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
145 Value *Src, QualType SrcType,
146 QualType DstType, llvm::Type *DstTy);
147
Chris Lattner3707b252007-08-26 06:48:56 +0000148 /// EmitScalarConversion - Emit a conversion from the specified type to the
149 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000150 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
151
152 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000153 /// complex type to the specified destination type, where the destination type
154 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000155 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
156 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000157
Anders Carlssona40a9f32010-05-22 17:45:10 +0000158 /// EmitNullValue - Emit a value that corresponds to null for the given type.
159 Value *EmitNullValue(QualType Ty);
160
John McCalldaa8e4e2010-11-15 09:13:47 +0000161 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
162 Value *EmitFloatToBoolConversion(Value *V) {
163 // Compare against 0.0 for fp scalars.
164 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
165 return Builder.CreateFCmpUNE(V, Zero, "tobool");
166 }
167
168 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
169 Value *EmitPointerToBoolConversion(Value *V) {
170 Value *Zero = llvm::ConstantPointerNull::get(
171 cast<llvm::PointerType>(V->getType()));
172 return Builder.CreateICmpNE(V, Zero, "tobool");
173 }
174
175 Value *EmitIntToBoolConversion(Value *V) {
176 // Because of the type rules of C, we often end up computing a
177 // logical value, then zero extending it to int, then wanting it
178 // as a logical value again. Optimize this common case.
179 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
180 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
181 Value *Result = ZI->getOperand(0);
182 // If there aren't any more uses, zap the instruction to save space.
183 // Note that there can be more uses, for example if this
184 // is the result of an assignment.
185 if (ZI->use_empty())
186 ZI->eraseFromParent();
187 return Result;
188 }
189 }
190
Chris Lattner48431f92011-04-19 22:55:03 +0000191 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000192 }
193
Chris Lattner7f02f722007-08-24 05:35:26 +0000194 //===--------------------------------------------------------------------===//
195 // Visitor Methods
196 //===--------------------------------------------------------------------===//
197
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000198 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000199 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
200 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000201
Chris Lattner7f02f722007-08-24 05:35:26 +0000202 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000203 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000204 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000205 }
206 Value *VisitExpr(Expr *S);
Craig Topperd10e5c22013-07-26 06:16:11 +0000207
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000208 Value *VisitParenExpr(ParenExpr *PE) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000209 return Visit(PE->getSubExpr());
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000210 }
John McCall91a57552011-07-15 05:09:51 +0000211 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000212 return Visit(E->getReplacement());
John McCall91a57552011-07-15 05:09:51 +0000213 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000214 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
215 return Visit(GE->getResultExpr());
216 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000217
218 // Leaves.
219 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000220 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000221 }
222 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000223 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000224 }
225 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000226 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000227 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000228 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
229 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
230 }
Nate Begemane7579b52007-11-15 05:40:03 +0000231 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000232 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000233 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000234 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000235 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000236 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000237 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000238 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000239 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000240 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000241 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000242 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000243 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
244 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000245 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000246
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000247 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000248 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000249 }
John McCalle996ffd2011-02-16 08:02:54 +0000250
John McCall4b9c2d22011-11-06 09:01:30 +0000251 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
252 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
253 }
254
John McCalle996ffd2011-02-16 08:02:54 +0000255 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000256 if (E->isGLValue())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000257 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
John McCalle996ffd2011-02-16 08:02:54 +0000258
259 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000260 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000261 }
John McCalldd2ecee2012-03-10 03:05:10 +0000262
Chris Lattner7f02f722007-08-24 05:35:26 +0000263 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000264 Value *VisitDeclRefExpr(DeclRefExpr *E) {
265 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000266 if (result.isReference())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000267 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
268 E->getExprLoc());
John McCalldd2ecee2012-03-10 03:05:10 +0000269 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000270 }
John McCallf4b88a42012-03-10 09:33:50 +0000271 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000272 }
273
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000274 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
275 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000276 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000277 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
278 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000279 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000280 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000281 return EmitLoadOfLValue(E);
282 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000283 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000284 if (E->getMethodDecl() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700285 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000286 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000287 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000288 }
289
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000290 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000291 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000292 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000293 return V;
294 }
295
Chris Lattner7f02f722007-08-24 05:35:26 +0000296 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000297 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkel414a1bd2013-09-18 03:29:45 +0000298 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000299 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000300 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000301 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
302 return EmitLoadOfLValue(E);
303 }
Devang Patel35634f52007-10-24 17:18:43 +0000304
Nate Begeman0533b302009-10-18 20:10:40 +0000305 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000306
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000307 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000308 return EmitNullValue(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000309 }
John McCallbc8d40d2011-06-24 21:55:10 +0000310 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000311 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000312 CGF.EmitVariablyModifiedType(E->getType());
Stephen Hines176edba2014-12-01 14:53:08 -0800313
314 if (CGDebugInfo *DI = CGF.getDebugInfo())
315 DI->EmitExplicitCastType(E->getType());
316
John McCallbc8d40d2011-06-24 21:55:10 +0000317 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 }
John McCallbc8d40d2011-06-24 21:55:10 +0000319 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000320
321 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000322 if (E->getCallReturnType()->isReferenceType())
323 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000324
Stephen Hines176edba2014-12-01 14:53:08 -0800325 Value *V = CGF.EmitCallExpr(E).getScalarVal();
326
327 EmitLValueAlignmentAssumption(E, V);
328 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000329 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000330
Chris Lattner33793202007-08-31 22:09:40 +0000331 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000332
Chris Lattner7f02f722007-08-24 05:35:26 +0000333 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000334 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000335 LValue LV = EmitLValue(E->getSubExpr());
336 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000337 }
338 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000339 LValue LV = EmitLValue(E->getSubExpr());
340 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000341 }
342 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000343 LValue LV = EmitLValue(E->getSubExpr());
344 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000345 }
346 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000347 LValue LV = EmitLValue(E->getSubExpr());
348 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000349 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000350
Anton Yartsev683564a2011-02-07 02:17:30 +0000351 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
352 llvm::Value *InVal,
353 llvm::Value *NextVal,
354 bool IsInc);
355
Chris Lattner8c11a652010-06-26 22:09:34 +0000356 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
357 bool isInc, bool isPre);
358
Craig Topperd10e5c22013-07-26 06:16:11 +0000359
Chris Lattner7f02f722007-08-24 05:35:26 +0000360 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000361 if (isa<MemberPointerType>(E->getType())) // never sugared
362 return CGF.CGM.getMemberPointerConstant(E);
363
Chris Lattner7f02f722007-08-24 05:35:26 +0000364 return EmitLValue(E->getSubExpr()).getAddress();
365 }
John McCallfd569002010-12-04 12:43:24 +0000366 Value *VisitUnaryDeref(const UnaryOperator *E) {
367 if (E->getType()->isVoidType())
368 return Visit(E->getSubExpr()); // the actual value should be unused
369 return EmitLoadOfLValue(E);
370 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000371 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000372 // This differs from gcc, though, most likely due to a bug in gcc.
373 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000374 return Visit(E->getSubExpr());
375 }
376 Value *VisitUnaryMinus (const UnaryOperator *E);
377 Value *VisitUnaryNot (const UnaryOperator *E);
378 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000379 Value *VisitUnaryReal (const UnaryOperator *E);
380 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000381 Value *VisitUnaryExtension(const UnaryOperator *E) {
382 return Visit(E->getSubExpr());
383 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000384
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000385 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000386 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000387 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000388 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000389
Chris Lattner04421082008-04-08 04:40:51 +0000390 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
391 return Visit(DAE->getExpr());
392 }
Richard Smithc3bf52c2013-04-20 22:23:05 +0000393 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
394 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
395 return Visit(DIE->getExpr());
396 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000397 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
398 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000399 }
400
John McCall4765fa02010-12-06 08:20:24 +0000401 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000402 CGF.enterFullExpression(E);
403 CodeGenFunction::RunCleanupsScope Scope(CGF);
Stephen Hines176edba2014-12-01 14:53:08 -0800404 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000405 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000406 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
407 return CGF.EmitCXXNewExpr(E);
408 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000409 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
410 CGF.EmitCXXDeleteExpr(E);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700411 return nullptr;
Anders Carlsson60e282c2009-08-16 21:13:42 +0000412 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000413
Stephen Hines651f13c2014-04-23 16:59:28 -0700414 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000415 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000416 }
417
John Wiegley21ff2e52011-04-28 00:16:57 +0000418 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
419 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
420 }
421
John Wiegley55262202011-04-25 06:54:41 +0000422 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
423 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
424 }
425
Douglas Gregora71d8192009-09-04 17:36:40 +0000426 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
427 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000428 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000429 // operator (), and the result of such a call has type void. The only
430 // effect is the evaluation of the postfix-expression before the dot or
431 // arrow.
432 CGF.EmitScalarExpr(E->getBase());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700433 return nullptr;
Douglas Gregora71d8192009-09-04 17:36:40 +0000434 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000435
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000436 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000437 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000438 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000439
440 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
441 CGF.EmitCXXThrowExpr(E);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700442 return nullptr;
Anders Carlsson756b5c42009-10-30 01:42:31 +0000443 }
444
Sebastian Redl98294de2010-09-10 21:04:00 +0000445 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000446 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000447 }
448
Chris Lattner7f02f722007-08-24 05:35:26 +0000449 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000450 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000451 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000452 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000453 case LangOptions::SOB_Defined:
454 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000455 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -0800456 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +0000457 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
458 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000459 case LangOptions::SOB_Trapping:
460 return EmitOverflowCheckedBinOp(Ops);
461 }
462 }
Richard Smithd6396a62012-11-05 22:21:05 +0000463
Stephen Hines176edba2014-12-01 14:53:08 -0800464 if (Ops.Ty->isUnsignedIntegerType() &&
465 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietzb8540362012-11-27 15:01:55 +0000466 return EmitOverflowCheckedBinOp(Ops);
467
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000468 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000469 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000470 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
471 }
Mike Stump2add4732009-04-01 20:28:16 +0000472 /// Create a binary op that checks for overflow.
473 /// Currently only supports +, - and *.
474 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000475
Chris Lattner80230302010-09-11 21:47:09 +0000476 // Check for undefined division and modulus behaviors.
Craig Topperd10e5c22013-07-26 06:16:11 +0000477 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner80230302010-09-11 21:47:09 +0000478 llvm::Value *Zero,bool isDiv);
David Tweed7a834212013-01-07 16:43:27 +0000479 // Common helper for getting how wide LHS of shift is.
480 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner7f02f722007-08-24 05:35:26 +0000481 Value *EmitDiv(const BinOpInfo &Ops);
482 Value *EmitRem(const BinOpInfo &Ops);
483 Value *EmitAdd(const BinOpInfo &Ops);
484 Value *EmitSub(const BinOpInfo &Ops);
485 Value *EmitShl(const BinOpInfo &Ops);
486 Value *EmitShr(const BinOpInfo &Ops);
487 Value *EmitAnd(const BinOpInfo &Ops) {
488 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
489 }
490 Value *EmitXor(const BinOpInfo &Ops) {
491 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
492 }
493 Value *EmitOr (const BinOpInfo &Ops) {
494 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
495 }
496
Chris Lattner1f1ded92007-08-24 21:00:35 +0000497 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000498 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
499 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000500 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000501
Chris Lattner3ccf7742007-08-26 21:41:21 +0000502 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000503 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
504
505 // Binary operators and binary compound assignment operators.
506#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000507 Value *VisitBin ## OP(const BinaryOperator *E) { \
508 return Emit ## OP(EmitBinOps(E)); \
509 } \
510 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
511 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000512 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000513 HANDLEBINOP(Mul)
514 HANDLEBINOP(Div)
515 HANDLEBINOP(Rem)
516 HANDLEBINOP(Add)
517 HANDLEBINOP(Sub)
518 HANDLEBINOP(Shl)
519 HANDLEBINOP(Shr)
520 HANDLEBINOP(And)
521 HANDLEBINOP(Xor)
522 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000523#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000524
Chris Lattner7f02f722007-08-24 05:35:26 +0000525 // Comparisons.
526 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
527 unsigned SICmpOpc, unsigned FCmpOpc);
528#define VISITCOMP(CODE, UI, SI, FP) \
529 Value *VisitBin##CODE(const BinaryOperator *E) { \
530 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
531 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000532 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
533 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
534 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
535 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
536 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
537 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000538#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000539
Chris Lattner7f02f722007-08-24 05:35:26 +0000540 Value *VisitBinAssign (const BinaryOperator *E);
541
542 Value *VisitBinLAnd (const BinaryOperator *E);
543 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000544 Value *VisitBinComma (const BinaryOperator *E);
545
Eli Friedman25b825d2009-11-18 09:41:26 +0000546 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
547 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
548
Chris Lattner7f02f722007-08-24 05:35:26 +0000549 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000550 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000551 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000552 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000553 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000554 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
555 return CGF.EmitObjCStringLiteral(E);
556 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000557 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
558 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000559 }
560 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
561 return CGF.EmitObjCArrayLiteral(E);
562 }
563 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
564 return CGF.EmitObjCDictionaryLiteral(E);
565 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000566 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000567 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000568};
569} // end anonymous namespace.
570
571//===----------------------------------------------------------------------===//
572// Utilities
573//===----------------------------------------------------------------------===//
574
Chris Lattner9abc84e2007-08-26 16:42:57 +0000575/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000576/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000577Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000578 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000579
John McCalldaa8e4e2010-11-15 09:13:47 +0000580 if (SrcType->isRealFloatingType())
581 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000582
John McCall0bab0cd2010-08-23 01:21:21 +0000583 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
584 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000585
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000586 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000587 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000588
John McCalldaa8e4e2010-11-15 09:13:47 +0000589 if (isa<llvm::IntegerType>(Src->getType()))
590 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000591
John McCalldaa8e4e2010-11-15 09:13:47 +0000592 assert(isa<llvm::PointerType>(Src->getType()));
593 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000594}
595
Richard Smithb2aa66c2012-10-12 22:57:06 +0000596void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
597 QualType OrigSrcType,
598 Value *Src, QualType SrcType,
599 QualType DstType,
600 llvm::Type *DstTy) {
Stephen Hines176edba2014-12-01 14:53:08 -0800601 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000602 using llvm::APFloat;
603 using llvm::APSInt;
604
605 llvm::Type *SrcTy = Src->getType();
606
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700607 llvm::Value *Check = nullptr;
Richard Smithb2aa66c2012-10-12 22:57:06 +0000608 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
609 // Integer to floating-point. This can fail for unsigned short -> __half
610 // or unsigned __int128 -> float.
611 assert(DstType->isFloatingType());
612 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
613
614 APFloat LargestFloat =
615 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
616 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
617
618 bool IsExact;
619 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
620 &IsExact) != APFloat::opOK)
621 // The range of representable values of this floating point type includes
622 // all values of this integer type. Don't need an overflow check.
623 return;
624
625 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
626 if (SrcIsUnsigned)
627 Check = Builder.CreateICmpULE(Src, Max);
628 else {
629 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
630 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
631 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
632 Check = Builder.CreateAnd(GE, LE);
633 }
634 } else {
Richard Smithb2aa66c2012-10-12 22:57:06 +0000635 const llvm::fltSemantics &SrcSema =
636 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000637 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith50876452013-03-27 23:20:25 +0000638 // Floating-point to integer. This has undefined behavior if the source is
639 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
640 // to an integer).
Richard Smithb2aa66c2012-10-12 22:57:06 +0000641 unsigned Width = CGF.getContext().getIntWidth(DstType);
642 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
643
644 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith50876452013-03-27 23:20:25 +0000645 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000646 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
647 APFloat::opOverflow)
648 // Don't need an overflow check for lower bound. Just check for
649 // -Inf/NaN.
Richard Smithaa624952013-03-19 00:01:12 +0000650 MinSrc = APFloat::getInf(SrcSema, true);
651 else
652 // Find the largest value which is too small to represent (before
653 // truncation toward zero).
654 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000655
656 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith50876452013-03-27 23:20:25 +0000657 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000658 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
659 APFloat::opOverflow)
660 // Don't need an overflow check for upper bound. Just check for
661 // +Inf/NaN.
Richard Smithaa624952013-03-19 00:01:12 +0000662 MaxSrc = APFloat::getInf(SrcSema, false);
663 else
664 // Find the smallest value which is too large to represent (before
665 // truncation toward zero).
666 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000667
Richard Smith50876452013-03-27 23:20:25 +0000668 // If we're converting from __half, convert the range to float to match
669 // the type of src.
670 if (OrigSrcType->isHalfType()) {
671 const llvm::fltSemantics &Sema =
672 CGF.getContext().getFloatTypeSemantics(SrcType);
673 bool IsInexact;
674 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
675 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
676 }
Richard Smithb2aa66c2012-10-12 22:57:06 +0000677
Richard Smithaa624952013-03-19 00:01:12 +0000678 llvm::Value *GE =
679 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
680 llvm::Value *LE =
681 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
682 Check = Builder.CreateAnd(GE, LE);
683 } else {
Richard Smith50876452013-03-27 23:20:25 +0000684 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
685 //
686 // Floating-point to floating-point. This has undefined behavior if the
687 // source is not in the range of representable values of the destination
688 // type. The C and C++ standards are spectacularly unclear here. We
689 // diagnose finite out-of-range conversions, but allow infinities and NaNs
690 // to convert to the corresponding value in the smaller type.
691 //
692 // C11 Annex F gives all such conversions defined behavior for IEC 60559
693 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
694 // does not.
695
696 // Converting from a lower rank to a higher rank can never have
697 // undefined behavior, since higher-rank types must have a superset
698 // of values of lower-rank types.
699 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
700 return;
701
702 assert(!OrigSrcType->isHalfType() &&
703 "should not check conversion from __half, it has the lowest rank");
704
705 const llvm::fltSemantics &DstSema =
706 CGF.getContext().getFloatTypeSemantics(DstType);
707 APFloat MinBad = APFloat::getLargest(DstSema, false);
708 APFloat MaxBad = APFloat::getInf(DstSema, false);
709
710 bool IsInexact;
711 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
712 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
713
714 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
715 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smithaa624952013-03-19 00:01:12 +0000716 llvm::Value *GE =
Richard Smith50876452013-03-27 23:20:25 +0000717 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smithaa624952013-03-19 00:01:12 +0000718 llvm::Value *LE =
Richard Smith50876452013-03-27 23:20:25 +0000719 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
720 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smithaa624952013-03-19 00:01:12 +0000721 }
Richard Smithb2aa66c2012-10-12 22:57:06 +0000722 }
723
724 // FIXME: Provide a SourceLocation.
725 llvm::Constant *StaticArgs[] = {
726 CGF.EmitCheckTypeDescriptor(OrigSrcType),
727 CGF.EmitCheckTypeDescriptor(DstType)
728 };
Stephen Hines176edba2014-12-01 14:53:08 -0800729 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
730 "float_cast_overflow", StaticArgs, OrigSrc);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000731}
732
Chris Lattner3707b252007-08-26 06:48:56 +0000733/// EmitScalarConversion - Emit a conversion from the specified type to the
734/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000735Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
736 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000737 SrcType = CGF.getContext().getCanonicalType(SrcType);
738 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000739 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000740
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700741 if (DstType->isVoidType()) return nullptr;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000742
Richard Smithb2aa66c2012-10-12 22:57:06 +0000743 llvm::Value *OrigSrc = Src;
744 QualType OrigSrcType = SrcType;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000745 llvm::Type *SrcTy = Src->getType();
746
Joey Gouly19dbb202013-01-23 11:56:20 +0000747 // If casting to/from storage-only half FP, use special intrinsics.
Stephen Hines176edba2014-12-01 14:53:08 -0800748 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
749 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
750 Src = Builder.CreateCall(
751 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
752 CGF.CGM.FloatTy),
753 Src);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000754 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000755 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000756 }
757
Chris Lattner3707b252007-08-26 06:48:56 +0000758 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000759 if (DstType->isBooleanType())
760 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000761
Chris Lattner2acc6e32011-07-18 04:24:23 +0000762 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000763
764 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000765 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000766 return Src;
767
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000768 // Handle pointer conversions next: pointers can only be converted to/from
769 // other pointers and integers. Check for pointer types in terms of LLVM, as
770 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000771 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000772 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000773 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000774 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000775
Chris Lattner3707b252007-08-26 06:48:56 +0000776 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000777 // First, convert to the correct width so that we control the kind of
778 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000779 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000780 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000781 llvm::Value* IntResult =
782 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
783 // Then, cast to pointer.
784 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000785 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000786
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000787 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000788 // Must be an ptr to int cast.
789 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000790 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000791 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000792
Nate Begeman213541a2008-04-18 23:10:10 +0000793 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000794 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000795 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000796 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000797 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
798
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000799 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000800 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer0b227082013-01-01 20:08:10 +0000801 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000802 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000803
Chris Lattner3b1ae002008-02-02 04:51:41 +0000804 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000805 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000806 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000807 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000808
Chris Lattner3707b252007-08-26 06:48:56 +0000809 // Finally, we have the arithmetic types: real int/float.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700810 Value *Res = nullptr;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000811 llvm::Type *ResTy = DstTy;
812
Richard Smithb2aa66c2012-10-12 22:57:06 +0000813 // An overflowing conversion has undefined behavior if either the source type
814 // or the destination type is a floating-point type.
Stephen Hines176edba2014-12-01 14:53:08 -0800815 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smithb2aa66c2012-10-12 22:57:06 +0000816 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Will Dietz4f45bc02013-01-18 11:30:38 +0000817 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
818 DstTy);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000819
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000820 // Cast to half via float
Stephen Hines176edba2014-12-01 14:53:08 -0800821 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
822 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
Chris Lattner8b418682012-02-07 00:39:47 +0000823 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000824
825 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000826 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000827 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000828 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000829 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000830 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000831 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000832 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
833 } else if (isa<llvm::IntegerType>(DstTy)) {
834 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000835 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000836 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000837 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000838 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
839 } else {
840 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
841 "Unknown real conversion");
842 if (DstTy->getTypeID() < SrcTy->getTypeID())
843 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
844 else
845 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000846 }
847
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000848 if (DstTy != ResTy) {
849 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
Stephen Hines176edba2014-12-01 14:53:08 -0800850 Res = Builder.CreateCall(
851 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
852 Res);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000853 }
854
855 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000856}
857
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000858/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
859/// type to the specified destination type, where the destination type is an
860/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000861Value *ScalarExprEmitter::
862EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
863 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000864 // Get the source element type.
John McCall9d232c82013-03-07 21:37:08 +0000865 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000866
Chris Lattnered70f0a2007-08-26 16:52:28 +0000867 // Handle conversions to bool first, they are special: comparisons against 0.
868 if (DstTy->isBooleanType()) {
869 // Complex != 0 -> (Real != 0) | (Imag != 0)
870 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
871 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
872 return Builder.CreateOr(Src.first, Src.second, "tobool");
873 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000874
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000875 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
876 // the imaginary part of the complex value is discarded and the value of the
877 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000878 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000879 return EmitScalarConversion(Src.first, SrcTy, DstTy);
880}
881
Anders Carlssona40a9f32010-05-22 17:45:10 +0000882Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000883 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlssona40a9f32010-05-22 17:45:10 +0000884}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000885
Richard Smith4def70d2012-10-09 19:52:38 +0000886/// \brief Emit a sanitization check for the given "binary" operation (which
887/// might actually be a unary increment which has been lowered to a binary
Stephen Hines176edba2014-12-01 14:53:08 -0800888/// operation). The check passes if all values in \p Checks (which are \c i1),
889/// are \c true.
890void ScalarExprEmitter::EmitBinOpCheck(
891 ArrayRef<std::pair<Value *, SanitizerKind>> Checks, const BinOpInfo &Info) {
892 assert(CGF.IsSanitizerScope);
Richard Smith4def70d2012-10-09 19:52:38 +0000893 StringRef CheckName;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000894 SmallVector<llvm::Constant *, 4> StaticData;
895 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smith4def70d2012-10-09 19:52:38 +0000896
897 BinaryOperatorKind Opcode = Info.Opcode;
898 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
899 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
900
901 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
902 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
903 if (UO && UO->getOpcode() == UO_Minus) {
904 CheckName = "negate_overflow";
905 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
906 DynamicData.push_back(Info.RHS);
907 } else {
908 if (BinaryOperator::isShiftOp(Opcode)) {
909 // Shift LHS negative or too large, or RHS out of bounds.
910 CheckName = "shift_out_of_bounds";
911 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
912 StaticData.push_back(
913 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
914 StaticData.push_back(
915 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
916 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
917 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
918 CheckName = "divrem_overflow";
Will Dietz822023a2013-01-07 22:25:52 +0000919 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000920 } else {
Stephen Hines176edba2014-12-01 14:53:08 -0800921 // Arithmetic overflow (+, -, *).
Richard Smith4def70d2012-10-09 19:52:38 +0000922 switch (Opcode) {
923 case BO_Add: CheckName = "add_overflow"; break;
924 case BO_Sub: CheckName = "sub_overflow"; break;
925 case BO_Mul: CheckName = "mul_overflow"; break;
926 default: llvm_unreachable("unexpected opcode for bin op check");
927 }
Will Dietz822023a2013-01-07 22:25:52 +0000928 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000929 }
930 DynamicData.push_back(Info.LHS);
931 DynamicData.push_back(Info.RHS);
932 }
933
Stephen Hines176edba2014-12-01 14:53:08 -0800934 CGF.EmitCheck(Checks, CheckName, StaticData, DynamicData);
Richard Smith4def70d2012-10-09 19:52:38 +0000935}
936
Chris Lattner7f02f722007-08-24 05:35:26 +0000937//===----------------------------------------------------------------------===//
938// Visitor Methods
939//===----------------------------------------------------------------------===//
940
941Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000942 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000943 if (E->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700944 return nullptr;
Owen Anderson03e20502009-07-30 23:11:26 +0000945 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000946}
947
Eli Friedmand38617c2008-05-14 19:38:39 +0000948Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000949 // Vector Mask Case
Craig Topperd10e5c22013-07-26 06:16:11 +0000950 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000951 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000952 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
953 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
954 Value *Mask;
Craig Topperd10e5c22013-07-26 06:16:11 +0000955
Chris Lattner2acc6e32011-07-18 04:24:23 +0000956 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000957 unsigned LHSElts = LTy->getNumElements();
958
959 if (E->getNumSubExprs() == 3) {
960 Mask = CGF.EmitScalarExpr(E->getExpr(2));
Craig Topperd10e5c22013-07-26 06:16:11 +0000961
Nate Begeman37b6a572010-06-08 00:16:34 +0000962 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000963 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000964 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000965 concat.push_back(Builder.getInt32(2*i));
966 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000967 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000968
Chris Lattnerfb018d12011-02-15 00:14:06 +0000969 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000970 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
971 LHSElts *= 2;
972 } else {
973 Mask = RHS;
974 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000975
Chris Lattner2acc6e32011-07-18 04:24:23 +0000976 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000977 llvm::Constant* EltMask;
Craig Topperd10e5c22013-07-26 06:16:11 +0000978
Craig Topper2f665122013-08-01 06:42:40 +0000979 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
980 llvm::NextPowerOf2(LHSElts-1)-1);
Craig Topperd10e5c22013-07-26 06:16:11 +0000981
Nate Begeman37b6a572010-06-08 00:16:34 +0000982 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000983 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
984 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000985 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Topperd10e5c22013-07-26 06:16:11 +0000986
Nate Begeman37b6a572010-06-08 00:16:34 +0000987 // newv = undef
988 // mask = mask & maskbits
989 // for each elt
990 // n = extract mask i
991 // x = extract val n
992 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000993 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper34d55e12013-07-27 05:00:42 +0000994 MTy->getNumElements());
Nate Begeman37b6a572010-06-08 00:16:34 +0000995 Value* NewV = llvm::UndefValue::get(RTy);
996 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700997 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman87b9c032012-04-05 21:48:40 +0000998 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Topperd10e5c22013-07-26 06:16:11 +0000999
Nate Begeman37b6a572010-06-08 00:16:34 +00001000 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +00001001 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +00001002 }
1003 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +00001004 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001005
Eli Friedmand38617c2008-05-14 19:38:39 +00001006 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1007 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Topperd10e5c22013-07-26 06:16:11 +00001008
Chris Lattner5f9e2722011-07-23 10:55:15 +00001009 SmallVector<llvm::Constant*, 32> indices;
Craig Topper72c422c2013-08-01 04:51:48 +00001010 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper6f4f8082013-08-03 17:40:38 +00001011 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1012 // Check for -1 and output it as undef in the IR.
1013 if (Idx.isSigned() && Idx.isAllOnesValue())
1014 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1015 else
1016 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001017 }
1018
Chris Lattnerfb018d12011-02-15 00:14:06 +00001019 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +00001020 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1021}
Hal Finkel414a1bd2013-09-18 03:29:45 +00001022
1023Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1024 QualType SrcType = E->getSrcExpr()->getType(),
1025 DstType = E->getType();
1026
1027 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1028
1029 SrcType = CGF.getContext().getCanonicalType(SrcType);
1030 DstType = CGF.getContext().getCanonicalType(DstType);
1031 if (SrcType == DstType) return Src;
1032
1033 assert(SrcType->isVectorType() &&
1034 "ConvertVector source type must be a vector");
1035 assert(DstType->isVectorType() &&
1036 "ConvertVector destination type must be a vector");
1037
1038 llvm::Type *SrcTy = Src->getType();
1039 llvm::Type *DstTy = ConvertType(DstType);
1040
1041 // Ignore conversions like int -> uint.
1042 if (SrcTy == DstTy)
1043 return Src;
1044
1045 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1046 DstEltType = DstType->getAs<VectorType>()->getElementType();
1047
1048 assert(SrcTy->isVectorTy() &&
1049 "ConvertVector source IR type must be a vector");
1050 assert(DstTy->isVectorTy() &&
1051 "ConvertVector destination IR type must be a vector");
1052
1053 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1054 *DstEltTy = DstTy->getVectorElementType();
1055
1056 if (DstEltType->isBooleanType()) {
1057 assert((SrcEltTy->isFloatingPointTy() ||
1058 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1059
1060 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1061 if (SrcEltTy->isFloatingPointTy()) {
1062 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1063 } else {
1064 return Builder.CreateICmpNE(Src, Zero, "tobool");
1065 }
1066 }
1067
1068 // We have the arithmetic types: real int/float.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001069 Value *Res = nullptr;
Hal Finkel414a1bd2013-09-18 03:29:45 +00001070
1071 if (isa<llvm::IntegerType>(SrcEltTy)) {
1072 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1073 if (isa<llvm::IntegerType>(DstEltTy))
1074 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1075 else if (InputSigned)
1076 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1077 else
1078 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1079 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1080 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1081 if (DstEltType->isSignedIntegerOrEnumerationType())
1082 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1083 else
1084 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1085 } else {
1086 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1087 "Unknown real conversion");
1088 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1089 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1090 else
1091 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1092 }
1093
1094 return Res;
1095}
1096
Eli Friedman28665272009-11-26 03:22:21 +00001097Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +00001098 llvm::APSInt Value;
1099 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +00001100 if (E->isArrow())
1101 CGF.EmitScalarExpr(E->getBase());
1102 else
1103 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +00001104 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +00001105 }
Devang Patel78ba3d42010-10-04 21:46:04 +00001106
Eli Friedman28665272009-11-26 03:22:21 +00001107 return EmitLoadOfLValue(E);
1108}
Eli Friedmand38617c2008-05-14 19:38:39 +00001109
Chris Lattner7f02f722007-08-24 05:35:26 +00001110Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001111 TestAndClearIgnoreResultAssign();
1112
Chris Lattner7f02f722007-08-24 05:35:26 +00001113 // Emit subscript expressions in rvalue context's. For most cases, this just
1114 // loads the lvalue formed by the subscript expr. However, we have to be
1115 // careful, because the base of a vector subscript is occasionally an rvalue,
1116 // so we can't get it as an lvalue.
1117 if (!E->getBase()->getType()->isVectorType())
1118 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001119
Chris Lattner7f02f722007-08-24 05:35:26 +00001120 // Handle the vector case. The base must be a vector, the index must be an
1121 // integer value.
1122 Value *Base = Visit(E->getBase());
1123 Value *Idx = Visit(E->getIdx());
Richard Smitha0a628f2013-02-23 02:53:19 +00001124 QualType IdxTy = E->getIdx()->getType();
1125
Stephen Hines176edba2014-12-01 14:53:08 -08001126 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smitha0a628f2013-02-23 02:53:19 +00001127 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1128
Chris Lattner7f02f722007-08-24 05:35:26 +00001129 return Builder.CreateExtractElement(Base, Idx, "vecext");
1130}
1131
Nate Begeman0533b302009-10-18 20:10:40 +00001132static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001133 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +00001134 int MV = SVI->getMaskValue(Idx);
Craig Topperd10e5c22013-07-26 06:16:11 +00001135 if (MV == -1)
Nate Begeman0533b302009-10-18 20:10:40 +00001136 return llvm::UndefValue::get(I32Ty);
1137 return llvm::ConstantInt::get(I32Ty, Off+MV);
1138}
1139
1140Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1141 bool Ignore = TestAndClearIgnoreResultAssign();
1142 (void)Ignore;
1143 assert (Ignore == false && "init list ignored");
1144 unsigned NumInitElements = E->getNumInits();
Craig Topperd10e5c22013-07-26 06:16:11 +00001145
Nate Begeman0533b302009-10-18 20:10:40 +00001146 if (E->hadArrayRangeDesignator())
1147 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Topperd10e5c22013-07-26 06:16:11 +00001148
Chris Lattner2acc6e32011-07-18 04:24:23 +00001149 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +00001150 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Topperd10e5c22013-07-26 06:16:11 +00001151
Sebastian Redlcea8d962011-09-24 17:48:14 +00001152 if (!VType) {
1153 if (NumInitElements == 0) {
1154 // C++11 value-initialization for the scalar.
1155 return EmitNullValue(E->getType());
1156 }
1157 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +00001158 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +00001159 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001160
Nate Begeman0533b302009-10-18 20:10:40 +00001161 unsigned ResElts = VType->getNumElements();
Craig Topperd10e5c22013-07-26 06:16:11 +00001162
1163 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman0533b302009-10-18 20:10:40 +00001164 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1165 // us to fold the shuffle for the swizzle into the shuffle for the vector
1166 // initializer, since LLVM optimizers generally do not want to touch
1167 // shuffles.
1168 unsigned CurIdx = 0;
1169 bool VIsUndefShuffle = false;
1170 llvm::Value *V = llvm::UndefValue::get(VType);
1171 for (unsigned i = 0; i != NumInitElements; ++i) {
1172 Expr *IE = E->getInit(i);
1173 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001174 SmallVector<llvm::Constant*, 16> Args;
Craig Topperd10e5c22013-07-26 06:16:11 +00001175
Chris Lattner2acc6e32011-07-18 04:24:23 +00001176 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001177
Nate Begeman0533b302009-10-18 20:10:40 +00001178 // Handle scalar elements. If the scalar initializer is actually one
Craig Topperd10e5c22013-07-26 06:16:11 +00001179 // element of a different vector of the same width, use shuffle instead of
Nate Begeman0533b302009-10-18 20:10:40 +00001180 // extract+insert.
1181 if (!VVT) {
1182 if (isa<ExtVectorElementExpr>(IE)) {
1183 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1184
1185 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1186 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001187 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman0533b302009-10-18 20:10:40 +00001188 if (CurIdx == 0) {
1189 // insert into undef -> shuffle (src, undef)
1190 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +00001191 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001192
1193 LHS = EI->getVectorOperand();
1194 RHS = V;
1195 VIsUndefShuffle = true;
1196 } else if (VIsUndefShuffle) {
1197 // insert into undefshuffle && size match -> shuffle (v, src)
1198 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1199 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001200 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +00001201 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001202 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1203
Nate Begeman0533b302009-10-18 20:10:40 +00001204 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1205 RHS = EI->getVectorOperand();
1206 VIsUndefShuffle = false;
1207 }
1208 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +00001209 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001210 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1211 ++CurIdx;
1212 continue;
1213 }
1214 }
1215 }
Chris Lattner48431f92011-04-19 22:55:03 +00001216 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1217 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +00001218 VIsUndefShuffle = false;
1219 ++CurIdx;
1220 continue;
1221 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001222
Nate Begeman0533b302009-10-18 20:10:40 +00001223 unsigned InitElts = VVT->getNumElements();
1224
Craig Topperd10e5c22013-07-26 06:16:11 +00001225 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman0533b302009-10-18 20:10:40 +00001226 // input is the same width as the vector being constructed, generate an
1227 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +00001228 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +00001229 if (isa<ExtVectorElementExpr>(IE)) {
1230 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1231 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001232 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001233
Nate Begeman0533b302009-10-18 20:10:40 +00001234 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +00001235 for (unsigned j = 0; j != CurIdx; ++j) {
1236 // If the current vector initializer is a shuffle with undef, merge
1237 // this shuffle directly into it.
1238 if (VIsUndefShuffle) {
1239 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +00001240 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001241 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001242 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001243 }
1244 }
1245 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001246 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001247 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001248
1249 if (VIsUndefShuffle)
1250 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1251
1252 Init = SVOp;
1253 }
1254 }
1255
1256 // Extend init to result vector length, and then shuffle its contribution
1257 // to the vector initializer into V.
1258 if (Args.empty()) {
1259 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001260 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001261 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +00001262 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001263 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +00001264 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +00001265
1266 Args.clear();
1267 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001268 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001269 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001270 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001271 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001272 }
1273
1274 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1275 // merging subsequent shuffles into this one.
1276 if (CurIdx == 0)
1277 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +00001278 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001279 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1280 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1281 CurIdx += InitElts;
1282 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001283
Nate Begeman0533b302009-10-18 20:10:40 +00001284 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1285 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001286 llvm::Type *EltTy = VType->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00001287
Nate Begeman0533b302009-10-18 20:10:40 +00001288 // Emit remaining default initializers
1289 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +00001290 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +00001291 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1292 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1293 }
1294 return V;
1295}
1296
Anders Carlssona3697c92009-11-23 17:57:54 +00001297static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1298 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001299
John McCall2de56d12010-08-25 11:45:40 +00001300 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001301 return false;
Craig Topperd10e5c22013-07-26 06:16:11 +00001302
Anders Carlssona3697c92009-11-23 17:57:54 +00001303 if (isa<CXXThisExpr>(E)) {
1304 // We always assume that 'this' is never null.
1305 return false;
1306 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001307
Anders Carlssona3697c92009-11-23 17:57:54 +00001308 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001309 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001310 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001311 return false;
1312 }
1313
1314 return true;
1315}
1316
Chris Lattner7f02f722007-08-24 05:35:26 +00001317// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1318// have to handle a more broad range of conversions than explicit casts, as they
1319// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001320Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001321 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001322 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001323 CastKind Kind = CE->getCastKind();
Craig Topperd10e5c22013-07-26 06:16:11 +00001324
Mike Stump7f79f9b2009-05-29 15:46:01 +00001325 if (!DestTy->isVoidType())
1326 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001327
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001328 // Since almost all cast kinds apply to scalars, this switch doesn't have
1329 // a default case, so the compiler will warn on a missing case. The cases
1330 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001331 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001332 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001333 case CK_BuiltinFnToFnPtr:
1334 llvm_unreachable("builtin functions are handled elsewhere");
1335
Craig Topperd10e5c22013-07-26 06:16:11 +00001336 case CK_LValueBitCast:
John McCall2de56d12010-08-25 11:45:40 +00001337 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001338 Value *V = EmitLValue(E).getAddress();
Craig Topperd10e5c22013-07-26 06:16:11 +00001339 V = Builder.CreateBitCast(V,
Douglas Gregore39a3892010-07-13 23:17:26 +00001340 ConvertType(CGF.getContext().getPointerType(DestTy)));
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001341 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy),
1342 CE->getExprLoc());
Douglas Gregore39a3892010-07-13 23:17:26 +00001343 }
John McCalldc05b112011-09-10 01:16:55 +00001344
John McCall1d9b3b22011-09-09 05:25:32 +00001345 case CK_CPointerToObjCPointerCast:
1346 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001347 case CK_AnyPointerToBlockPointerCast:
1348 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001349 Value *Src = Visit(const_cast<Expr*>(E));
Stephen Hines651f13c2014-04-23 16:59:28 -07001350 llvm::Type *SrcTy = Src->getType();
1351 llvm::Type *DstTy = ConvertType(DestTy);
1352 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
1353 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
1354 llvm::Type *MidTy = CGF.CGM.getDataLayout().getIntPtrType(SrcTy);
1355 return Builder.CreateIntToPtr(Builder.CreatePtrToInt(Src, MidTy), DstTy);
1356 }
1357 return Builder.CreateBitCast(Src, DstTy);
1358 }
1359 case CK_AddressSpaceConversion: {
1360 Value *Src = Visit(const_cast<Expr*>(E));
1361 return Builder.CreateAddrSpaceCast(Src, ConvertType(DestTy));
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001362 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001363 case CK_AtomicToNonAtomic:
1364 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001365 case CK_NoOp:
1366 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001367 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001368
John McCall2de56d12010-08-25 11:45:40 +00001369 case CK_BaseToDerived: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001370 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1371 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1372
Richard Smithc7648302013-02-13 21:18:23 +00001373 llvm::Value *V = Visit(E);
1374
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001375 llvm::Value *Derived =
1376 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1377 CE->path_begin(), CE->path_end(),
1378 ShouldNullCheckClassCastValue(CE));
1379
Richard Smithc7648302013-02-13 21:18:23 +00001380 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1381 // performed and the object is not of the derived type.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001382 if (CGF.sanitizePerformTypeCheck())
Richard Smithc7648302013-02-13 21:18:23 +00001383 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001384 Derived, DestTy->getPointeeType());
Richard Smithc7648302013-02-13 21:18:23 +00001385
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001386 return Derived;
Anders Carlssona3697c92009-11-23 17:57:54 +00001387 }
John McCall2de56d12010-08-25 11:45:40 +00001388 case CK_UncheckedDerivedToBase:
1389 case CK_DerivedToBase: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001390 const CXXRecordDecl *DerivedClassDecl =
1391 E->getType()->getPointeeCXXRecordDecl();
1392 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson191dfe92009-09-12 04:57:16 +00001393
Stephen Hines176edba2014-12-01 14:53:08 -08001394 return CGF.GetAddressOfBaseClass(
1395 Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(),
1396 ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
Anders Carlsson191dfe92009-09-12 04:57:16 +00001397 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001398 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001399 Value *V = Visit(const_cast<Expr*>(E));
1400 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1401 return CGF.EmitDynamicCast(V, DCE);
1402 }
Eli Friedmand8889622009-11-27 04:41:50 +00001403
John McCall2de56d12010-08-25 11:45:40 +00001404 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001405 assert(E->getType()->isArrayType() &&
1406 "Array to pointer decay must have array source type!");
1407
1408 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1409
1410 // Note that VLA pointers are always decayed, so we don't need to do
1411 // anything here.
1412 if (!E->getType()->isVariableArrayType()) {
1413 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1414 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1415 ->getElementType()) &&
1416 "Expected pointer to array");
1417 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1418 }
1419
Chris Lattner410b12e2011-07-20 04:31:01 +00001420 // Make sure the array decay ends up being the right type. This matters if
1421 // the array type was of an incomplete type.
Stephen Hines651f13c2014-04-23 16:59:28 -07001422 return CGF.Builder.CreatePointerCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001423 }
John McCall2de56d12010-08-25 11:45:40 +00001424 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001425 return EmitLValue(E).getAddress();
1426
John McCall404cd162010-11-13 01:35:44 +00001427 case CK_NullToPointer:
1428 if (MustVisitNullValue(E))
1429 (void) Visit(E);
1430
1431 return llvm::ConstantPointerNull::get(
1432 cast<llvm::PointerType>(ConvertType(DestTy)));
1433
John McCall2de56d12010-08-25 11:45:40 +00001434 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001435 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001436 (void) Visit(E);
1437
John McCall0bab0cd2010-08-23 01:21:21 +00001438 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1439 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1440 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001441
John McCall4d4e5c12012-02-15 01:22:51 +00001442 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001443 case CK_BaseToDerivedMemberPointer:
1444 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001445 Value *Src = Visit(E);
Craig Topperd10e5c22013-07-26 06:16:11 +00001446
John McCalld608cdb2010-08-22 10:59:02 +00001447 // Note that the AST doesn't distinguish between checked and
1448 // unchecked member pointer conversions, so we always have to
1449 // implement checked conversions here. This is inefficient when
1450 // actual control flow may be required in order to perform the
1451 // check, which it is for data member pointers (but not member
1452 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001453 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001454 }
John McCallf85e1932011-06-15 23:02:42 +00001455
John McCall33e56f32011-09-10 06:18:15 +00001456 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001457 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001458 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001459 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001460 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001461 llvm::Value *value = Visit(E);
1462 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1463 return CGF.EmitObjCConsumeObject(E->getType(), value);
1464 }
John McCall348f16f2011-10-04 06:23:45 +00001465 case CK_ARCExtendBlockObject:
1466 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001467
Douglas Gregorac1303e2012-02-22 05:02:47 +00001468 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001469 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001470
John McCall2bb5d002010-11-13 09:02:35 +00001471 case CK_FloatingRealToComplex:
1472 case CK_FloatingComplexCast:
1473 case CK_IntegralRealToComplex:
1474 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001475 case CK_IntegralComplexToFloatingComplex:
1476 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001477 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001478 case CK_ToUnion:
1479 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001480
John McCall0ae287a2010-12-01 04:43:34 +00001481 case CK_LValueToRValue:
1482 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001483 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001484 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001485
John McCall2de56d12010-08-25 11:45:40 +00001486 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001487 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001488
Anders Carlsson82debc72009-10-18 18:12:03 +00001489 // First, convert to the correct width so that we control the kind of
1490 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001491 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001492 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001493 llvm::Value* IntResult =
1494 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001495
Anders Carlsson82debc72009-10-18 18:12:03 +00001496 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001497 }
Eli Friedman65949422011-06-25 02:58:47 +00001498 case CK_PointerToIntegral:
1499 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1500 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001501
John McCall2de56d12010-08-25 11:45:40 +00001502 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001503 CGF.EmitIgnoredExpr(E);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001504 return nullptr;
Eli Friedmanad35a832009-11-16 21:33:53 +00001505 }
John McCall2de56d12010-08-25 11:45:40 +00001506 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001507 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001508 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001509 Elt = EmitScalarConversion(Elt, E->getType(),
1510 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001511
Eli Friedmanad35a832009-11-16 21:33:53 +00001512 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001513 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001514 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanad35a832009-11-16 21:33:53 +00001515 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001516
John McCall2de56d12010-08-25 11:45:40 +00001517 case CK_IntegralCast:
1518 case CK_IntegralToFloating:
1519 case CK_FloatingToIntegral:
1520 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001521 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001522 case CK_IntegralToBoolean:
1523 return EmitIntToBoolConversion(Visit(E));
1524 case CK_PointerToBoolean:
1525 return EmitPointerToBoolConversion(Visit(E));
1526 case CK_FloatingToBoolean:
1527 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001528 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001529 llvm::Value *MemPtr = Visit(E);
1530 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1531 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001532 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001533
1534 case CK_FloatingComplexToReal:
1535 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001536 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001537
1538 case CK_FloatingComplexToBoolean:
1539 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001540 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001541
1542 // TODO: kill this function off, inline appropriate case here
1543 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1544 }
1545
Guy Benyeie6b9d802013-01-20 12:31:11 +00001546 case CK_ZeroToOCLEvent: {
Stephen Hines651f13c2014-04-23 16:59:28 -07001547 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
Guy Benyeie6b9d802013-01-20 12:31:11 +00001548 return llvm::Constant::getNullValue(ConvertType(DestTy));
1549 }
1550
John McCall0bab0cd2010-08-23 01:21:21 +00001551 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001552
John McCall61ad0e62010-11-16 06:21:14 +00001553 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001554}
1555
Chris Lattner33793202007-08-31 22:09:40 +00001556Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001557 CodeGenFunction::StmtExprEvaluation eval(CGF);
Eli Friedman2ac2fa72013-06-10 22:04:49 +00001558 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1559 !E->getType()->isVoidType());
1560 if (!RetAlloca)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001561 return nullptr;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001562 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1563 E->getExprLoc());
Chris Lattner33793202007-08-31 22:09:40 +00001564}
1565
Chris Lattner7f02f722007-08-24 05:35:26 +00001566//===----------------------------------------------------------------------===//
1567// Unary Operators
1568//===----------------------------------------------------------------------===//
1569
Chris Lattner8c11a652010-06-26 22:09:34 +00001570llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001571EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1572 llvm::Value *InVal,
1573 llvm::Value *NextVal, bool IsInc) {
Richard Smith7edf9e32012-11-01 22:30:59 +00001574 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001575 case LangOptions::SOB_Defined:
1576 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001577 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08001578 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +00001579 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1580 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001581 case LangOptions::SOB_Trapping:
1582 BinOpInfo BinOp;
1583 BinOp.LHS = InVal;
1584 BinOp.RHS = NextVal;
1585 BinOp.Ty = E->getType();
1586 BinOp.Opcode = BO_Add;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001587 BinOp.FPContractable = false;
Anton Yartsev683564a2011-02-07 02:17:30 +00001588 BinOp.E = E;
1589 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001590 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001591 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001592}
1593
John McCall5936e332011-02-15 09:22:45 +00001594llvm::Value *
1595ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1596 bool isInc, bool isPre) {
Craig Topperd10e5c22013-07-26 06:16:11 +00001597
John McCall5936e332011-02-15 09:22:45 +00001598 QualType type = E->getSubExpr()->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001599 llvm::PHINode *atomicPHI = nullptr;
David Chisnall72c1dba2013-03-03 16:02:42 +00001600 llvm::Value *value;
1601 llvm::Value *input;
Anton Yartsev683564a2011-02-07 02:17:30 +00001602
John McCall5936e332011-02-15 09:22:45 +00001603 int amount = (isInc ? 1 : -1);
1604
David Chisnall7a7ee302012-01-16 17:27:18 +00001605 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnall72c1dba2013-03-03 16:02:42 +00001606 type = atomicTy->getValueType();
1607 if (isInc && type->isBooleanType()) {
1608 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1609 if (isPre) {
1610 Builder.Insert(new llvm::StoreInst(True,
1611 LV.getAddress(), LV.isVolatileQualified(),
1612 LV.getAlignment().getQuantity(),
1613 llvm::SequentiallyConsistent));
1614 return Builder.getTrue();
1615 }
1616 // For atomic bool increment, we just store true and return it for
1617 // preincrement, do an atomic swap with true for postincrement
1618 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1619 LV.getAddress(), True, llvm::SequentiallyConsistent);
1620 }
1621 // Special case for atomic increment / decrement on integers, emit
1622 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Topperd10e5c22013-07-26 06:16:11 +00001623 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnall72c1dba2013-03-03 16:02:42 +00001624 if (!type->isBooleanType() && type->isIntegerType() &&
1625 !(type->isUnsignedIntegerType() &&
Stephen Hines176edba2014-12-01 14:53:08 -08001626 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnall72c1dba2013-03-03 16:02:42 +00001627 CGF.getLangOpts().getSignedOverflowBehavior() !=
Stephen Hines176edba2014-12-01 14:53:08 -08001628 LangOptions::SOB_Trapping) {
David Chisnall72c1dba2013-03-03 16:02:42 +00001629 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1630 llvm::AtomicRMWInst::Sub;
1631 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1632 llvm::Instruction::Sub;
1633 llvm::Value *amt = CGF.EmitToMemory(
1634 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1635 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1636 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1637 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1638 }
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001639 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnall72c1dba2013-03-03 16:02:42 +00001640 input = value;
1641 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnall7a7ee302012-01-16 17:27:18 +00001642 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1643 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnall72c1dba2013-03-03 16:02:42 +00001644 value = CGF.EmitToMemory(value, type);
David Chisnall7a7ee302012-01-16 17:27:18 +00001645 Builder.CreateBr(opBB);
1646 Builder.SetInsertPoint(opBB);
1647 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1648 atomicPHI->addIncoming(value, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001649 value = atomicPHI;
David Chisnall72c1dba2013-03-03 16:02:42 +00001650 } else {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001651 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnall72c1dba2013-03-03 16:02:42 +00001652 input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001653 }
1654
John McCall5936e332011-02-15 09:22:45 +00001655 // Special case of integer increment that we have to check first: bool++.
1656 // Due to promotion rules, we get:
1657 // bool++ -> bool = bool + 1
1658 // -> bool = (int)bool + 1
1659 // -> bool = ((int)bool + 1 != 0)
1660 // An interesting aspect of this is that increment is always true.
1661 // Decrement does not have this property.
1662 if (isInc && type->isBooleanType()) {
1663 value = Builder.getTrue();
1664
1665 // Most common case by far: integer increment.
1666 } else if (type->isIntegerType()) {
1667
Michael Liao36d5cea2012-08-28 16:55:13 +00001668 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001669
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001670 // Note that signed integer inc/dec with width less than int can't
1671 // overflow because of promotion rules; we're just eliding a few steps here.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001672 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1673 CGF.IntTy->getIntegerBitWidth();
1674 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
John McCall5936e332011-02-15 09:22:45 +00001675 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001676 } else if (CanOverflow && type->isUnsignedIntegerType() &&
Stephen Hines176edba2014-12-01 14:53:08 -08001677 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
Will Dietzb8540362012-11-27 15:01:55 +00001678 BinOpInfo BinOp;
1679 BinOp.LHS = value;
1680 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1681 BinOp.Ty = E->getType();
1682 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1683 BinOp.FPContractable = false;
1684 BinOp.E = E;
1685 value = EmitOverflowCheckedBinOp(BinOp);
1686 } else
John McCall5936e332011-02-15 09:22:45 +00001687 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Craig Topperd10e5c22013-07-26 06:16:11 +00001688
John McCall5936e332011-02-15 09:22:45 +00001689 // Next most common: pointer increment.
1690 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1691 QualType type = ptr->getPointeeType();
1692
1693 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001694 if (const VariableArrayType *vla
1695 = CGF.getContext().getAsVariableArrayType(type)) {
1696 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001697 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith7edf9e32012-11-01 22:30:59 +00001698 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001699 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001700 else
John McCallbc8d40d2011-06-24 21:55:10 +00001701 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
Craig Topperd10e5c22013-07-26 06:16:11 +00001702
John McCall5936e332011-02-15 09:22:45 +00001703 // Arithmetic on function pointers (!) is just +-1.
1704 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001705 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001706
1707 value = CGF.EmitCastToVoidPtr(value);
Richard Smith7edf9e32012-11-01 22:30:59 +00001708 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001709 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1710 else
1711 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001712 value = Builder.CreateBitCast(value, input->getType());
1713
1714 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001715 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001716 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith7edf9e32012-11-01 22:30:59 +00001717 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001718 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1719 else
1720 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001721 }
1722
1723 // Vector increment/decrement.
1724 } else if (type->isVectorType()) {
1725 if (type->hasIntegerRepresentation()) {
1726 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1727
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001728 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001729 } else {
1730 value = Builder.CreateFAdd(
1731 value,
1732 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001733 isInc ? "inc" : "dec");
1734 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001735
John McCall5936e332011-02-15 09:22:45 +00001736 // Floating point.
1737 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001738 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001739 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001740
Stephen Hines176edba2014-12-01 14:53:08 -08001741 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1742 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001743 // Another special case: half FP increment should be done via float
Stephen Hines176edba2014-12-01 14:53:08 -08001744 value = Builder.CreateCall(
1745 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1746 CGF.CGM.FloatTy),
1747 input);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001748 }
1749
John McCall5936e332011-02-15 09:22:45 +00001750 if (value->getType()->isFloatTy())
1751 amt = llvm::ConstantFP::get(VMContext,
1752 llvm::APFloat(static_cast<float>(amount)));
1753 else if (value->getType()->isDoubleTy())
1754 amt = llvm::ConstantFP::get(VMContext,
1755 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001756 else {
John McCall5936e332011-02-15 09:22:45 +00001757 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001758 bool ignored;
John McCall64aa4b32013-04-16 22:48:15 +00001759 F.convert(CGF.getTarget().getLongDoubleFormat(),
1760 llvm::APFloat::rmTowardZero, &ignored);
John McCall5936e332011-02-15 09:22:45 +00001761 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001762 }
John McCall5936e332011-02-15 09:22:45 +00001763 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1764
Stephen Hines176edba2014-12-01 14:53:08 -08001765 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1766 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
1767 value = Builder.CreateCall(
1768 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1769 CGF.CGM.FloatTy),
1770 value);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001771
John McCall5936e332011-02-15 09:22:45 +00001772 // Objective-C pointer types.
1773 } else {
1774 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1775 value = CGF.EmitCastToVoidPtr(value);
1776
1777 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1778 if (!isInc) size = -size;
1779 llvm::Value *sizeValue =
1780 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1781
Richard Smith7edf9e32012-11-01 22:30:59 +00001782 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001783 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1784 else
1785 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001786 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001787 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001788
David Chisnall7a7ee302012-01-16 17:27:18 +00001789 if (atomicPHI) {
1790 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1791 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001792 llvm::Value *pair = Builder.CreateAtomicCmpXchg(
Stephen Hines651f13c2014-04-23 16:59:28 -07001793 LV.getAddress(), atomicPHI, CGF.EmitToMemory(value, type),
1794 llvm::SequentiallyConsistent, llvm::SequentiallyConsistent);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001795 llvm::Value *old = Builder.CreateExtractValue(pair, 0);
1796 llvm::Value *success = Builder.CreateExtractValue(pair, 1);
David Chisnall7a7ee302012-01-16 17:27:18 +00001797 atomicPHI->addIncoming(old, opBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001798 Builder.CreateCondBr(success, contBB, opBB);
1799 Builder.SetInsertPoint(contBB);
1800 return isPre ? value : input;
1801 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001802
Chris Lattner8c11a652010-06-26 22:09:34 +00001803 // Store the updated result through the lvalue.
1804 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001805 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001806 else
John McCall545d9962011-06-25 02:11:03 +00001807 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001808
Chris Lattner8c11a652010-06-26 22:09:34 +00001809 // If this is a postinc, return the value read from memory, otherwise use the
1810 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001811 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001812}
1813
1814
1815
Chris Lattner7f02f722007-08-24 05:35:26 +00001816Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001817 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001818 // Emit unary minus with EmitSub so we handle overflow cases etc.
1819 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001820 BinOp.RHS = Visit(E->getSubExpr());
Craig Topperd10e5c22013-07-26 06:16:11 +00001821
Chris Lattner4ac0d832010-06-28 17:12:37 +00001822 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1823 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001824 else
Chris Lattner4ac0d832010-06-28 17:12:37 +00001825 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001826 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001827 BinOp.Opcode = BO_Sub;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001828 BinOp.FPContractable = false;
Chris Lattner9a207232010-06-26 21:48:21 +00001829 BinOp.E = E;
1830 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001831}
1832
1833Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001834 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001835 Value *Op = Visit(E->getSubExpr());
1836 return Builder.CreateNot(Op, "neg");
1837}
1838
1839Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001840 // Perform vector logical not on comparison with zero vector.
1841 if (E->getType()->isExtVectorType()) {
1842 Value *Oper = Visit(E->getSubExpr());
1843 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00001844 Value *Result;
1845 if (Oper->getType()->isFPOrFPVectorTy())
1846 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1847 else
1848 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner4f692c22012-01-16 21:02:28 +00001849 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1850 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001851
Chris Lattner7f02f722007-08-24 05:35:26 +00001852 // Compare operand to zero.
1853 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001854
Chris Lattner7f02f722007-08-24 05:35:26 +00001855 // Invert value.
1856 // TODO: Could dynamically modify easy computations here. For example, if
1857 // the operand is an icmp ne, turn into icmp eq.
1858 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001859
Anders Carlsson9f84d882009-05-19 18:44:53 +00001860 // ZExt result to the expr type.
1861 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001862}
1863
Eli Friedman0027d2b2010-08-05 09:58:49 +00001864Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1865 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001866 llvm::APSInt Value;
1867 if (E->EvaluateAsInt(Value, CGF.getContext()))
1868 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001869
1870 // Loop over the components of the offsetof to compute the value.
1871 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001872 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001873 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1874 QualType CurrentType = E->getTypeSourceInfo()->getType();
1875 for (unsigned i = 0; i != n; ++i) {
1876 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001877 llvm::Value *Offset = nullptr;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001878 switch (ON.getKind()) {
1879 case OffsetOfExpr::OffsetOfNode::Array: {
1880 // Compute the index
1881 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1882 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001883 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001884 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1885
1886 // Save the element type
1887 CurrentType =
1888 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1889
1890 // Compute the element size
1891 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1892 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1893
1894 // Multiply out to compute the result
1895 Offset = Builder.CreateMul(Idx, ElemSize);
1896 break;
1897 }
1898
1899 case OffsetOfExpr::OffsetOfNode::Field: {
1900 FieldDecl *MemberDecl = ON.getField();
1901 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1902 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1903
1904 // Compute the index of the field in its parent.
1905 unsigned i = 0;
1906 // FIXME: It would be nice if we didn't have to loop here!
1907 for (RecordDecl::field_iterator Field = RD->field_begin(),
1908 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001909 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001910 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001911 break;
1912 }
1913 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1914
1915 // Compute the offset to the field
1916 int64_t OffsetInt = RL.getFieldOffset(i) /
1917 CGF.getContext().getCharWidth();
1918 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1919
1920 // Save the element type.
1921 CurrentType = MemberDecl->getType();
1922 break;
1923 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001924
Eli Friedman0027d2b2010-08-05 09:58:49 +00001925 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001926 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001927
Eli Friedman0027d2b2010-08-05 09:58:49 +00001928 case OffsetOfExpr::OffsetOfNode::Base: {
1929 if (ON.getBase()->isVirtual()) {
1930 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1931 continue;
1932 }
1933
1934 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1935 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1936
1937 // Save the element type.
1938 CurrentType = ON.getBase()->getType();
Craig Topperd10e5c22013-07-26 06:16:11 +00001939
Eli Friedman0027d2b2010-08-05 09:58:49 +00001940 // Compute the offset to the base.
1941 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1942 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001943 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1944 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001945 break;
1946 }
1947 }
1948 Result = Builder.CreateAdd(Result, Offset);
1949 }
1950 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001951}
1952
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001953/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001954/// argument of the sizeof expression as an integer.
1955Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001956ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1957 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001958 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001959 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001960 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001961 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1962 if (E->isArgumentType()) {
1963 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001964 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001965 } else {
1966 // C99 6.5.3.4p2: If the argument is an expression of type
1967 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001968 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001969 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001970
John McCallbc8d40d2011-06-24 21:55:10 +00001971 QualType eltType;
1972 llvm::Value *numElts;
Stephen Hines651f13c2014-04-23 16:59:28 -07001973 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
John McCallbc8d40d2011-06-24 21:55:10 +00001974
1975 llvm::Value *size = numElts;
1976
1977 // Scale the number of non-VLA elements by the non-VLA element size.
1978 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1979 if (!eltSize.isOne())
1980 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1981
1982 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001983 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001984 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001985
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001986 // If this isn't sizeof(vla), the result must be constant; use the constant
1987 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001988 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001989}
1990
Chris Lattner46f93d02007-08-24 21:20:17 +00001991Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1992 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001993 if (Op->getType()->isAnyComplexType()) {
1994 // If it's an l-value, load through the appropriate subobject l-value.
1995 // Note that we have to ask E because Op might be an l-value that
1996 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001997 if (E->isGLValue())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001998 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
1999 E->getExprLoc()).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00002000
2001 // Otherwise, calculate and project.
2002 return CGF.EmitComplexExpr(Op, false, true).first;
2003 }
2004
Chris Lattner46f93d02007-08-24 21:20:17 +00002005 return Visit(Op);
2006}
John McCallb418d742010-11-16 10:08:07 +00002007
Chris Lattner46f93d02007-08-24 21:20:17 +00002008Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2009 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00002010 if (Op->getType()->isAnyComplexType()) {
2011 // If it's an l-value, load through the appropriate subobject l-value.
2012 // Note that we have to ask E because Op might be an l-value that
2013 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00002014 if (Op->isGLValue())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002015 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2016 E->getExprLoc()).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00002017
2018 // Otherwise, calculate and project.
2019 return CGF.EmitComplexExpr(Op, true, false).second;
2020 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002021
Mike Stump7f79f9b2009-05-29 15:46:01 +00002022 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2023 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00002024 if (Op->isGLValue())
2025 CGF.EmitLValue(Op);
2026 else
2027 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002028 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00002029}
2030
Chris Lattner7f02f722007-08-24 05:35:26 +00002031//===----------------------------------------------------------------------===//
2032// Binary Operators
2033//===----------------------------------------------------------------------===//
2034
2035BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002036 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00002037 BinOpInfo Result;
2038 Result.LHS = Visit(E->getLHS());
2039 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00002040 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00002041 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00002042 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00002043 Result.E = E;
2044 return Result;
2045}
2046
Douglas Gregor6a03e342010-04-23 04:16:32 +00002047LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2048 const CompoundAssignOperator *E,
2049 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002050 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00002051 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00002052 BinOpInfo OpInfo;
Craig Topperd10e5c22013-07-26 06:16:11 +00002053
Eli Friedman0934e182013-06-12 01:40:06 +00002054 if (E->getComputationResultType()->isAnyComplexType())
2055 return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
Craig Topperd10e5c22013-07-26 06:16:11 +00002056
Mike Stumpcc0442f2009-05-22 19:07:20 +00002057 // Emit the RHS first. __block variables need to have the rhs evaluated
2058 // first, plus this should improve codegen a little.
2059 OpInfo.RHS = Visit(E->getRHS());
2060 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00002061 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerddc57332012-10-03 20:58:04 +00002062 OpInfo.FPContractable = false;
Mike Stumpcc0442f2009-05-22 19:07:20 +00002063 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00002064 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00002065 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnall7a7ee302012-01-16 17:27:18 +00002066
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002067 llvm::PHINode *atomicPHI = nullptr;
David Chisnall72c1dba2013-03-03 16:02:42 +00002068 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2069 QualType type = atomicTy->getValueType();
2070 if (!type->isBooleanType() && type->isIntegerType() &&
Stephen Hines176edba2014-12-01 14:53:08 -08002071 !(type->isUnsignedIntegerType() &&
2072 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2073 CGF.getLangOpts().getSignedOverflowBehavior() !=
2074 LangOptions::SOB_Trapping) {
David Chisnall72c1dba2013-03-03 16:02:42 +00002075 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2076 switch (OpInfo.Opcode) {
2077 // We don't have atomicrmw operands for *, %, /, <<, >>
2078 case BO_MulAssign: case BO_DivAssign:
2079 case BO_RemAssign:
2080 case BO_ShlAssign:
2081 case BO_ShrAssign:
2082 break;
2083 case BO_AddAssign:
2084 aop = llvm::AtomicRMWInst::Add;
2085 break;
2086 case BO_SubAssign:
2087 aop = llvm::AtomicRMWInst::Sub;
2088 break;
2089 case BO_AndAssign:
2090 aop = llvm::AtomicRMWInst::And;
2091 break;
2092 case BO_XorAssign:
2093 aop = llvm::AtomicRMWInst::Xor;
2094 break;
2095 case BO_OrAssign:
2096 aop = llvm::AtomicRMWInst::Or;
2097 break;
2098 default:
2099 llvm_unreachable("Invalid compound assignment type");
2100 }
2101 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2102 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2103 E->getRHS()->getType(), LHSTy), LHSTy);
2104 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2105 llvm::SequentiallyConsistent);
2106 return LHSLV;
2107 }
2108 }
David Chisnall7a7ee302012-01-16 17:27:18 +00002109 // FIXME: For floating point types, we should be saving and restoring the
2110 // floating point environment in the loop.
2111 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2112 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002113 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnall72c1dba2013-03-03 16:02:42 +00002114 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnall7a7ee302012-01-16 17:27:18 +00002115 Builder.CreateBr(opBB);
2116 Builder.SetInsertPoint(opBB);
2117 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2118 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00002119 OpInfo.LHS = atomicPHI;
2120 }
David Chisnall72c1dba2013-03-03 16:02:42 +00002121 else
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002122 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman860a3192012-06-16 02:19:17 +00002123
2124 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2125 E->getComputationLHSType());
2126
Chris Lattner1f1ded92007-08-24 21:00:35 +00002127 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002128 Result = (this->*Func)(OpInfo);
Craig Topperd10e5c22013-07-26 06:16:11 +00002129
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00002130 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00002131 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00002132
2133 if (atomicPHI) {
2134 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2135 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002136 llvm::Value *pair = Builder.CreateAtomicCmpXchg(
Stephen Hines651f13c2014-04-23 16:59:28 -07002137 LHSLV.getAddress(), atomicPHI, CGF.EmitToMemory(Result, LHSTy),
2138 llvm::SequentiallyConsistent, llvm::SequentiallyConsistent);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002139 llvm::Value *old = Builder.CreateExtractValue(pair, 0);
2140 llvm::Value *success = Builder.CreateExtractValue(pair, 1);
David Chisnall7a7ee302012-01-16 17:27:18 +00002141 atomicPHI->addIncoming(old, opBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00002142 Builder.CreateCondBr(success, contBB, opBB);
2143 Builder.SetInsertPoint(contBB);
2144 return LHSLV;
2145 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002146
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002147 // Store the result value into the LHS lvalue. Bit-fields are handled
2148 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2149 // 'An assignment expression has the value of the left operand after the
2150 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002151 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002152 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002153 else
John McCall545d9962011-06-25 02:11:03 +00002154 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002155
Douglas Gregor6a03e342010-04-23 04:16:32 +00002156 return LHSLV;
2157}
2158
2159Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2160 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2161 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002162 Value *RHS;
2163 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2164
2165 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002166 if (Ignore)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002167 return nullptr;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002168
John McCallb418d742010-11-16 10:08:07 +00002169 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002170 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002171 return RHS;
2172
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002173 // If the lvalue is non-volatile, return the computed value of the assignment.
2174 if (!LHS.isVolatileQualified())
2175 return RHS;
2176
2177 // Otherwise, reload the value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002178 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner1f1ded92007-08-24 21:00:35 +00002179}
2180
Chris Lattner80230302010-09-11 21:47:09 +00002181void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00002182 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Stephen Hines176edba2014-12-01 14:53:08 -08002183 SmallVector<std::pair<llvm::Value *, SanitizerKind>, 2> Checks;
Chris Lattner80230302010-09-11 21:47:09 +00002184
Stephen Hines176edba2014-12-01 14:53:08 -08002185 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2186 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2187 SanitizerKind::IntegerDivideByZero));
2188 }
Richard Smithc54e25f2012-11-06 02:30:30 +00002189
Stephen Hines176edba2014-12-01 14:53:08 -08002190 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Richard Smithc54e25f2012-11-06 02:30:30 +00002191 Ops.Ty->hasSignedIntegerRepresentation()) {
2192 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2193
Chris Lattner80230302010-09-11 21:47:09 +00002194 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00002195 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00002196 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2197
Richard Smith7ac9ef12012-09-08 02:08:36 +00002198 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2199 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Stephen Hines176edba2014-12-01 14:53:08 -08002200 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2201 Checks.push_back(
2202 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner80230302010-09-11 21:47:09 +00002203 }
Richard Smithc54e25f2012-11-06 02:30:30 +00002204
Stephen Hines176edba2014-12-01 14:53:08 -08002205 if (Checks.size() > 0)
2206 EmitBinOpCheck(Checks, Ops);
Chris Lattner80230302010-09-11 21:47:09 +00002207}
Chris Lattner1f1ded92007-08-24 21:00:35 +00002208
Chris Lattner7f02f722007-08-24 05:35:26 +00002209Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Stephen Hines176edba2014-12-01 14:53:08 -08002210 {
2211 CodeGenFunction::SanitizerScope SanScope(&CGF);
2212 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2213 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2214 Ops.Ty->isIntegerType()) {
2215 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2216 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2217 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2218 Ops.Ty->isRealFloatingType()) {
2219 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2220 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2221 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2222 Ops);
2223 }
Chris Lattner80230302010-09-11 21:47:09 +00002224 }
Will Dietzb8540362012-11-27 15:01:55 +00002225
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002226 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2227 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Richard Smith7edf9e32012-11-01 22:30:59 +00002228 if (CGF.getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002229 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2230 llvm::Type *ValTy = Val->getType();
2231 if (ValTy->isFloatTy() ||
2232 (isa<llvm::VectorType>(ValTy) &&
2233 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00002234 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002235 }
2236 return Val;
2237 }
Douglas Gregorf6094622010-07-23 15:58:24 +00002238 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002239 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2240 else
2241 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2242}
2243
2244Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2245 // Rem in C can't be a floating point type: C99 6.5.5p2.
Stephen Hines176edba2014-12-01 14:53:08 -08002246 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2247 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner80230302010-09-11 21:47:09 +00002248 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2249
Will Dietzb8540362012-11-27 15:01:55 +00002250 if (Ops.Ty->isIntegerType())
Chris Lattner80230302010-09-11 21:47:09 +00002251 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2252 }
2253
Eli Friedman52d68742011-04-10 04:44:11 +00002254 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002255 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2256 else
2257 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2258}
2259
Mike Stump2add4732009-04-01 20:28:16 +00002260Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2261 unsigned IID;
2262 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00002263
Will Dietzb8540362012-11-27 15:01:55 +00002264 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner9a207232010-06-26 21:48:21 +00002265 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00002266 case BO_Add:
2267 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002268 OpID = 1;
Will Dietzb8540362012-11-27 15:01:55 +00002269 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2270 llvm::Intrinsic::uadd_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002271 break;
John McCall2de56d12010-08-25 11:45:40 +00002272 case BO_Sub:
2273 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002274 OpID = 2;
Will Dietzb8540362012-11-27 15:01:55 +00002275 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2276 llvm::Intrinsic::usub_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002277 break;
John McCall2de56d12010-08-25 11:45:40 +00002278 case BO_Mul:
2279 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002280 OpID = 3;
Will Dietzb8540362012-11-27 15:01:55 +00002281 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2282 llvm::Intrinsic::umul_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002283 break;
2284 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002285 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00002286 }
Mike Stump035cf892009-04-02 18:15:54 +00002287 OpID <<= 1;
Will Dietzb8540362012-11-27 15:01:55 +00002288 if (isSigned)
2289 OpID |= 1;
Mike Stump035cf892009-04-02 18:15:54 +00002290
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002291 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00002292
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002293 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00002294
2295 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2296 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2297 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2298
Richard Smith7ac9ef12012-09-08 02:08:36 +00002299 // Handle overflow with llvm.trap if no custom handler has been specified.
2300 const std::string *handlerName =
Richard Smith7edf9e32012-11-01 22:30:59 +00002301 &CGF.getLangOpts().OverflowHandler;
Richard Smith7ac9ef12012-09-08 02:08:36 +00002302 if (handlerName->empty()) {
Richard Smithd6396a62012-11-05 22:21:05 +00002303 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithcc305612012-11-01 22:15:34 +00002304 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Stephen Hines176edba2014-12-01 14:53:08 -08002305 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
2306 CodeGenFunction::SanitizerScope SanScope(&CGF);
2307 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
2308 SanitizerKind Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
2309 : SanitizerKind::UnsignedIntegerOverflow;
2310 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
2311 } else
Chad Rosier78d85b12013-01-29 23:31:22 +00002312 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith7ac9ef12012-09-08 02:08:36 +00002313 return result;
2314 }
2315
Mike Stump2add4732009-04-01 20:28:16 +00002316 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00002317 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00002318 llvm::Function::iterator insertPt = initialBB;
2319 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
Stephen Hines651f13c2014-04-23 16:59:28 -07002320 std::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00002321 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00002322
2323 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2324
David Chisnall7f18e672010-09-17 18:29:54 +00002325 // If an overflow handler is set, then we want to call it and then use its
2326 // result, if it returns.
2327 Builder.SetInsertPoint(overflowBB);
2328
2329 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00002330 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002331 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00002332 llvm::FunctionType *handlerTy =
2333 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2334 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2335
2336 // Sign extend the args to 64-bit, so that we can use the same handler for
2337 // all types of overflow.
2338 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2339 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2340
2341 // Call the handler with the two arguments, the operation, and the size of
2342 // the result.
John McCallbd7370a2013-02-28 19:01:20 +00002343 llvm::Value *handlerArgs[] = {
2344 lhs,
2345 rhs,
2346 Builder.getInt8(OpID),
2347 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2348 };
2349 llvm::Value *handlerResult =
2350 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnall7f18e672010-09-17 18:29:54 +00002351
2352 // Truncate the result back to the desired size.
2353 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2354 Builder.CreateBr(continueBB);
2355
Mike Stump2add4732009-04-01 20:28:16 +00002356 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002357 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00002358 phi->addIncoming(result, initialBB);
2359 phi->addIncoming(handlerResult, overflowBB);
2360
2361 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00002362}
Chris Lattner7f02f722007-08-24 05:35:26 +00002363
John McCall913dab22011-06-25 01:32:37 +00002364/// Emit pointer + index arithmetic.
2365static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2366 const BinOpInfo &op,
2367 bool isSubtraction) {
2368 // Must have binary (not unary) expr here. Unary pointer
2369 // increment/decrement doesn't use this path.
2370 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Topperd10e5c22013-07-26 06:16:11 +00002371
John McCall913dab22011-06-25 01:32:37 +00002372 Value *pointer = op.LHS;
2373 Expr *pointerOperand = expr->getLHS();
2374 Value *index = op.RHS;
2375 Expr *indexOperand = expr->getRHS();
2376
2377 // In a subtraction, the LHS is always the pointer.
2378 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2379 std::swap(pointer, index);
2380 std::swap(pointerOperand, indexOperand);
2381 }
2382
2383 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2384 if (width != CGF.PointerWidthInBits) {
2385 // Zero-extend or sign-extend the pointer value according to
2386 // whether the index is signed or not.
2387 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2388 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2389 "idx.ext");
2390 }
2391
2392 // If this is subtraction, negate the index.
2393 if (isSubtraction)
2394 index = CGF.Builder.CreateNeg(index, "idx.neg");
2395
Stephen Hines176edba2014-12-01 14:53:08 -08002396 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smitha0a628f2013-02-23 02:53:19 +00002397 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2398 /*Accessed*/ false);
2399
John McCall913dab22011-06-25 01:32:37 +00002400 const PointerType *pointerType
2401 = pointerOperand->getType()->getAs<PointerType>();
2402 if (!pointerType) {
2403 QualType objectType = pointerOperand->getType()
2404 ->castAs<ObjCObjectPointerType>()
2405 ->getPointeeType();
2406 llvm::Value *objectSize
2407 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2408
2409 index = CGF.Builder.CreateMul(index, objectSize);
2410
2411 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2412 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2413 return CGF.Builder.CreateBitCast(result, pointer->getType());
2414 }
2415
2416 QualType elementType = pointerType->getPointeeType();
2417 if (const VariableArrayType *vla
2418 = CGF.getContext().getAsVariableArrayType(elementType)) {
2419 // The element count here is the total number of non-VLA elements.
2420 llvm::Value *numElements = CGF.getVLASize(vla).first;
2421
2422 // Effectively, the multiply by the VLA size is part of the GEP.
2423 // GEP indexes are signed, and scaling an index isn't permitted to
2424 // signed-overflow, so we use the same semantics for our explicit
2425 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00002426 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00002427 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2428 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2429 } else {
2430 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2431 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00002432 }
John McCall913dab22011-06-25 01:32:37 +00002433 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002434 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00002435
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002436 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2437 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2438 // future proof.
John McCall913dab22011-06-25 01:32:37 +00002439 if (elementType->isVoidType() || elementType->isFunctionType()) {
2440 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2441 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2442 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002443 }
2444
David Blaikie4e4d0842012-03-11 07:00:24 +00002445 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00002446 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2447
2448 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00002449}
2450
Lang Hamesbe9af122012-10-02 04:45:10 +00002451// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2452// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2453// the add operand respectively. This allows fmuladd to represent a*b-c, or
2454// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2455// efficient operations.
2456static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2457 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2458 bool negMul, bool negAdd) {
2459 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Topperd10e5c22013-07-26 06:16:11 +00002460
Lang Hamesbe9af122012-10-02 04:45:10 +00002461 Value *MulOp0 = MulOp->getOperand(0);
2462 Value *MulOp1 = MulOp->getOperand(1);
2463 if (negMul) {
2464 MulOp0 =
2465 Builder.CreateFSub(
2466 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2467 "neg");
2468 } else if (negAdd) {
2469 Addend =
2470 Builder.CreateFSub(
2471 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2472 "neg");
2473 }
2474
2475 Value *FMulAdd =
2476 Builder.CreateCall3(
2477 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2478 MulOp0, MulOp1, Addend);
2479 MulOp->eraseFromParent();
2480
2481 return FMulAdd;
2482}
2483
2484// Check whether it would be legal to emit an fmuladd intrinsic call to
2485// represent op and if so, build the fmuladd.
2486//
2487// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2488// Does NOT check the type of the operation - it's assumed that this function
2489// will be called from contexts where it's known that the type is contractable.
Craig Topperd10e5c22013-07-26 06:16:11 +00002490static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hamesbe9af122012-10-02 04:45:10 +00002491 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2492 bool isSub=false) {
2493
2494 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2495 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2496 "Only fadd/fsub can be the root of an fmuladd.");
2497
2498 // Check whether this op is marked as fusable.
2499 if (!op.FPContractable)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002500 return nullptr;
Lang Hamesbe9af122012-10-02 04:45:10 +00002501
2502 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2503 // either disabled, or handled entirely by the LLVM backend).
Lang Hames931c0832012-11-15 07:51:26 +00002504 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002505 return nullptr;
Lang Hamesbe9af122012-10-02 04:45:10 +00002506
2507 // We have a potentially fusable op. Look for a mul on one of the operands.
2508 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2509 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002510 assert(LHSBinOp->getNumUses() == 0 &&
2511 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002512 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2513 }
2514 } else if (llvm::BinaryOperator* RHSBinOp =
2515 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2516 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002517 assert(RHSBinOp->getNumUses() == 0 &&
2518 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002519 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2520 }
2521 }
2522
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002523 return nullptr;
Lang Hamesbe9af122012-10-02 04:45:10 +00002524}
2525
John McCall913dab22011-06-25 01:32:37 +00002526Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2527 if (op.LHS->getType()->isPointerTy() ||
2528 op.RHS->getType()->isPointerTy())
2529 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2530
2531 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002532 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002533 case LangOptions::SOB_Defined:
2534 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002535 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08002536 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +00002537 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2538 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002539 case LangOptions::SOB_Trapping:
2540 return EmitOverflowCheckedBinOp(op);
2541 }
2542 }
Will Dietzb8540362012-11-27 15:01:55 +00002543
Stephen Hines176edba2014-12-01 14:53:08 -08002544 if (op.Ty->isUnsignedIntegerType() &&
2545 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietzb8540362012-11-27 15:01:55 +00002546 return EmitOverflowCheckedBinOp(op);
2547
Lang Hamesbe9af122012-10-02 04:45:10 +00002548 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2549 // Try to form an fmuladd.
2550 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2551 return FMulAdd;
2552
John McCall913dab22011-06-25 01:32:37 +00002553 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002554 }
John McCall913dab22011-06-25 01:32:37 +00002555
2556 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2557}
2558
2559Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2560 // The LHS is always a pointer if either side is.
2561 if (!op.LHS->getType()->isPointerTy()) {
2562 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002563 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002564 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002565 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002566 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08002567 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +00002568 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2569 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002570 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002571 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002572 }
2573 }
Will Dietzb8540362012-11-27 15:01:55 +00002574
Stephen Hines176edba2014-12-01 14:53:08 -08002575 if (op.Ty->isUnsignedIntegerType() &&
2576 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietzb8540362012-11-27 15:01:55 +00002577 return EmitOverflowCheckedBinOp(op);
2578
Lang Hamesbe9af122012-10-02 04:45:10 +00002579 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2580 // Try to form an fmuladd.
2581 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2582 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002583 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002584 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002585
John McCall913dab22011-06-25 01:32:37 +00002586 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002587 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002588
John McCall913dab22011-06-25 01:32:37 +00002589 // If the RHS is not a pointer, then we have normal pointer
2590 // arithmetic.
2591 if (!op.RHS->getType()->isPointerTy())
2592 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002593
John McCall913dab22011-06-25 01:32:37 +00002594 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002595
John McCall913dab22011-06-25 01:32:37 +00002596 // Do the raw subtraction part.
2597 llvm::Value *LHS
2598 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2599 llvm::Value *RHS
2600 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2601 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002602
John McCall913dab22011-06-25 01:32:37 +00002603 // Okay, figure out the element size.
2604 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2605 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002606
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002607 llvm::Value *divisor = nullptr;
John McCall913dab22011-06-25 01:32:37 +00002608
2609 // For a variable-length array, this is going to be non-constant.
2610 if (const VariableArrayType *vla
2611 = CGF.getContext().getAsVariableArrayType(elementType)) {
2612 llvm::Value *numElements;
Stephen Hines651f13c2014-04-23 16:59:28 -07002613 std::tie(numElements, elementType) = CGF.getVLASize(vla);
John McCall913dab22011-06-25 01:32:37 +00002614
2615 divisor = numElements;
2616
2617 // Scale the number of non-VLA elements by the non-VLA element size.
2618 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2619 if (!eltSize.isOne())
2620 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2621
2622 // For everything elese, we can just compute it, safe in the
2623 // assumption that Sema won't let anything through that we can't
2624 // safely compute the size of.
2625 } else {
2626 CharUnits elementSize;
2627 // Handle GCC extension for pointer arithmetic on void* and
2628 // function pointer types.
2629 if (elementType->isVoidType() || elementType->isFunctionType())
2630 elementSize = CharUnits::One();
2631 else
2632 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2633
2634 // Don't even emit the divide for element size of 1.
2635 if (elementSize.isOne())
2636 return diffInChars;
2637
2638 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002639 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002640
Chris Lattner2cb42222011-03-01 00:03:48 +00002641 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2642 // pointer difference in C is only defined in the case where both operands
2643 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002644 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002645}
2646
David Tweed7a834212013-01-07 16:43:27 +00002647Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweedf20318f2013-01-10 09:11:33 +00002648 llvm::IntegerType *Ty;
2649 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2650 Ty = cast<llvm::IntegerType>(VT->getElementType());
2651 else
2652 Ty = cast<llvm::IntegerType>(LHS->getType());
2653 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed7a834212013-01-07 16:43:27 +00002654}
2655
Chris Lattner7f02f722007-08-24 05:35:26 +00002656Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2657 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2658 // RHS to the same size as the LHS.
2659 Value *RHS = Ops.RHS;
2660 if (Ops.LHS->getType() != RHS->getType())
2661 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002662
Stephen Hines176edba2014-12-01 14:53:08 -08002663 if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
Will Dietz4f45bc02013-01-18 11:30:38 +00002664 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Stephen Hines176edba2014-12-01 14:53:08 -08002665 CodeGenFunction::SanitizerScope SanScope(&CGF);
David Tweed7a834212013-01-07 16:43:27 +00002666 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
Will Dietzbb60fc62013-02-25 22:37:49 +00002667 llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
Richard Smith9d3e2262012-08-25 00:32:28 +00002668
2669 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Will Dietzbb60fc62013-02-25 22:37:49 +00002670 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2671 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2672 llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2673 Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2674
Richard Smith9d3e2262012-08-25 00:32:28 +00002675 // Check whether we are shifting any non-zero bits off the top of the
2676 // integer.
Will Dietzbb60fc62013-02-25 22:37:49 +00002677 CGF.EmitBlock(CheckBitsShifted);
Richard Smith9d3e2262012-08-25 00:32:28 +00002678 llvm::Value *BitsShiftedOff =
2679 Builder.CreateLShr(Ops.LHS,
2680 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2681 /*NUW*/true, /*NSW*/true),
2682 "shl.check");
2683 if (CGF.getLangOpts().CPlusPlus) {
2684 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2685 // Under C++11's rules, shifting a 1 bit into the sign bit is
2686 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2687 // define signed left shifts, so we use the C99 and C++11 rules there).
2688 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2689 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2690 }
2691 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Will Dietzbb60fc62013-02-25 22:37:49 +00002692 llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2693 CGF.EmitBlock(Cont);
2694 llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2695 P->addIncoming(Valid, Orig);
2696 P->addIncoming(SecondCheck, CheckBitsShifted);
2697 Valid = P;
Richard Smith9d3e2262012-08-25 00:32:28 +00002698 }
Will Dietzbb60fc62013-02-25 22:37:49 +00002699
Stephen Hines176edba2014-12-01 14:53:08 -08002700 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
Mike Stumpbe07f602009-12-14 21:58:14 +00002701 }
David Tweed7a834212013-01-07 16:43:27 +00002702 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2703 if (CGF.getLangOpts().OpenCL)
2704 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002705
Chris Lattner7f02f722007-08-24 05:35:26 +00002706 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2707}
2708
2709Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2710 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2711 // RHS to the same size as the LHS.
2712 Value *RHS = Ops.RHS;
2713 if (Ops.LHS->getType() != RHS->getType())
2714 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002715
Stephen Hines176edba2014-12-01 14:53:08 -08002716 if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
2717 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2718 CodeGenFunction::SanitizerScope SanScope(&CGF);
2719 llvm::Value *Valid =
2720 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
2721 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2722 }
David Tweed7a834212013-01-07 16:43:27 +00002723
2724 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2725 if (CGF.getLangOpts().OpenCL)
2726 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002727
Douglas Gregorf6094622010-07-23 15:58:24 +00002728 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002729 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2730 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2731}
2732
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002733enum IntrinsicType { VCMPEQ, VCMPGT };
2734// return corresponding comparison intrinsic for given vector type
2735static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2736 BuiltinType::Kind ElemKind) {
2737 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002738 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002739 case BuiltinType::Char_U:
2740 case BuiltinType::UChar:
2741 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2742 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002743 case BuiltinType::Char_S:
2744 case BuiltinType::SChar:
2745 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2746 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002747 case BuiltinType::UShort:
2748 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2749 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002750 case BuiltinType::Short:
2751 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2752 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002753 case BuiltinType::UInt:
2754 case BuiltinType::ULong:
2755 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2756 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002757 case BuiltinType::Int:
2758 case BuiltinType::Long:
2759 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2760 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002761 case BuiltinType::Float:
2762 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2763 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002764 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002765}
2766
Chris Lattner7f02f722007-08-24 05:35:26 +00002767Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2768 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002769 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002770 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002771 QualType LHSTy = E->getLHS()->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08002772 QualType RHSTy = E->getRHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002773 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002774 assert(E->getOpcode() == BO_EQ ||
2775 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002776 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2777 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002778 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002779 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Stephen Hines176edba2014-12-01 14:53:08 -08002780 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002781 Value *LHS = Visit(E->getLHS());
2782 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002783
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002784 // If AltiVec, the comparison results in a numeric type, so we use
2785 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002786 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002787 // constants for mapping CR6 register bits to predicate result
2788 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2789
2790 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2791
2792 // in several cases vector arguments order will be reversed
2793 Value *FirstVecArg = LHS,
2794 *SecondVecArg = RHS;
2795
2796 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002797 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002798 BuiltinType::Kind ElementKind = BTy->getKind();
2799
2800 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002801 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002802 case BO_EQ:
2803 CR6 = CR6_LT;
2804 ID = GetIntrinsic(VCMPEQ, ElementKind);
2805 break;
2806 case BO_NE:
2807 CR6 = CR6_EQ;
2808 ID = GetIntrinsic(VCMPEQ, ElementKind);
2809 break;
2810 case BO_LT:
2811 CR6 = CR6_LT;
2812 ID = GetIntrinsic(VCMPGT, ElementKind);
2813 std::swap(FirstVecArg, SecondVecArg);
2814 break;
2815 case BO_GT:
2816 CR6 = CR6_LT;
2817 ID = GetIntrinsic(VCMPGT, ElementKind);
2818 break;
2819 case BO_LE:
2820 if (ElementKind == BuiltinType::Float) {
2821 CR6 = CR6_LT;
2822 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2823 std::swap(FirstVecArg, SecondVecArg);
2824 }
2825 else {
2826 CR6 = CR6_EQ;
2827 ID = GetIntrinsic(VCMPGT, ElementKind);
2828 }
2829 break;
2830 case BO_GE:
2831 if (ElementKind == BuiltinType::Float) {
2832 CR6 = CR6_LT;
2833 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2834 }
2835 else {
2836 CR6 = CR6_EQ;
2837 ID = GetIntrinsic(VCMPGT, ElementKind);
2838 std::swap(FirstVecArg, SecondVecArg);
2839 }
2840 break;
2841 }
2842
Chris Lattner48431f92011-04-19 22:55:03 +00002843 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002844 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2845 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2846 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2847 }
2848
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002849 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002850 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002851 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002852 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002853 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002854 LHS, RHS, "cmp");
2855 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002856 // Unsigned integers and pointers.
2857 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002858 LHS, RHS, "cmp");
2859 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002860
2861 // If this is a vector comparison, sign extend the result to the appropriate
2862 // vector integer type and return it (don't convert to bool).
2863 if (LHSTy->isVectorType())
2864 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002865
Chris Lattner7f02f722007-08-24 05:35:26 +00002866 } else {
2867 // Complex Comparison: can only be an equality comparison.
Stephen Hines176edba2014-12-01 14:53:08 -08002868 CodeGenFunction::ComplexPairTy LHS, RHS;
2869 QualType CETy;
2870 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2871 LHS = CGF.EmitComplexExpr(E->getLHS());
2872 CETy = CTy->getElementType();
2873 } else {
2874 LHS.first = Visit(E->getLHS());
2875 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2876 CETy = LHSTy;
2877 }
2878 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
2879 RHS = CGF.EmitComplexExpr(E->getRHS());
2880 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
2881 CTy->getElementType()) &&
2882 "The element types must always match.");
2883 (void)CTy;
2884 } else {
2885 RHS.first = Visit(E->getRHS());
2886 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
2887 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
2888 "The element types must always match.");
2889 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002890
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002891 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002892 if (CETy->isRealFloatingType()) {
2893 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2894 LHS.first, RHS.first, "cmp.r");
2895 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2896 LHS.second, RHS.second, "cmp.i");
2897 } else {
2898 // Complex comparisons can only be equality comparisons. As such, signed
2899 // and unsigned opcodes are the same.
2900 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2901 LHS.first, RHS.first, "cmp.r");
2902 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2903 LHS.second, RHS.second, "cmp.i");
2904 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002905
John McCall2de56d12010-08-25 11:45:40 +00002906 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002907 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2908 } else {
John McCall2de56d12010-08-25 11:45:40 +00002909 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002910 "Complex comparison other than == or != ?");
2911 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2912 }
2913 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002914
2915 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002916}
2917
2918Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002919 bool Ignore = TestAndClearIgnoreResultAssign();
2920
John McCallf85e1932011-06-15 23:02:42 +00002921 Value *RHS;
2922 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002923
John McCallf85e1932011-06-15 23:02:42 +00002924 switch (E->getLHS()->getType().getObjCLifetime()) {
2925 case Qualifiers::OCL_Strong:
Stephen Hines651f13c2014-04-23 16:59:28 -07002926 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCallf85e1932011-06-15 23:02:42 +00002927 break;
2928
2929 case Qualifiers::OCL_Autoreleasing:
Stephen Hines651f13c2014-04-23 16:59:28 -07002930 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCallf85e1932011-06-15 23:02:42 +00002931 break;
2932
2933 case Qualifiers::OCL_Weak:
2934 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002935 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002936 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2937 break;
2938
2939 // No reason to do any of these differently.
2940 case Qualifiers::OCL_None:
2941 case Qualifiers::OCL_ExplicitNone:
2942 // __block variables need to have the rhs evaluated first, plus
2943 // this should improve codegen just a little.
2944 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002945 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002946
2947 // Store the value into the LHS. Bit-fields are handled specially
2948 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2949 // 'An assignment expression has the value of the left operand after
2950 // the assignment...'.
2951 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002952 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002953 else
John McCall545d9962011-06-25 02:11:03 +00002954 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002955 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002956
2957 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002958 if (Ignore)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002959 return nullptr;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002960
John McCallb418d742010-11-16 10:08:07 +00002961 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002962 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002963 return RHS;
2964
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002965 // If the lvalue is non-volatile, return the computed value of the assignment.
2966 if (!LHS.isVolatileQualified())
2967 return RHS;
2968
2969 // Otherwise, reload the value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002970 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002971}
2972
2973Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002974 RegionCounter Cnt = CGF.getPGORegionCounter(E);
2975
Tanya Lattner4f692c22012-01-16 21:02:28 +00002976 // Perform vector logical and on comparisons with zero vectors.
2977 if (E->getType()->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002978 Cnt.beginRegion(Builder);
2979
Tanya Lattner4f692c22012-01-16 21:02:28 +00002980 Value *LHS = Visit(E->getLHS());
2981 Value *RHS = Visit(E->getRHS());
2982 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00002983 if (LHS->getType()->isFPOrFPVectorTy()) {
2984 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2985 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2986 } else {
2987 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2988 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2989 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00002990 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly52e933b2013-02-21 11:49:56 +00002991 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner4f692c22012-01-16 21:02:28 +00002992 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002993
Chris Lattner2acc6e32011-07-18 04:24:23 +00002994 llvm::Type *ResTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00002995
Chris Lattner20eb09d2008-11-12 08:26:50 +00002996 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2997 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002998 bool LHSCondVal;
2999 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3000 if (LHSCondVal) { // If we have 1 && X, just emit X.
Stephen Hines651f13c2014-04-23 16:59:28 -07003001 Cnt.beginRegion(Builder);
3002
Chris Lattner0946ccd2008-11-11 07:41:27 +00003003 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00003004 // ZExt result to int or bool.
3005 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00003006 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003007
Chris Lattner7804bcb2009-10-17 04:24:20 +00003008 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00003009 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00003010 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00003011 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003012
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003013 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3014 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00003015
John McCall150b4622011-01-26 04:00:11 +00003016 CodeGenFunction::ConditionalEvaluation eval(CGF);
3017
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003018 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Stephen Hines651f13c2014-04-23 16:59:28 -07003019 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, Cnt.getCount());
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003020
3021 // Any edges into the ContBlock are now from an (indeterminate number of)
3022 // edges from this first condition. All of these values will be false. Start
3023 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003024 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00003025 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003026 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3027 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00003028 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003029
John McCall150b4622011-01-26 04:00:11 +00003030 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00003031 CGF.EmitBlock(RHSBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07003032 Cnt.beginRegion(Builder);
Chris Lattner7f02f722007-08-24 05:35:26 +00003033 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00003034 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003035
Chris Lattner7f02f722007-08-24 05:35:26 +00003036 // Reaquire the RHS block, as there may be subblocks inserted.
3037 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003038
Stephen Hines176edba2014-12-01 14:53:08 -08003039 // Emit an unconditional branch from this block to ContBlock.
3040 {
Devang Patelacd72362011-03-30 00:08:31 +00003041 // There is no need to emit line number for unconditional branch.
Stephen Hines176edba2014-12-01 14:53:08 -08003042 SuppressDebugLocation S(Builder);
3043 CGF.EmitBlock(ContBlock);
3044 }
3045 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00003046 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003047
Chris Lattner7f02f722007-08-24 05:35:26 +00003048 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00003049 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00003050}
3051
3052Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003053 RegionCounter Cnt = CGF.getPGORegionCounter(E);
3054
Tanya Lattner4f692c22012-01-16 21:02:28 +00003055 // Perform vector logical or on comparisons with zero vectors.
3056 if (E->getType()->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003057 Cnt.beginRegion(Builder);
3058
Tanya Lattner4f692c22012-01-16 21:02:28 +00003059 Value *LHS = Visit(E->getLHS());
3060 Value *RHS = Visit(E->getRHS());
3061 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00003062 if (LHS->getType()->isFPOrFPVectorTy()) {
3063 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3064 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3065 } else {
3066 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3067 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3068 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00003069 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly52e933b2013-02-21 11:49:56 +00003070 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner4f692c22012-01-16 21:02:28 +00003071 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003072
Chris Lattner2acc6e32011-07-18 04:24:23 +00003073 llvm::Type *ResTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003074
Chris Lattner20eb09d2008-11-12 08:26:50 +00003075 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3076 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00003077 bool LHSCondVal;
3078 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3079 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Stephen Hines651f13c2014-04-23 16:59:28 -07003080 Cnt.beginRegion(Builder);
3081
Chris Lattner0946ccd2008-11-11 07:41:27 +00003082 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00003083 // ZExt result to int or bool.
3084 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00003085 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003086
Chris Lattner7804bcb2009-10-17 04:24:20 +00003087 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00003088 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00003089 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00003090 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003091
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003092 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3093 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003094
John McCall150b4622011-01-26 04:00:11 +00003095 CodeGenFunction::ConditionalEvaluation eval(CGF);
3096
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003097 // Branch on the LHS first. If it is true, go to the success (cont) block.
Stephen Hines651f13c2014-04-23 16:59:28 -07003098 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
3099 Cnt.getParentCount() - Cnt.getCount());
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003100
3101 // Any edges into the ContBlock are now from an (indeterminate number of)
3102 // edges from this first condition. All of these values will be true. Start
3103 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003104 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00003105 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003106 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3107 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00003108 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003109
John McCall150b4622011-01-26 04:00:11 +00003110 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00003111
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003112 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00003113 CGF.EmitBlock(RHSBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07003114 Cnt.beginRegion(Builder);
Chris Lattner7f02f722007-08-24 05:35:26 +00003115 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003116
John McCall150b4622011-01-26 04:00:11 +00003117 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003118
Chris Lattner7f02f722007-08-24 05:35:26 +00003119 // Reaquire the RHS block, as there may be subblocks inserted.
3120 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003121
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003122 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3123 // into the phi node for the edge with the value of RHSCond.
3124 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00003125 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003126
Chris Lattner7f02f722007-08-24 05:35:26 +00003127 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00003128 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00003129}
3130
3131Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00003132 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00003133 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00003134 return Visit(E->getRHS());
3135}
3136
3137//===----------------------------------------------------------------------===//
3138// Other Operators
3139//===----------------------------------------------------------------------===//
3140
Chris Lattner9802a512008-11-12 08:55:54 +00003141/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3142/// expression is cheap enough and side-effect-free enough to evaluate
3143/// unconditionally instead of conditionally. This is used to convert control
3144/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00003145static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3146 CodeGenFunction &CGF) {
Chris Lattnerc6bea672011-04-16 23:15:35 +00003147 // Anything that is an integer or floating point constant is fine.
Nick Lewyckyc5699172013-11-08 23:00:12 +00003148 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003149
Nick Lewyckyc5699172013-11-08 23:00:12 +00003150 // Even non-volatile automatic variables can't be evaluated unconditionally.
3151 // Referencing a thread_local may cause non-trivial initialization work to
3152 // occur. If we're inside a lambda and one of the variables is from the scope
3153 // outside the lambda, that function may have returned already. Reading its
3154 // locals is a bad idea. Also, these reads may introduce races there didn't
3155 // exist in the source-level program.
Chris Lattner9802a512008-11-12 08:55:54 +00003156}
3157
3158
Chris Lattner7f02f722007-08-24 05:35:26 +00003159Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00003160VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00003161 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00003162
3163 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00003164 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
Stephen Hines651f13c2014-04-23 16:59:28 -07003165 RegionCounter Cnt = CGF.getPGORegionCounter(E);
John McCall56ca35d2011-02-17 10:25:35 +00003166
3167 Expr *condExpr = E->getCond();
3168 Expr *lhsExpr = E->getTrueExpr();
3169 Expr *rhsExpr = E->getFalseExpr();
3170
Chris Lattner31a09842008-11-12 08:04:58 +00003171 // If the condition constant folds and can be elided, try to avoid emitting
3172 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00003173 bool CondExprBool;
3174 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00003175 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00003176 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003177
Eli Friedmanc8645e32011-10-15 02:10:40 +00003178 // If the dead side doesn't have labels we need, just emit the Live part.
3179 if (!CGF.ContainsLabel(dead)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003180 if (CondExprBool)
3181 Cnt.beginRegion(Builder);
Eli Friedmanc8645e32011-10-15 02:10:40 +00003182 Value *Result = Visit(live);
3183
3184 // If the live part is a throw expression, it acts like it has a void
3185 // type, so evaluating it returns a null Value*. However, a conditional
3186 // with non-void type must return a non-null Value*.
3187 if (!Result && !E->getType()->isVoidType())
3188 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3189
3190 return Result;
3191 }
Chris Lattnerc657e922008-11-11 18:56:45 +00003192 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003193
Nate Begeman6155d732010-09-20 22:41:17 +00003194 // OpenCL: If the condition is a vector, we can treat this condition like
3195 // the select function.
Craig Topperd10e5c22013-07-26 06:16:11 +00003196 if (CGF.getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00003197 && condExpr->getType()->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003198 Cnt.beginRegion(Builder);
3199
John McCall56ca35d2011-02-17 10:25:35 +00003200 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3201 llvm::Value *LHS = Visit(lhsExpr);
3202 llvm::Value *RHS = Visit(rhsExpr);
Craig Topperd10e5c22013-07-26 06:16:11 +00003203
Chris Lattner2acc6e32011-07-18 04:24:23 +00003204 llvm::Type *condType = ConvertType(condExpr->getType());
3205 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Topperd10e5c22013-07-26 06:16:11 +00003206
3207 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00003208 llvm::Type *elemType = vecTy->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003209
Chris Lattner2ce88422012-01-25 05:34:41 +00003210 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00003211 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Topperd10e5c22013-07-26 06:16:11 +00003212 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begeman6155d732010-09-20 22:41:17 +00003213 llvm::VectorType::get(elemType,
Craig Topperd10e5c22013-07-26 06:16:11 +00003214 numElem),
Nate Begeman6155d732010-09-20 22:41:17 +00003215 "sext");
3216 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Topperd10e5c22013-07-26 06:16:11 +00003217
Nate Begeman6155d732010-09-20 22:41:17 +00003218 // Cast float to int to perform ANDs if necessary.
3219 llvm::Value *RHSTmp = RHS;
3220 llvm::Value *LHSTmp = LHS;
3221 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00003222 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00003223 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00003224 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3225 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3226 wasCast = true;
3227 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003228
Nate Begeman6155d732010-09-20 22:41:17 +00003229 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3230 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3231 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3232 if (wasCast)
3233 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3234
3235 return tmp5;
3236 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003237
Chris Lattner9802a512008-11-12 08:55:54 +00003238 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3239 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00003240 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00003241 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3242 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003243 Cnt.beginRegion(Builder);
3244
John McCall56ca35d2011-02-17 10:25:35 +00003245 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3246 llvm::Value *LHS = Visit(lhsExpr);
3247 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00003248 if (!LHS) {
3249 // If the conditional has void type, make sure we return a null Value*.
3250 assert(!RHS && "LHS and RHS types must match");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003251 return nullptr;
Eli Friedman1e4f68c2011-12-08 22:01:56 +00003252 }
Chris Lattner9802a512008-11-12 08:55:54 +00003253 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3254 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003255
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00003256 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3257 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003258 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00003259
3260 CodeGenFunction::ConditionalEvaluation eval(CGF);
Stephen Hines651f13c2014-04-23 16:59:28 -07003261 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, Cnt.getCount());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00003262
Chris Lattner7f02f722007-08-24 05:35:26 +00003263 CGF.EmitBlock(LHSBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07003264 Cnt.beginRegion(Builder);
John McCall150b4622011-01-26 04:00:11 +00003265 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003266 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00003267 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003268
Chris Lattner7f02f722007-08-24 05:35:26 +00003269 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00003270 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003271
Chris Lattner7f02f722007-08-24 05:35:26 +00003272 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00003273 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003274 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00003275 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003276
John McCall150b4622011-01-26 04:00:11 +00003277 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00003278 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003279
Eli Friedman48daf592009-12-07 20:25:53 +00003280 // If the LHS or RHS is a throw expression, it will be legitimately null.
3281 if (!LHS)
3282 return RHS;
3283 if (!RHS)
3284 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003285
Chris Lattner7f02f722007-08-24 05:35:26 +00003286 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003287 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00003288 PN->addIncoming(LHS, LHSBlock);
3289 PN->addIncoming(RHS, RHSBlock);
3290 return PN;
3291}
3292
3293Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmana5e66012013-07-20 00:40:58 +00003294 return Visit(E->getChosenSubExpr());
Chris Lattner7f02f722007-08-24 05:35:26 +00003295}
3296
Chris Lattner2202bce2007-11-30 17:56:23 +00003297Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003298 QualType Ty = VE->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08003299
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003300 if (Ty->isVariablyModifiedType())
3301 CGF.EmitVariablyModifiedType(Ty);
3302
Eli Friedman4fd0aa52009-01-20 17:46:04 +00003303 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003304 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
Stephen Hines176edba2014-12-01 14:53:08 -08003305 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003306
3307 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003308 if (!ArgPtr)
Stephen Hines176edba2014-12-01 14:53:08 -08003309 return Builder.CreateVAArg(ArgValue, ArgTy);
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003310
Mike Stump7f79f9b2009-05-29 15:46:01 +00003311 // FIXME Volatility.
Stephen Hines176edba2014-12-01 14:53:08 -08003312 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3313
3314 // If EmitVAArg promoted the type, we must truncate it.
3315 if (ArgTy != Val->getType())
3316 Val = Builder.CreateTrunc(Val, ArgTy);
3317
3318 return Val;
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003319}
3320
John McCall6b5a61b2011-02-07 10:33:21 +00003321Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3322 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00003323}
3324
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003325Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3326 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00003327 llvm::Type *DstTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003328
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003329 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3330 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003331 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003332 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3333 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3334 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
Craig Topperd10e5c22013-07-26 06:16:11 +00003335 if ((numElementsDst == 3 && numElementsSrc == 4)
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003336 || (numElementsDst == 4 && numElementsSrc == 3)) {
Craig Topperd10e5c22013-07-26 06:16:11 +00003337
3338
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003339 // In the case of going from int4->float3, a bitcast is needed before
3340 // doing a shuffle.
Craig Topperd10e5c22013-07-26 06:16:11 +00003341 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003342 cast<llvm::VectorType>(SrcTy)->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003343 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003344 cast<llvm::VectorType>(DstTy)->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003345
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003346 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3347 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3348 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003349 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003350 numElementsSrc);
Craig Topperd10e5c22013-07-26 06:16:11 +00003351
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003352 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3353 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003354
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003355 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003356
Chris Lattner5f9e2722011-07-23 10:55:15 +00003357 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003358 Args.push_back(Builder.getInt32(0));
3359 Args.push_back(Builder.getInt32(1));
3360 Args.push_back(Builder.getInt32(2));
Craig Topperd10e5c22013-07-26 06:16:11 +00003361
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003362 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00003363 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Craig Topperd10e5c22013-07-26 06:16:11 +00003364
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003365 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Craig Topperd10e5c22013-07-26 06:16:11 +00003366
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003367 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3368 }
3369 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003370
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003371 return Builder.CreateBitCast(Src, DstTy, "astype");
3372}
3373
Eli Friedman276b0612011-10-11 02:20:01 +00003374Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3375 return CGF.EmitAtomicExpr(E).getScalarVal();
3376}
3377
Chris Lattner7f02f722007-08-24 05:35:26 +00003378//===----------------------------------------------------------------------===//
3379// Entry Point into this File
3380//===----------------------------------------------------------------------===//
3381
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003382/// EmitScalarExpr - Emit the computation of the specified expression of scalar
3383/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00003384Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall9d232c82013-03-07 21:37:08 +00003385 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner7f02f722007-08-24 05:35:26 +00003386 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003387
Devang Patel5de7a0e2011-03-07 18:29:53 +00003388 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003389 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003390 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00003391 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00003392 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003393 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003394 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00003395}
Chris Lattner3707b252007-08-26 06:48:56 +00003396
3397/// EmitScalarConversion - Emit a conversion from the specified type to the
3398/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003399Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3400 QualType DstTy) {
John McCall9d232c82013-03-07 21:37:08 +00003401 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3707b252007-08-26 06:48:56 +00003402 "Invalid scalar expression to emit");
3403 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3404}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003405
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003406/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3407/// type to the specified destination type, where the destination type is an
3408/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003409Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3410 QualType SrcTy,
3411 QualType DstTy) {
John McCall9d232c82013-03-07 21:37:08 +00003412 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003413 "Invalid complex -> scalar conversion");
3414 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3415 DstTy);
3416}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00003417
Chris Lattner8c11a652010-06-26 22:09:34 +00003418
3419llvm::Value *CodeGenFunction::
3420EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3421 bool isInc, bool isPre) {
3422 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3423}
3424
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003425LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3426 llvm::Value *V;
3427 // object->isa or (*object).isa
3428 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003429 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00003430 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003431
3432 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00003433 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00003434 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003435 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3436 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003437 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00003438 MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003439 } else {
3440 if (E->isArrow())
3441 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3442 else
3443 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003444 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003445
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003446 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003447 ClassPtrTy = ClassPtrTy->getPointerTo();
3448 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00003449 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003450}
3451
Douglas Gregor6a03e342010-04-23 04:16:32 +00003452
John McCall2a416372010-12-05 02:00:02 +00003453LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00003454 const CompoundAssignOperator *E) {
3455 ScalarExprEmitter Scalar(*this);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003456 Value *Result = nullptr;
Douglas Gregor6a03e342010-04-23 04:16:32 +00003457 switch (E->getOpcode()) {
3458#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00003459 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00003460 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003461 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00003462 COMPOUND_OP(Mul);
3463 COMPOUND_OP(Div);
3464 COMPOUND_OP(Rem);
3465 COMPOUND_OP(Add);
3466 COMPOUND_OP(Sub);
3467 COMPOUND_OP(Shl);
3468 COMPOUND_OP(Shr);
3469 COMPOUND_OP(And);
3470 COMPOUND_OP(Xor);
3471 COMPOUND_OP(Or);
3472#undef COMPOUND_OP
Craig Topperd10e5c22013-07-26 06:16:11 +00003473
John McCall2de56d12010-08-25 11:45:40 +00003474 case BO_PtrMemD:
3475 case BO_PtrMemI:
3476 case BO_Mul:
3477 case BO_Div:
3478 case BO_Rem:
3479 case BO_Add:
3480 case BO_Sub:
3481 case BO_Shl:
3482 case BO_Shr:
3483 case BO_LT:
3484 case BO_GT:
3485 case BO_LE:
3486 case BO_GE:
3487 case BO_EQ:
3488 case BO_NE:
3489 case BO_And:
3490 case BO_Xor:
3491 case BO_Or:
3492 case BO_LAnd:
3493 case BO_LOr:
3494 case BO_Assign:
3495 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00003496 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00003497 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003498
Douglas Gregor6a03e342010-04-23 04:16:32 +00003499 llvm_unreachable("Unhandled compound assignment operator");
3500}