blob: 287dc6c02315ac04f07ef3ab19cae5f9c0b92499 [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"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000031#include "llvm/Support/CFG.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
Richard Smith4def70d2012-10-09 19:52:38 +000088 void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
89
John McCall545d9962011-06-25 02:11:03 +000090 Value *EmitLoadOfLValue(LValue LV) {
91 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000092 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000093
Chris Lattner7f02f722007-08-24 05:35:26 +000094 /// EmitLoadOfLValue - Given an expression with complex type that represents a
95 /// value l-value, this method emits the address of the l-value, then loads
96 /// and returns the result.
97 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith7ac9ef12012-09-08 02:08:36 +000098 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
Chris Lattner7f02f722007-08-24 05:35:26 +000099 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000100
Chris Lattner9abc84e2007-08-26 16:42:57 +0000101 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000102 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000103 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000104
Richard Smithb2aa66c2012-10-12 22:57:06 +0000105 /// \brief Emit a check that a conversion to or from a floating-point type
106 /// does not overflow.
107 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
108 Value *Src, QualType SrcType,
109 QualType DstType, llvm::Type *DstTy);
110
Chris Lattner3707b252007-08-26 06:48:56 +0000111 /// EmitScalarConversion - Emit a conversion from the specified type to the
112 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000113 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
114
115 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000116 /// complex type to the specified destination type, where the destination type
117 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000118 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
119 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000120
Anders Carlssona40a9f32010-05-22 17:45:10 +0000121 /// EmitNullValue - Emit a value that corresponds to null for the given type.
122 Value *EmitNullValue(QualType Ty);
123
John McCalldaa8e4e2010-11-15 09:13:47 +0000124 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
125 Value *EmitFloatToBoolConversion(Value *V) {
126 // Compare against 0.0 for fp scalars.
127 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
128 return Builder.CreateFCmpUNE(V, Zero, "tobool");
129 }
130
131 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
132 Value *EmitPointerToBoolConversion(Value *V) {
133 Value *Zero = llvm::ConstantPointerNull::get(
134 cast<llvm::PointerType>(V->getType()));
135 return Builder.CreateICmpNE(V, Zero, "tobool");
136 }
137
138 Value *EmitIntToBoolConversion(Value *V) {
139 // Because of the type rules of C, we often end up computing a
140 // logical value, then zero extending it to int, then wanting it
141 // as a logical value again. Optimize this common case.
142 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
143 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
144 Value *Result = ZI->getOperand(0);
145 // If there aren't any more uses, zap the instruction to save space.
146 // Note that there can be more uses, for example if this
147 // is the result of an assignment.
148 if (ZI->use_empty())
149 ZI->eraseFromParent();
150 return Result;
151 }
152 }
153
Chris Lattner48431f92011-04-19 22:55:03 +0000154 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000155 }
156
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 //===--------------------------------------------------------------------===//
158 // Visitor Methods
159 //===--------------------------------------------------------------------===//
160
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000161 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000162 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
163 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000164
Chris Lattner7f02f722007-08-24 05:35:26 +0000165 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000166 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000167 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000168 }
169 Value *VisitExpr(Expr *S);
Craig Topperd10e5c22013-07-26 06:16:11 +0000170
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000171 Value *VisitParenExpr(ParenExpr *PE) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000172 return Visit(PE->getSubExpr());
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000173 }
John McCall91a57552011-07-15 05:09:51 +0000174 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000175 return Visit(E->getReplacement());
John McCall91a57552011-07-15 05:09:51 +0000176 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000177 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
178 return Visit(GE->getResultExpr());
179 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000180
181 // Leaves.
182 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000183 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000184 }
185 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000186 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000187 }
188 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000189 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000190 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000191 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
192 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
193 }
Nate Begemane7579b52007-11-15 05:40:03 +0000194 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000195 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000196 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000197 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000198 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000199 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000200 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000201 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000202 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000203 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000204 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000205 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000206 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
207 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000208 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000209
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000210 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000211 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000212 }
John McCalle996ffd2011-02-16 08:02:54 +0000213
John McCall4b9c2d22011-11-06 09:01:30 +0000214 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
215 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
216 }
217
John McCalle996ffd2011-02-16 08:02:54 +0000218 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000219 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000220 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000221
222 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000223 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000224 }
John McCalldd2ecee2012-03-10 03:05:10 +0000225
Chris Lattner7f02f722007-08-24 05:35:26 +0000226 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000227 Value *VisitDeclRefExpr(DeclRefExpr *E) {
228 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000229 if (result.isReference())
John McCallf4b88a42012-03-10 09:33:50 +0000230 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000231 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000232 }
John McCallf4b88a42012-03-10 09:33:50 +0000233 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000234 }
235
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000236 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
237 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000238 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000239 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
240 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000242 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000243 return EmitLoadOfLValue(E);
244 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000245 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000246 if (E->getMethodDecl() &&
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000247 E->getMethodDecl()->getResultType()->isReferenceType())
248 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000249 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000250 }
251
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000252 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000253 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000254 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000255 return V;
256 }
257
Chris Lattner7f02f722007-08-24 05:35:26 +0000258 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000259 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000260 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000261 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000262 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
263 return EmitLoadOfLValue(E);
264 }
Devang Patel35634f52007-10-24 17:18:43 +0000265
Nate Begeman0533b302009-10-18 20:10:40 +0000266 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000267
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000268 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000269 return EmitNullValue(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000270 }
John McCallbc8d40d2011-06-24 21:55:10 +0000271 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000272 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000273 CGF.EmitVariablyModifiedType(E->getType());
274 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000275 }
John McCallbc8d40d2011-06-24 21:55:10 +0000276 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000277
278 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000279 if (E->getCallReturnType()->isReferenceType())
280 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000281
Chris Lattner9b655512007-08-31 22:49:20 +0000282 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000283 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000284
Chris Lattner33793202007-08-31 22:09:40 +0000285 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000286
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000288 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
296 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 }
300 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000301 LValue LV = EmitLValue(E->getSubExpr());
302 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000304
Anton Yartsev683564a2011-02-07 02:17:30 +0000305 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
306 llvm::Value *InVal,
307 llvm::Value *NextVal,
308 bool IsInc);
309
Chris Lattner8c11a652010-06-26 22:09:34 +0000310 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
311 bool isInc, bool isPre);
312
Craig Topperd10e5c22013-07-26 06:16:11 +0000313
Chris Lattner7f02f722007-08-24 05:35:26 +0000314 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000315 if (isa<MemberPointerType>(E->getType())) // never sugared
316 return CGF.CGM.getMemberPointerConstant(E);
317
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 return EmitLValue(E->getSubExpr()).getAddress();
319 }
John McCallfd569002010-12-04 12:43:24 +0000320 Value *VisitUnaryDeref(const UnaryOperator *E) {
321 if (E->getType()->isVoidType())
322 return Visit(E->getSubExpr()); // the actual value should be unused
323 return EmitLoadOfLValue(E);
324 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000325 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000326 // This differs from gcc, though, most likely due to a bug in gcc.
327 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 return Visit(E->getSubExpr());
329 }
330 Value *VisitUnaryMinus (const UnaryOperator *E);
331 Value *VisitUnaryNot (const UnaryOperator *E);
332 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000333 Value *VisitUnaryReal (const UnaryOperator *E);
334 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000335 Value *VisitUnaryExtension(const UnaryOperator *E) {
336 return Visit(E->getSubExpr());
337 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000338
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000339 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000340 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000341 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000342 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000343
Chris Lattner04421082008-04-08 04:40:51 +0000344 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
345 return Visit(DAE->getExpr());
346 }
Richard Smithc3bf52c2013-04-20 22:23:05 +0000347 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
348 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
349 return Visit(DIE->getExpr());
350 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000351 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
352 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000353 }
354
John McCall4765fa02010-12-06 08:20:24 +0000355 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000356 CGF.enterFullExpression(E);
357 CodeGenFunction::RunCleanupsScope Scope(CGF);
358 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000359 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000360 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
361 return CGF.EmitCXXNewExpr(E);
362 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000363 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
364 CGF.EmitCXXDeleteExpr(E);
365 return 0;
366 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000367 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000368 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000369 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000370
Francois Pichet6ad6f282010-12-07 00:08:36 +0000371 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000372 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000373 }
374
John Wiegley21ff2e52011-04-28 00:16:57 +0000375 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
377 }
378
John Wiegley55262202011-04-25 06:54:41 +0000379 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
380 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
381 }
382
Douglas Gregora71d8192009-09-04 17:36:40 +0000383 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
384 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000385 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000386 // operator (), and the result of such a call has type void. The only
387 // effect is the evaluation of the postfix-expression before the dot or
388 // arrow.
389 CGF.EmitScalarExpr(E->getBase());
390 return 0;
391 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000392
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000393 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000394 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000395 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000396
397 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
398 CGF.EmitCXXThrowExpr(E);
399 return 0;
400 }
401
Sebastian Redl98294de2010-09-10 21:04:00 +0000402 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000403 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000404 }
405
Chris Lattner7f02f722007-08-24 05:35:26 +0000406 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000407 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000408 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000409 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000410 case LangOptions::SOB_Defined:
411 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000412 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +0000413 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +0000414 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
415 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000416 case LangOptions::SOB_Trapping:
417 return EmitOverflowCheckedBinOp(Ops);
418 }
419 }
Richard Smithd6396a62012-11-05 22:21:05 +0000420
Will Dietz4f45bc02013-01-18 11:30:38 +0000421 if (Ops.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
Will Dietzb8540362012-11-27 15:01:55 +0000422 return EmitOverflowCheckedBinOp(Ops);
423
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000424 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000425 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000426 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
427 }
Mike Stump2add4732009-04-01 20:28:16 +0000428 /// Create a binary op that checks for overflow.
429 /// Currently only supports +, - and *.
430 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000431
Chris Lattner80230302010-09-11 21:47:09 +0000432 // Check for undefined division and modulus behaviors.
Craig Topperd10e5c22013-07-26 06:16:11 +0000433 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner80230302010-09-11 21:47:09 +0000434 llvm::Value *Zero,bool isDiv);
David Tweed7a834212013-01-07 16:43:27 +0000435 // Common helper for getting how wide LHS of shift is.
436 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner7f02f722007-08-24 05:35:26 +0000437 Value *EmitDiv(const BinOpInfo &Ops);
438 Value *EmitRem(const BinOpInfo &Ops);
439 Value *EmitAdd(const BinOpInfo &Ops);
440 Value *EmitSub(const BinOpInfo &Ops);
441 Value *EmitShl(const BinOpInfo &Ops);
442 Value *EmitShr(const BinOpInfo &Ops);
443 Value *EmitAnd(const BinOpInfo &Ops) {
444 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
445 }
446 Value *EmitXor(const BinOpInfo &Ops) {
447 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
448 }
449 Value *EmitOr (const BinOpInfo &Ops) {
450 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
451 }
452
Chris Lattner1f1ded92007-08-24 21:00:35 +0000453 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000454 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
455 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000456 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000457
Chris Lattner3ccf7742007-08-26 21:41:21 +0000458 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000459 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
460
461 // Binary operators and binary compound assignment operators.
462#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000463 Value *VisitBin ## OP(const BinaryOperator *E) { \
464 return Emit ## OP(EmitBinOps(E)); \
465 } \
466 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
467 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000468 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000469 HANDLEBINOP(Mul)
470 HANDLEBINOP(Div)
471 HANDLEBINOP(Rem)
472 HANDLEBINOP(Add)
473 HANDLEBINOP(Sub)
474 HANDLEBINOP(Shl)
475 HANDLEBINOP(Shr)
476 HANDLEBINOP(And)
477 HANDLEBINOP(Xor)
478 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000479#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000480
Chris Lattner7f02f722007-08-24 05:35:26 +0000481 // Comparisons.
482 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
483 unsigned SICmpOpc, unsigned FCmpOpc);
484#define VISITCOMP(CODE, UI, SI, FP) \
485 Value *VisitBin##CODE(const BinaryOperator *E) { \
486 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
487 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000488 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
489 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
490 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
491 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
492 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
493 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000494#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000495
Chris Lattner7f02f722007-08-24 05:35:26 +0000496 Value *VisitBinAssign (const BinaryOperator *E);
497
498 Value *VisitBinLAnd (const BinaryOperator *E);
499 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000500 Value *VisitBinComma (const BinaryOperator *E);
501
Eli Friedman25b825d2009-11-18 09:41:26 +0000502 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
503 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
504
Chris Lattner7f02f722007-08-24 05:35:26 +0000505 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000506 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000507 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000508 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000509 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000510 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
511 return CGF.EmitObjCStringLiteral(E);
512 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000513 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
514 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000515 }
516 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
517 return CGF.EmitObjCArrayLiteral(E);
518 }
519 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
520 return CGF.EmitObjCDictionaryLiteral(E);
521 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000522 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000523 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000524};
525} // end anonymous namespace.
526
527//===----------------------------------------------------------------------===//
528// Utilities
529//===----------------------------------------------------------------------===//
530
Chris Lattner9abc84e2007-08-26 16:42:57 +0000531/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000532/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000533Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000534 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000535
John McCalldaa8e4e2010-11-15 09:13:47 +0000536 if (SrcType->isRealFloatingType())
537 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000538
John McCall0bab0cd2010-08-23 01:21:21 +0000539 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
540 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000541
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000542 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000543 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000544
John McCalldaa8e4e2010-11-15 09:13:47 +0000545 if (isa<llvm::IntegerType>(Src->getType()))
546 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000547
John McCalldaa8e4e2010-11-15 09:13:47 +0000548 assert(isa<llvm::PointerType>(Src->getType()));
549 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000550}
551
Richard Smithb2aa66c2012-10-12 22:57:06 +0000552void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
553 QualType OrigSrcType,
554 Value *Src, QualType SrcType,
555 QualType DstType,
556 llvm::Type *DstTy) {
557 using llvm::APFloat;
558 using llvm::APSInt;
559
560 llvm::Type *SrcTy = Src->getType();
561
562 llvm::Value *Check = 0;
563 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
564 // Integer to floating-point. This can fail for unsigned short -> __half
565 // or unsigned __int128 -> float.
566 assert(DstType->isFloatingType());
567 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
568
569 APFloat LargestFloat =
570 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
571 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
572
573 bool IsExact;
574 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
575 &IsExact) != APFloat::opOK)
576 // The range of representable values of this floating point type includes
577 // all values of this integer type. Don't need an overflow check.
578 return;
579
580 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
581 if (SrcIsUnsigned)
582 Check = Builder.CreateICmpULE(Src, Max);
583 else {
584 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
585 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
586 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
587 Check = Builder.CreateAnd(GE, LE);
588 }
589 } else {
Richard Smithb2aa66c2012-10-12 22:57:06 +0000590 const llvm::fltSemantics &SrcSema =
591 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000592 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith50876452013-03-27 23:20:25 +0000593 // Floating-point to integer. This has undefined behavior if the source is
594 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
595 // to an integer).
Richard Smithb2aa66c2012-10-12 22:57:06 +0000596 unsigned Width = CGF.getContext().getIntWidth(DstType);
597 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
598
599 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith50876452013-03-27 23:20:25 +0000600 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000601 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
602 APFloat::opOverflow)
603 // Don't need an overflow check for lower bound. Just check for
604 // -Inf/NaN.
Richard Smithaa624952013-03-19 00:01:12 +0000605 MinSrc = APFloat::getInf(SrcSema, true);
606 else
607 // Find the largest value which is too small to represent (before
608 // truncation toward zero).
609 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000610
611 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith50876452013-03-27 23:20:25 +0000612 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000613 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
614 APFloat::opOverflow)
615 // Don't need an overflow check for upper bound. Just check for
616 // +Inf/NaN.
Richard Smithaa624952013-03-19 00:01:12 +0000617 MaxSrc = APFloat::getInf(SrcSema, false);
618 else
619 // Find the smallest value which is too large to represent (before
620 // truncation toward zero).
621 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000622
Richard Smith50876452013-03-27 23:20:25 +0000623 // If we're converting from __half, convert the range to float to match
624 // the type of src.
625 if (OrigSrcType->isHalfType()) {
626 const llvm::fltSemantics &Sema =
627 CGF.getContext().getFloatTypeSemantics(SrcType);
628 bool IsInexact;
629 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
630 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
631 }
Richard Smithb2aa66c2012-10-12 22:57:06 +0000632
Richard Smithaa624952013-03-19 00:01:12 +0000633 llvm::Value *GE =
634 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
635 llvm::Value *LE =
636 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
637 Check = Builder.CreateAnd(GE, LE);
638 } else {
Richard Smith50876452013-03-27 23:20:25 +0000639 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
640 //
641 // Floating-point to floating-point. This has undefined behavior if the
642 // source is not in the range of representable values of the destination
643 // type. The C and C++ standards are spectacularly unclear here. We
644 // diagnose finite out-of-range conversions, but allow infinities and NaNs
645 // to convert to the corresponding value in the smaller type.
646 //
647 // C11 Annex F gives all such conversions defined behavior for IEC 60559
648 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
649 // does not.
650
651 // Converting from a lower rank to a higher rank can never have
652 // undefined behavior, since higher-rank types must have a superset
653 // of values of lower-rank types.
654 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
655 return;
656
657 assert(!OrigSrcType->isHalfType() &&
658 "should not check conversion from __half, it has the lowest rank");
659
660 const llvm::fltSemantics &DstSema =
661 CGF.getContext().getFloatTypeSemantics(DstType);
662 APFloat MinBad = APFloat::getLargest(DstSema, false);
663 APFloat MaxBad = APFloat::getInf(DstSema, false);
664
665 bool IsInexact;
666 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
667 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
668
669 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
670 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smithaa624952013-03-19 00:01:12 +0000671 llvm::Value *GE =
Richard Smith50876452013-03-27 23:20:25 +0000672 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smithaa624952013-03-19 00:01:12 +0000673 llvm::Value *LE =
Richard Smith50876452013-03-27 23:20:25 +0000674 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
675 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smithaa624952013-03-19 00:01:12 +0000676 }
Richard Smithb2aa66c2012-10-12 22:57:06 +0000677 }
678
679 // FIXME: Provide a SourceLocation.
680 llvm::Constant *StaticArgs[] = {
681 CGF.EmitCheckTypeDescriptor(OrigSrcType),
682 CGF.EmitCheckTypeDescriptor(DstType)
683 };
Will Dietzad954812012-12-02 19:50:33 +0000684 CGF.EmitCheck(Check, "float_cast_overflow", StaticArgs, OrigSrc,
685 CodeGenFunction::CRK_Recoverable);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000686}
687
Chris Lattner3707b252007-08-26 06:48:56 +0000688/// EmitScalarConversion - Emit a conversion from the specified type to the
689/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000690Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
691 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000692 SrcType = CGF.getContext().getCanonicalType(SrcType);
693 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000694 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000695
Chris Lattnercf289082007-08-26 07:21:11 +0000696 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000697
Richard Smithb2aa66c2012-10-12 22:57:06 +0000698 llvm::Value *OrigSrc = Src;
699 QualType OrigSrcType = SrcType;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000700 llvm::Type *SrcTy = Src->getType();
701
Joey Gouly19dbb202013-01-23 11:56:20 +0000702 // If casting to/from storage-only half FP, use special intrinsics.
703 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000704 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
705 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000706 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000707 }
708
Chris Lattner3707b252007-08-26 06:48:56 +0000709 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000710 if (DstType->isBooleanType())
711 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000712
Chris Lattner2acc6e32011-07-18 04:24:23 +0000713 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000714
715 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000716 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000717 return Src;
718
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000719 // Handle pointer conversions next: pointers can only be converted to/from
720 // other pointers and integers. Check for pointer types in terms of LLVM, as
721 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000722 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000723 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000724 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000725 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000726
Chris Lattner3707b252007-08-26 06:48:56 +0000727 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000728 // First, convert to the correct width so that we control the kind of
729 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000730 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000731 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000732 llvm::Value* IntResult =
733 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
734 // Then, cast to pointer.
735 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000736 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000737
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000738 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000739 // Must be an ptr to int cast.
740 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000741 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000742 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000743
Nate Begeman213541a2008-04-18 23:10:10 +0000744 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000745 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000746 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000747 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000748 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
749
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000750 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000751 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer0b227082013-01-01 20:08:10 +0000752 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000753 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000754
Chris Lattner3b1ae002008-02-02 04:51:41 +0000755 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000756 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000757 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000758 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000759
Chris Lattner3707b252007-08-26 06:48:56 +0000760 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000761 Value *Res = NULL;
762 llvm::Type *ResTy = DstTy;
763
Richard Smithb2aa66c2012-10-12 22:57:06 +0000764 // An overflowing conversion has undefined behavior if either the source type
765 // or the destination type is a floating-point type.
Will Dietz4f45bc02013-01-18 11:30:38 +0000766 if (CGF.SanOpts->FloatCastOverflow &&
Richard Smithb2aa66c2012-10-12 22:57:06 +0000767 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Will Dietz4f45bc02013-01-18 11:30:38 +0000768 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
769 DstTy);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000770
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000771 // Cast to half via float
Joey Gouly19dbb202013-01-23 11:56:20 +0000772 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
Chris Lattner8b418682012-02-07 00:39:47 +0000773 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000774
775 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000776 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000777 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000778 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000779 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000780 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000781 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000782 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
783 } else if (isa<llvm::IntegerType>(DstTy)) {
784 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000785 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000786 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000787 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000788 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
789 } else {
790 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
791 "Unknown real conversion");
792 if (DstTy->getTypeID() < SrcTy->getTypeID())
793 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
794 else
795 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000796 }
797
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000798 if (DstTy != ResTy) {
799 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
800 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
801 }
802
803 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000804}
805
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000806/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
807/// type to the specified destination type, where the destination type is an
808/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000809Value *ScalarExprEmitter::
810EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
811 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000812 // Get the source element type.
John McCall9d232c82013-03-07 21:37:08 +0000813 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000814
Chris Lattnered70f0a2007-08-26 16:52:28 +0000815 // Handle conversions to bool first, they are special: comparisons against 0.
816 if (DstTy->isBooleanType()) {
817 // Complex != 0 -> (Real != 0) | (Imag != 0)
818 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
819 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
820 return Builder.CreateOr(Src.first, Src.second, "tobool");
821 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000822
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000823 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
824 // the imaginary part of the complex value is discarded and the value of the
825 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000826 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000827 return EmitScalarConversion(Src.first, SrcTy, DstTy);
828}
829
Anders Carlssona40a9f32010-05-22 17:45:10 +0000830Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000831 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlssona40a9f32010-05-22 17:45:10 +0000832}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000833
Richard Smith4def70d2012-10-09 19:52:38 +0000834/// \brief Emit a sanitization check for the given "binary" operation (which
835/// might actually be a unary increment which has been lowered to a binary
836/// operation). The check passes if \p Check, which is an \c i1, is \c true.
837void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
838 StringRef CheckName;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000839 SmallVector<llvm::Constant *, 4> StaticData;
840 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smith4def70d2012-10-09 19:52:38 +0000841
842 BinaryOperatorKind Opcode = Info.Opcode;
843 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
844 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
845
846 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
847 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
848 if (UO && UO->getOpcode() == UO_Minus) {
849 CheckName = "negate_overflow";
850 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
851 DynamicData.push_back(Info.RHS);
852 } else {
853 if (BinaryOperator::isShiftOp(Opcode)) {
854 // Shift LHS negative or too large, or RHS out of bounds.
855 CheckName = "shift_out_of_bounds";
856 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
857 StaticData.push_back(
858 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
859 StaticData.push_back(
860 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
861 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
862 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
863 CheckName = "divrem_overflow";
Will Dietz822023a2013-01-07 22:25:52 +0000864 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000865 } else {
866 // Signed arithmetic overflow (+, -, *).
867 switch (Opcode) {
868 case BO_Add: CheckName = "add_overflow"; break;
869 case BO_Sub: CheckName = "sub_overflow"; break;
870 case BO_Mul: CheckName = "mul_overflow"; break;
871 default: llvm_unreachable("unexpected opcode for bin op check");
872 }
Will Dietz822023a2013-01-07 22:25:52 +0000873 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000874 }
875 DynamicData.push_back(Info.LHS);
876 DynamicData.push_back(Info.RHS);
877 }
878
Will Dietzad954812012-12-02 19:50:33 +0000879 CGF.EmitCheck(Check, CheckName, StaticData, DynamicData,
880 CodeGenFunction::CRK_Recoverable);
Richard Smith4def70d2012-10-09 19:52:38 +0000881}
882
Chris Lattner7f02f722007-08-24 05:35:26 +0000883//===----------------------------------------------------------------------===//
884// Visitor Methods
885//===----------------------------------------------------------------------===//
886
887Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000888 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000889 if (E->getType()->isVoidType())
890 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000891 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000892}
893
Eli Friedmand38617c2008-05-14 19:38:39 +0000894Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000895 // Vector Mask Case
Craig Topperd10e5c22013-07-26 06:16:11 +0000896 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000897 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000898 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
899 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
900 Value *Mask;
Craig Topperd10e5c22013-07-26 06:16:11 +0000901
Chris Lattner2acc6e32011-07-18 04:24:23 +0000902 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000903 unsigned LHSElts = LTy->getNumElements();
904
905 if (E->getNumSubExprs() == 3) {
906 Mask = CGF.EmitScalarExpr(E->getExpr(2));
Craig Topperd10e5c22013-07-26 06:16:11 +0000907
Nate Begeman37b6a572010-06-08 00:16:34 +0000908 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000909 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000910 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000911 concat.push_back(Builder.getInt32(2*i));
912 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000913 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000914
Chris Lattnerfb018d12011-02-15 00:14:06 +0000915 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000916 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
917 LHSElts *= 2;
918 } else {
919 Mask = RHS;
920 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000921
Chris Lattner2acc6e32011-07-18 04:24:23 +0000922 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000923 llvm::Constant* EltMask;
Craig Topperd10e5c22013-07-26 06:16:11 +0000924
Craig Topper2f665122013-08-01 06:42:40 +0000925 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
926 llvm::NextPowerOf2(LHSElts-1)-1);
Craig Topperd10e5c22013-07-26 06:16:11 +0000927
Nate Begeman37b6a572010-06-08 00:16:34 +0000928 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000929 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
930 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000931 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Topperd10e5c22013-07-26 06:16:11 +0000932
Nate Begeman37b6a572010-06-08 00:16:34 +0000933 // newv = undef
934 // mask = mask & maskbits
935 // for each elt
936 // n = extract mask i
937 // x = extract val n
938 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000939 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper34d55e12013-07-27 05:00:42 +0000940 MTy->getNumElements());
Nate Begeman37b6a572010-06-08 00:16:34 +0000941 Value* NewV = llvm::UndefValue::get(RTy);
942 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman87b9c032012-04-05 21:48:40 +0000943 Value *IIndx = Builder.getInt32(i);
944 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000945 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Craig Topperd10e5c22013-07-26 06:16:11 +0000946
Nate Begeman37b6a572010-06-08 00:16:34 +0000947 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +0000948 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +0000949 }
950 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000951 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000952
Eli Friedmand38617c2008-05-14 19:38:39 +0000953 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
954 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Topperd10e5c22013-07-26 06:16:11 +0000955
Chris Lattner5f9e2722011-07-23 10:55:15 +0000956 SmallVector<llvm::Constant*, 32> indices;
Craig Topper72c422c2013-08-01 04:51:48 +0000957 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper6f4f8082013-08-03 17:40:38 +0000958 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
959 // Check for -1 and output it as undef in the IR.
960 if (Idx.isSigned() && Idx.isAllOnesValue())
961 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
962 else
963 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begeman37b6a572010-06-08 00:16:34 +0000964 }
965
Chris Lattnerfb018d12011-02-15 00:14:06 +0000966 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000967 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
968}
Eli Friedman28665272009-11-26 03:22:21 +0000969Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000970 llvm::APSInt Value;
971 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000972 if (E->isArrow())
973 CGF.EmitScalarExpr(E->getBase());
974 else
975 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000976 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000977 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000978
Eli Friedman28665272009-11-26 03:22:21 +0000979 return EmitLoadOfLValue(E);
980}
Eli Friedmand38617c2008-05-14 19:38:39 +0000981
Chris Lattner7f02f722007-08-24 05:35:26 +0000982Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000983 TestAndClearIgnoreResultAssign();
984
Chris Lattner7f02f722007-08-24 05:35:26 +0000985 // Emit subscript expressions in rvalue context's. For most cases, this just
986 // loads the lvalue formed by the subscript expr. However, we have to be
987 // careful, because the base of a vector subscript is occasionally an rvalue,
988 // so we can't get it as an lvalue.
989 if (!E->getBase()->getType()->isVectorType())
990 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000991
Chris Lattner7f02f722007-08-24 05:35:26 +0000992 // Handle the vector case. The base must be a vector, the index must be an
993 // integer value.
994 Value *Base = Visit(E->getBase());
995 Value *Idx = Visit(E->getIdx());
Richard Smitha0a628f2013-02-23 02:53:19 +0000996 QualType IdxTy = E->getIdx()->getType();
997
998 if (CGF.SanOpts->Bounds)
999 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1000
1001 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +00001002 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001003 return Builder.CreateExtractElement(Base, Idx, "vecext");
1004}
1005
Nate Begeman0533b302009-10-18 20:10:40 +00001006static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001007 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +00001008 int MV = SVI->getMaskValue(Idx);
Craig Topperd10e5c22013-07-26 06:16:11 +00001009 if (MV == -1)
Nate Begeman0533b302009-10-18 20:10:40 +00001010 return llvm::UndefValue::get(I32Ty);
1011 return llvm::ConstantInt::get(I32Ty, Off+MV);
1012}
1013
1014Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1015 bool Ignore = TestAndClearIgnoreResultAssign();
1016 (void)Ignore;
1017 assert (Ignore == false && "init list ignored");
1018 unsigned NumInitElements = E->getNumInits();
Craig Topperd10e5c22013-07-26 06:16:11 +00001019
Nate Begeman0533b302009-10-18 20:10:40 +00001020 if (E->hadArrayRangeDesignator())
1021 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Topperd10e5c22013-07-26 06:16:11 +00001022
Chris Lattner2acc6e32011-07-18 04:24:23 +00001023 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +00001024 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Topperd10e5c22013-07-26 06:16:11 +00001025
Sebastian Redlcea8d962011-09-24 17:48:14 +00001026 if (!VType) {
1027 if (NumInitElements == 0) {
1028 // C++11 value-initialization for the scalar.
1029 return EmitNullValue(E->getType());
1030 }
1031 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +00001032 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +00001033 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001034
Nate Begeman0533b302009-10-18 20:10:40 +00001035 unsigned ResElts = VType->getNumElements();
Craig Topperd10e5c22013-07-26 06:16:11 +00001036
1037 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman0533b302009-10-18 20:10:40 +00001038 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1039 // us to fold the shuffle for the swizzle into the shuffle for the vector
1040 // initializer, since LLVM optimizers generally do not want to touch
1041 // shuffles.
1042 unsigned CurIdx = 0;
1043 bool VIsUndefShuffle = false;
1044 llvm::Value *V = llvm::UndefValue::get(VType);
1045 for (unsigned i = 0; i != NumInitElements; ++i) {
1046 Expr *IE = E->getInit(i);
1047 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001048 SmallVector<llvm::Constant*, 16> Args;
Craig Topperd10e5c22013-07-26 06:16:11 +00001049
Chris Lattner2acc6e32011-07-18 04:24:23 +00001050 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001051
Nate Begeman0533b302009-10-18 20:10:40 +00001052 // Handle scalar elements. If the scalar initializer is actually one
Craig Topperd10e5c22013-07-26 06:16:11 +00001053 // element of a different vector of the same width, use shuffle instead of
Nate Begeman0533b302009-10-18 20:10:40 +00001054 // extract+insert.
1055 if (!VVT) {
1056 if (isa<ExtVectorElementExpr>(IE)) {
1057 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1058
1059 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1060 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1061 Value *LHS = 0, *RHS = 0;
1062 if (CurIdx == 0) {
1063 // insert into undef -> shuffle (src, undef)
1064 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +00001065 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001066
1067 LHS = EI->getVectorOperand();
1068 RHS = V;
1069 VIsUndefShuffle = true;
1070 } else if (VIsUndefShuffle) {
1071 // insert into undefshuffle && size match -> shuffle (v, src)
1072 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1073 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001074 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +00001075 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001076 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1077
Nate Begeman0533b302009-10-18 20:10:40 +00001078 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1079 RHS = EI->getVectorOperand();
1080 VIsUndefShuffle = false;
1081 }
1082 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +00001083 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001084 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1085 ++CurIdx;
1086 continue;
1087 }
1088 }
1089 }
Chris Lattner48431f92011-04-19 22:55:03 +00001090 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1091 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +00001092 VIsUndefShuffle = false;
1093 ++CurIdx;
1094 continue;
1095 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001096
Nate Begeman0533b302009-10-18 20:10:40 +00001097 unsigned InitElts = VVT->getNumElements();
1098
Craig Topperd10e5c22013-07-26 06:16:11 +00001099 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman0533b302009-10-18 20:10:40 +00001100 // input is the same width as the vector being constructed, generate an
1101 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +00001102 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +00001103 if (isa<ExtVectorElementExpr>(IE)) {
1104 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1105 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001106 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001107
Nate Begeman0533b302009-10-18 20:10:40 +00001108 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +00001109 for (unsigned j = 0; j != CurIdx; ++j) {
1110 // If the current vector initializer is a shuffle with undef, merge
1111 // this shuffle directly into it.
1112 if (VIsUndefShuffle) {
1113 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +00001114 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001115 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001116 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001117 }
1118 }
1119 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001120 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001121 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001122
1123 if (VIsUndefShuffle)
1124 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1125
1126 Init = SVOp;
1127 }
1128 }
1129
1130 // Extend init to result vector length, and then shuffle its contribution
1131 // to the vector initializer into V.
1132 if (Args.empty()) {
1133 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001134 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001135 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +00001136 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001137 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +00001138 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +00001139
1140 Args.clear();
1141 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001142 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001143 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001144 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001145 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001146 }
1147
1148 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1149 // merging subsequent shuffles into this one.
1150 if (CurIdx == 0)
1151 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +00001152 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001153 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1154 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1155 CurIdx += InitElts;
1156 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001157
Nate Begeman0533b302009-10-18 20:10:40 +00001158 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1159 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001160 llvm::Type *EltTy = VType->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00001161
Nate Begeman0533b302009-10-18 20:10:40 +00001162 // Emit remaining default initializers
1163 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +00001164 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +00001165 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1166 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1167 }
1168 return V;
1169}
1170
Anders Carlssona3697c92009-11-23 17:57:54 +00001171static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1172 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001173
John McCall2de56d12010-08-25 11:45:40 +00001174 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001175 return false;
Craig Topperd10e5c22013-07-26 06:16:11 +00001176
Anders Carlssona3697c92009-11-23 17:57:54 +00001177 if (isa<CXXThisExpr>(E)) {
1178 // We always assume that 'this' is never null.
1179 return false;
1180 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001181
Anders Carlssona3697c92009-11-23 17:57:54 +00001182 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001183 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001184 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001185 return false;
1186 }
1187
1188 return true;
1189}
1190
Chris Lattner7f02f722007-08-24 05:35:26 +00001191// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1192// have to handle a more broad range of conversions than explicit casts, as they
1193// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001194Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001195 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001196 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001197 CastKind Kind = CE->getCastKind();
Craig Topperd10e5c22013-07-26 06:16:11 +00001198
Mike Stump7f79f9b2009-05-29 15:46:01 +00001199 if (!DestTy->isVoidType())
1200 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001201
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001202 // Since almost all cast kinds apply to scalars, this switch doesn't have
1203 // a default case, so the compiler will warn on a missing case. The cases
1204 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001205 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001206 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001207 case CK_BuiltinFnToFnPtr:
1208 llvm_unreachable("builtin functions are handled elsewhere");
1209
Craig Topperd10e5c22013-07-26 06:16:11 +00001210 case CK_LValueBitCast:
John McCall2de56d12010-08-25 11:45:40 +00001211 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001212 Value *V = EmitLValue(E).getAddress();
Craig Topperd10e5c22013-07-26 06:16:11 +00001213 V = Builder.CreateBitCast(V,
Douglas Gregore39a3892010-07-13 23:17:26 +00001214 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001215 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001216 }
John McCalldc05b112011-09-10 01:16:55 +00001217
John McCall1d9b3b22011-09-09 05:25:32 +00001218 case CK_CPointerToObjCPointerCast:
1219 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001220 case CK_AnyPointerToBlockPointerCast:
1221 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001222 Value *Src = Visit(const_cast<Expr*>(E));
1223 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1224 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001225 case CK_AtomicToNonAtomic:
1226 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001227 case CK_NoOp:
1228 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001229 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001230
John McCall2de56d12010-08-25 11:45:40 +00001231 case CK_BaseToDerived: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001232 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1233 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1234
Richard Smithc7648302013-02-13 21:18:23 +00001235 llvm::Value *V = Visit(E);
1236
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001237 llvm::Value *Derived =
1238 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1239 CE->path_begin(), CE->path_end(),
1240 ShouldNullCheckClassCastValue(CE));
1241
Richard Smithc7648302013-02-13 21:18:23 +00001242 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1243 // performed and the object is not of the derived type.
1244 if (CGF.SanitizePerformTypeCheck)
1245 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001246 Derived, DestTy->getPointeeType());
Richard Smithc7648302013-02-13 21:18:23 +00001247
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001248 return Derived;
Anders Carlssona3697c92009-11-23 17:57:54 +00001249 }
John McCall2de56d12010-08-25 11:45:40 +00001250 case CK_UncheckedDerivedToBase:
1251 case CK_DerivedToBase: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001252 const CXXRecordDecl *DerivedClassDecl =
1253 E->getType()->getPointeeCXXRecordDecl();
1254 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson191dfe92009-09-12 04:57:16 +00001255
Craig Topperd10e5c22013-07-26 06:16:11 +00001256 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001257 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001258 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001259 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001260 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001261 Value *V = Visit(const_cast<Expr*>(E));
1262 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1263 return CGF.EmitDynamicCast(V, DCE);
1264 }
Eli Friedmand8889622009-11-27 04:41:50 +00001265
John McCall2de56d12010-08-25 11:45:40 +00001266 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001267 assert(E->getType()->isArrayType() &&
1268 "Array to pointer decay must have array source type!");
1269
1270 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1271
1272 // Note that VLA pointers are always decayed, so we don't need to do
1273 // anything here.
1274 if (!E->getType()->isVariableArrayType()) {
1275 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1276 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1277 ->getElementType()) &&
1278 "Expected pointer to array");
1279 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1280 }
1281
Chris Lattner410b12e2011-07-20 04:31:01 +00001282 // Make sure the array decay ends up being the right type. This matters if
1283 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001284 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001285 }
John McCall2de56d12010-08-25 11:45:40 +00001286 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001287 return EmitLValue(E).getAddress();
1288
John McCall404cd162010-11-13 01:35:44 +00001289 case CK_NullToPointer:
1290 if (MustVisitNullValue(E))
1291 (void) Visit(E);
1292
1293 return llvm::ConstantPointerNull::get(
1294 cast<llvm::PointerType>(ConvertType(DestTy)));
1295
John McCall2de56d12010-08-25 11:45:40 +00001296 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001297 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001298 (void) Visit(E);
1299
John McCall0bab0cd2010-08-23 01:21:21 +00001300 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1301 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1302 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001303
John McCall4d4e5c12012-02-15 01:22:51 +00001304 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001305 case CK_BaseToDerivedMemberPointer:
1306 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001307 Value *Src = Visit(E);
Craig Topperd10e5c22013-07-26 06:16:11 +00001308
John McCalld608cdb2010-08-22 10:59:02 +00001309 // Note that the AST doesn't distinguish between checked and
1310 // unchecked member pointer conversions, so we always have to
1311 // implement checked conversions here. This is inefficient when
1312 // actual control flow may be required in order to perform the
1313 // check, which it is for data member pointers (but not member
1314 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001315 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001316 }
John McCallf85e1932011-06-15 23:02:42 +00001317
John McCall33e56f32011-09-10 06:18:15 +00001318 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001319 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001320 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001321 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001322 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001323 llvm::Value *value = Visit(E);
1324 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1325 return CGF.EmitObjCConsumeObject(E->getType(), value);
1326 }
John McCall348f16f2011-10-04 06:23:45 +00001327 case CK_ARCExtendBlockObject:
1328 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001329
Douglas Gregorac1303e2012-02-22 05:02:47 +00001330 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001331 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001332
John McCall2bb5d002010-11-13 09:02:35 +00001333 case CK_FloatingRealToComplex:
1334 case CK_FloatingComplexCast:
1335 case CK_IntegralRealToComplex:
1336 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001337 case CK_IntegralComplexToFloatingComplex:
1338 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001339 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001340 case CK_ToUnion:
1341 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001342
John McCall0ae287a2010-12-01 04:43:34 +00001343 case CK_LValueToRValue:
1344 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001345 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001346 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001347
John McCall2de56d12010-08-25 11:45:40 +00001348 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001349 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001350
Anders Carlsson82debc72009-10-18 18:12:03 +00001351 // First, convert to the correct width so that we control the kind of
1352 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001353 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001354 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001355 llvm::Value* IntResult =
1356 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001357
Anders Carlsson82debc72009-10-18 18:12:03 +00001358 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001359 }
Eli Friedman65949422011-06-25 02:58:47 +00001360 case CK_PointerToIntegral:
1361 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1362 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001363
John McCall2de56d12010-08-25 11:45:40 +00001364 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001365 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001366 return 0;
1367 }
John McCall2de56d12010-08-25 11:45:40 +00001368 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001369 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001370 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001371 Elt = EmitScalarConversion(Elt, E->getType(),
1372 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001373
Eli Friedmanad35a832009-11-16 21:33:53 +00001374 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001375 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer0b227082013-01-01 20:08:10 +00001376 return Builder.CreateVectorSplat(NumElements, Elt, "splat");;
Eli Friedmanad35a832009-11-16 21:33:53 +00001377 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001378
John McCall2de56d12010-08-25 11:45:40 +00001379 case CK_IntegralCast:
1380 case CK_IntegralToFloating:
1381 case CK_FloatingToIntegral:
1382 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001383 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001384 case CK_IntegralToBoolean:
1385 return EmitIntToBoolConversion(Visit(E));
1386 case CK_PointerToBoolean:
1387 return EmitPointerToBoolConversion(Visit(E));
1388 case CK_FloatingToBoolean:
1389 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001390 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001391 llvm::Value *MemPtr = Visit(E);
1392 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1393 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001394 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001395
1396 case CK_FloatingComplexToReal:
1397 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001398 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001399
1400 case CK_FloatingComplexToBoolean:
1401 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001402 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001403
1404 // TODO: kill this function off, inline appropriate case here
1405 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1406 }
1407
Guy Benyeie6b9d802013-01-20 12:31:11 +00001408 case CK_ZeroToOCLEvent: {
1409 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non event type");
1410 return llvm::Constant::getNullValue(ConvertType(DestTy));
1411 }
1412
John McCall0bab0cd2010-08-23 01:21:21 +00001413 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001414
John McCall61ad0e62010-11-16 06:21:14 +00001415 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001416}
1417
Chris Lattner33793202007-08-31 22:09:40 +00001418Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001419 CodeGenFunction::StmtExprEvaluation eval(CGF);
Eli Friedman2ac2fa72013-06-10 22:04:49 +00001420 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1421 !E->getType()->isVoidType());
1422 if (!RetAlloca)
1423 return 0;
1424 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()));
1425
Chris Lattner33793202007-08-31 22:09:40 +00001426}
1427
Chris Lattner7f02f722007-08-24 05:35:26 +00001428//===----------------------------------------------------------------------===//
1429// Unary Operators
1430//===----------------------------------------------------------------------===//
1431
Chris Lattner8c11a652010-06-26 22:09:34 +00001432llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001433EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1434 llvm::Value *InVal,
1435 llvm::Value *NextVal, bool IsInc) {
Richard Smith7edf9e32012-11-01 22:30:59 +00001436 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001437 case LangOptions::SOB_Defined:
1438 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001439 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +00001440 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +00001441 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1442 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001443 case LangOptions::SOB_Trapping:
1444 BinOpInfo BinOp;
1445 BinOp.LHS = InVal;
1446 BinOp.RHS = NextVal;
1447 BinOp.Ty = E->getType();
1448 BinOp.Opcode = BO_Add;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001449 BinOp.FPContractable = false;
Anton Yartsev683564a2011-02-07 02:17:30 +00001450 BinOp.E = E;
1451 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001452 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001453 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001454}
1455
John McCall5936e332011-02-15 09:22:45 +00001456llvm::Value *
1457ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1458 bool isInc, bool isPre) {
Craig Topperd10e5c22013-07-26 06:16:11 +00001459
John McCall5936e332011-02-15 09:22:45 +00001460 QualType type = E->getSubExpr()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00001461 llvm::PHINode *atomicPHI = 0;
David Chisnall72c1dba2013-03-03 16:02:42 +00001462 llvm::Value *value;
1463 llvm::Value *input;
Anton Yartsev683564a2011-02-07 02:17:30 +00001464
John McCall5936e332011-02-15 09:22:45 +00001465 int amount = (isInc ? 1 : -1);
1466
David Chisnall7a7ee302012-01-16 17:27:18 +00001467 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnall72c1dba2013-03-03 16:02:42 +00001468 type = atomicTy->getValueType();
1469 if (isInc && type->isBooleanType()) {
1470 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1471 if (isPre) {
1472 Builder.Insert(new llvm::StoreInst(True,
1473 LV.getAddress(), LV.isVolatileQualified(),
1474 LV.getAlignment().getQuantity(),
1475 llvm::SequentiallyConsistent));
1476 return Builder.getTrue();
1477 }
1478 // For atomic bool increment, we just store true and return it for
1479 // preincrement, do an atomic swap with true for postincrement
1480 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1481 LV.getAddress(), True, llvm::SequentiallyConsistent);
1482 }
1483 // Special case for atomic increment / decrement on integers, emit
1484 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Topperd10e5c22013-07-26 06:16:11 +00001485 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnall72c1dba2013-03-03 16:02:42 +00001486 if (!type->isBooleanType() && type->isIntegerType() &&
1487 !(type->isUnsignedIntegerType() &&
1488 CGF.SanOpts->UnsignedIntegerOverflow) &&
1489 CGF.getLangOpts().getSignedOverflowBehavior() !=
1490 LangOptions::SOB_Trapping) {
1491 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1492 llvm::AtomicRMWInst::Sub;
1493 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1494 llvm::Instruction::Sub;
1495 llvm::Value *amt = CGF.EmitToMemory(
1496 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1497 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1498 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1499 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1500 }
1501 value = EmitLoadOfLValue(LV);
1502 input = value;
1503 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnall7a7ee302012-01-16 17:27:18 +00001504 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1505 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnall72c1dba2013-03-03 16:02:42 +00001506 value = CGF.EmitToMemory(value, type);
David Chisnall7a7ee302012-01-16 17:27:18 +00001507 Builder.CreateBr(opBB);
1508 Builder.SetInsertPoint(opBB);
1509 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1510 atomicPHI->addIncoming(value, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001511 value = atomicPHI;
David Chisnall72c1dba2013-03-03 16:02:42 +00001512 } else {
1513 value = EmitLoadOfLValue(LV);
1514 input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001515 }
1516
John McCall5936e332011-02-15 09:22:45 +00001517 // Special case of integer increment that we have to check first: bool++.
1518 // Due to promotion rules, we get:
1519 // bool++ -> bool = bool + 1
1520 // -> bool = (int)bool + 1
1521 // -> bool = ((int)bool + 1 != 0)
1522 // An interesting aspect of this is that increment is always true.
1523 // Decrement does not have this property.
1524 if (isInc && type->isBooleanType()) {
1525 value = Builder.getTrue();
1526
1527 // Most common case by far: integer increment.
1528 } else if (type->isIntegerType()) {
1529
Michael Liao36d5cea2012-08-28 16:55:13 +00001530 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001531
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001532 // Note that signed integer inc/dec with width less than int can't
1533 // overflow because of promotion rules; we're just eliding a few steps here.
Will Dietzb8540362012-11-27 15:01:55 +00001534 if (value->getType()->getPrimitiveSizeInBits() >=
1535 CGF.IntTy->getBitWidth() &&
1536 type->isSignedIntegerOrEnumerationType()) {
John McCall5936e332011-02-15 09:22:45 +00001537 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
Will Dietzb8540362012-11-27 15:01:55 +00001538 } else if (value->getType()->getPrimitiveSizeInBits() >=
Will Dietz4f45bc02013-01-18 11:30:38 +00001539 CGF.IntTy->getBitWidth() && type->isUnsignedIntegerType() &&
1540 CGF.SanOpts->UnsignedIntegerOverflow) {
Will Dietzb8540362012-11-27 15:01:55 +00001541 BinOpInfo BinOp;
1542 BinOp.LHS = value;
1543 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1544 BinOp.Ty = E->getType();
1545 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1546 BinOp.FPContractable = false;
1547 BinOp.E = E;
1548 value = EmitOverflowCheckedBinOp(BinOp);
1549 } else
John McCall5936e332011-02-15 09:22:45 +00001550 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Craig Topperd10e5c22013-07-26 06:16:11 +00001551
John McCall5936e332011-02-15 09:22:45 +00001552 // Next most common: pointer increment.
1553 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1554 QualType type = ptr->getPointeeType();
1555
1556 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001557 if (const VariableArrayType *vla
1558 = CGF.getContext().getAsVariableArrayType(type)) {
1559 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001560 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith7edf9e32012-11-01 22:30:59 +00001561 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001562 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001563 else
John McCallbc8d40d2011-06-24 21:55:10 +00001564 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
Craig Topperd10e5c22013-07-26 06:16:11 +00001565
John McCall5936e332011-02-15 09:22:45 +00001566 // Arithmetic on function pointers (!) is just +-1.
1567 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001568 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001569
1570 value = CGF.EmitCastToVoidPtr(value);
Richard Smith7edf9e32012-11-01 22:30:59 +00001571 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001572 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1573 else
1574 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001575 value = Builder.CreateBitCast(value, input->getType());
1576
1577 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001578 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001579 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith7edf9e32012-11-01 22:30:59 +00001580 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001581 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1582 else
1583 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001584 }
1585
1586 // Vector increment/decrement.
1587 } else if (type->isVectorType()) {
1588 if (type->hasIntegerRepresentation()) {
1589 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1590
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001591 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001592 } else {
1593 value = Builder.CreateFAdd(
1594 value,
1595 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001596 isInc ? "inc" : "dec");
1597 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001598
John McCall5936e332011-02-15 09:22:45 +00001599 // Floating point.
1600 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001601 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001602 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001603
Joey Gouly19dbb202013-01-23 11:56:20 +00001604 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001605 // Another special case: half FP increment should be done via float
1606 value =
1607 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1608 input);
1609 }
1610
John McCall5936e332011-02-15 09:22:45 +00001611 if (value->getType()->isFloatTy())
1612 amt = llvm::ConstantFP::get(VMContext,
1613 llvm::APFloat(static_cast<float>(amount)));
1614 else if (value->getType()->isDoubleTy())
1615 amt = llvm::ConstantFP::get(VMContext,
1616 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001617 else {
John McCall5936e332011-02-15 09:22:45 +00001618 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001619 bool ignored;
John McCall64aa4b32013-04-16 22:48:15 +00001620 F.convert(CGF.getTarget().getLongDoubleFormat(),
1621 llvm::APFloat::rmTowardZero, &ignored);
John McCall5936e332011-02-15 09:22:45 +00001622 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001623 }
John McCall5936e332011-02-15 09:22:45 +00001624 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1625
Joey Gouly19dbb202013-01-23 11:56:20 +00001626 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001627 value =
1628 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1629 value);
1630
John McCall5936e332011-02-15 09:22:45 +00001631 // Objective-C pointer types.
1632 } else {
1633 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1634 value = CGF.EmitCastToVoidPtr(value);
1635
1636 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1637 if (!isInc) size = -size;
1638 llvm::Value *sizeValue =
1639 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1640
Richard Smith7edf9e32012-11-01 22:30:59 +00001641 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001642 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1643 else
1644 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001645 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001646 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001647
David Chisnall7a7ee302012-01-16 17:27:18 +00001648 if (atomicPHI) {
1649 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1650 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1651 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
David Chisnall72c1dba2013-03-03 16:02:42 +00001652 CGF.EmitToMemory(value, type), llvm::SequentiallyConsistent);
David Chisnall7a7ee302012-01-16 17:27:18 +00001653 atomicPHI->addIncoming(old, opBB);
1654 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1655 Builder.CreateCondBr(success, contBB, opBB);
1656 Builder.SetInsertPoint(contBB);
1657 return isPre ? value : input;
1658 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001659
Chris Lattner8c11a652010-06-26 22:09:34 +00001660 // Store the updated result through the lvalue.
1661 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001662 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001663 else
John McCall545d9962011-06-25 02:11:03 +00001664 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001665
Chris Lattner8c11a652010-06-26 22:09:34 +00001666 // If this is a postinc, return the value read from memory, otherwise use the
1667 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001668 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001669}
1670
1671
1672
Chris Lattner7f02f722007-08-24 05:35:26 +00001673Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001674 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001675 // Emit unary minus with EmitSub so we handle overflow cases etc.
1676 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001677 BinOp.RHS = Visit(E->getSubExpr());
Craig Topperd10e5c22013-07-26 06:16:11 +00001678
Chris Lattner4ac0d832010-06-28 17:12:37 +00001679 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1680 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001681 else
Chris Lattner4ac0d832010-06-28 17:12:37 +00001682 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001683 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001684 BinOp.Opcode = BO_Sub;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001685 BinOp.FPContractable = false;
Chris Lattner9a207232010-06-26 21:48:21 +00001686 BinOp.E = E;
1687 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001688}
1689
1690Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001691 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001692 Value *Op = Visit(E->getSubExpr());
1693 return Builder.CreateNot(Op, "neg");
1694}
1695
1696Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001697 // Perform vector logical not on comparison with zero vector.
1698 if (E->getType()->isExtVectorType()) {
1699 Value *Oper = Visit(E->getSubExpr());
1700 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00001701 Value *Result;
1702 if (Oper->getType()->isFPOrFPVectorTy())
1703 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1704 else
1705 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner4f692c22012-01-16 21:02:28 +00001706 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1707 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001708
Chris Lattner7f02f722007-08-24 05:35:26 +00001709 // Compare operand to zero.
1710 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001711
Chris Lattner7f02f722007-08-24 05:35:26 +00001712 // Invert value.
1713 // TODO: Could dynamically modify easy computations here. For example, if
1714 // the operand is an icmp ne, turn into icmp eq.
1715 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001716
Anders Carlsson9f84d882009-05-19 18:44:53 +00001717 // ZExt result to the expr type.
1718 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001719}
1720
Eli Friedman0027d2b2010-08-05 09:58:49 +00001721Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1722 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001723 llvm::APSInt Value;
1724 if (E->EvaluateAsInt(Value, CGF.getContext()))
1725 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001726
1727 // Loop over the components of the offsetof to compute the value.
1728 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001729 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001730 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1731 QualType CurrentType = E->getTypeSourceInfo()->getType();
1732 for (unsigned i = 0; i != n; ++i) {
1733 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001734 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001735 switch (ON.getKind()) {
1736 case OffsetOfExpr::OffsetOfNode::Array: {
1737 // Compute the index
1738 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1739 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001740 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001741 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1742
1743 // Save the element type
1744 CurrentType =
1745 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1746
1747 // Compute the element size
1748 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1749 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1750
1751 // Multiply out to compute the result
1752 Offset = Builder.CreateMul(Idx, ElemSize);
1753 break;
1754 }
1755
1756 case OffsetOfExpr::OffsetOfNode::Field: {
1757 FieldDecl *MemberDecl = ON.getField();
1758 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1759 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1760
1761 // Compute the index of the field in its parent.
1762 unsigned i = 0;
1763 // FIXME: It would be nice if we didn't have to loop here!
1764 for (RecordDecl::field_iterator Field = RD->field_begin(),
1765 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001766 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001767 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001768 break;
1769 }
1770 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1771
1772 // Compute the offset to the field
1773 int64_t OffsetInt = RL.getFieldOffset(i) /
1774 CGF.getContext().getCharWidth();
1775 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1776
1777 // Save the element type.
1778 CurrentType = MemberDecl->getType();
1779 break;
1780 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001781
Eli Friedman0027d2b2010-08-05 09:58:49 +00001782 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001783 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001784
Eli Friedman0027d2b2010-08-05 09:58:49 +00001785 case OffsetOfExpr::OffsetOfNode::Base: {
1786 if (ON.getBase()->isVirtual()) {
1787 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1788 continue;
1789 }
1790
1791 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1792 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1793
1794 // Save the element type.
1795 CurrentType = ON.getBase()->getType();
Craig Topperd10e5c22013-07-26 06:16:11 +00001796
Eli Friedman0027d2b2010-08-05 09:58:49 +00001797 // Compute the offset to the base.
1798 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1799 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001800 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1801 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001802 break;
1803 }
1804 }
1805 Result = Builder.CreateAdd(Result, Offset);
1806 }
1807 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001808}
1809
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001810/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001811/// argument of the sizeof expression as an integer.
1812Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001813ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1814 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001815 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001816 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001817 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001818 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1819 if (E->isArgumentType()) {
1820 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001821 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001822 } else {
1823 // C99 6.5.3.4p2: If the argument is an expression of type
1824 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001825 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001826 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001827
John McCallbc8d40d2011-06-24 21:55:10 +00001828 QualType eltType;
1829 llvm::Value *numElts;
1830 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1831
1832 llvm::Value *size = numElts;
1833
1834 // Scale the number of non-VLA elements by the non-VLA element size.
1835 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1836 if (!eltSize.isOne())
1837 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1838
1839 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001840 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001841 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001842
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001843 // If this isn't sizeof(vla), the result must be constant; use the constant
1844 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001845 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001846}
1847
Chris Lattner46f93d02007-08-24 21:20:17 +00001848Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1849 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001850 if (Op->getType()->isAnyComplexType()) {
1851 // If it's an l-value, load through the appropriate subobject l-value.
1852 // Note that we have to ask E because Op might be an l-value that
1853 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001854 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001855 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001856
1857 // Otherwise, calculate and project.
1858 return CGF.EmitComplexExpr(Op, false, true).first;
1859 }
1860
Chris Lattner46f93d02007-08-24 21:20:17 +00001861 return Visit(Op);
1862}
John McCallb418d742010-11-16 10:08:07 +00001863
Chris Lattner46f93d02007-08-24 21:20:17 +00001864Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1865 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001866 if (Op->getType()->isAnyComplexType()) {
1867 // If it's an l-value, load through the appropriate subobject l-value.
1868 // Note that we have to ask E because Op might be an l-value that
1869 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001870 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001871 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001872
1873 // Otherwise, calculate and project.
1874 return CGF.EmitComplexExpr(Op, true, false).second;
1875 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001876
Mike Stump7f79f9b2009-05-29 15:46:01 +00001877 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1878 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001879 if (Op->isGLValue())
1880 CGF.EmitLValue(Op);
1881 else
1882 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001883 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001884}
1885
Chris Lattner7f02f722007-08-24 05:35:26 +00001886//===----------------------------------------------------------------------===//
1887// Binary Operators
1888//===----------------------------------------------------------------------===//
1889
1890BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001891 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001892 BinOpInfo Result;
1893 Result.LHS = Visit(E->getLHS());
1894 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001895 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001896 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00001897 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00001898 Result.E = E;
1899 return Result;
1900}
1901
Douglas Gregor6a03e342010-04-23 04:16:32 +00001902LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1903 const CompoundAssignOperator *E,
1904 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001905 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001906 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001907 BinOpInfo OpInfo;
Craig Topperd10e5c22013-07-26 06:16:11 +00001908
Eli Friedman0934e182013-06-12 01:40:06 +00001909 if (E->getComputationResultType()->isAnyComplexType())
1910 return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
Craig Topperd10e5c22013-07-26 06:16:11 +00001911
Mike Stumpcc0442f2009-05-22 19:07:20 +00001912 // Emit the RHS first. __block variables need to have the rhs evaluated
1913 // first, plus this should improve codegen a little.
1914 OpInfo.RHS = Visit(E->getRHS());
1915 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001916 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerddc57332012-10-03 20:58:04 +00001917 OpInfo.FPContractable = false;
Mike Stumpcc0442f2009-05-22 19:07:20 +00001918 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001919 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00001920 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnall7a7ee302012-01-16 17:27:18 +00001921
1922 llvm::PHINode *atomicPHI = 0;
David Chisnall72c1dba2013-03-03 16:02:42 +00001923 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
1924 QualType type = atomicTy->getValueType();
1925 if (!type->isBooleanType() && type->isIntegerType() &&
1926 !(type->isUnsignedIntegerType() &&
1927 CGF.SanOpts->UnsignedIntegerOverflow) &&
1928 CGF.getLangOpts().getSignedOverflowBehavior() !=
1929 LangOptions::SOB_Trapping) {
1930 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
1931 switch (OpInfo.Opcode) {
1932 // We don't have atomicrmw operands for *, %, /, <<, >>
1933 case BO_MulAssign: case BO_DivAssign:
1934 case BO_RemAssign:
1935 case BO_ShlAssign:
1936 case BO_ShrAssign:
1937 break;
1938 case BO_AddAssign:
1939 aop = llvm::AtomicRMWInst::Add;
1940 break;
1941 case BO_SubAssign:
1942 aop = llvm::AtomicRMWInst::Sub;
1943 break;
1944 case BO_AndAssign:
1945 aop = llvm::AtomicRMWInst::And;
1946 break;
1947 case BO_XorAssign:
1948 aop = llvm::AtomicRMWInst::Xor;
1949 break;
1950 case BO_OrAssign:
1951 aop = llvm::AtomicRMWInst::Or;
1952 break;
1953 default:
1954 llvm_unreachable("Invalid compound assignment type");
1955 }
1956 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
1957 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
1958 E->getRHS()->getType(), LHSTy), LHSTy);
1959 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
1960 llvm::SequentiallyConsistent);
1961 return LHSLV;
1962 }
1963 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001964 // FIXME: For floating point types, we should be saving and restoring the
1965 // floating point environment in the loop.
1966 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1967 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnall72c1dba2013-03-03 16:02:42 +00001968 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1969 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnall7a7ee302012-01-16 17:27:18 +00001970 Builder.CreateBr(opBB);
1971 Builder.SetInsertPoint(opBB);
1972 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1973 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001974 OpInfo.LHS = atomicPHI;
1975 }
David Chisnall72c1dba2013-03-03 16:02:42 +00001976 else
1977 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
Eli Friedman860a3192012-06-16 02:19:17 +00001978
1979 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1980 E->getComputationLHSType());
1981
Chris Lattner1f1ded92007-08-24 21:00:35 +00001982 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001983 Result = (this->*Func)(OpInfo);
Craig Topperd10e5c22013-07-26 06:16:11 +00001984
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001985 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001986 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001987
1988 if (atomicPHI) {
1989 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1990 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1991 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
David Chisnall72c1dba2013-03-03 16:02:42 +00001992 CGF.EmitToMemory(Result, LHSTy), llvm::SequentiallyConsistent);
David Chisnall7a7ee302012-01-16 17:27:18 +00001993 atomicPHI->addIncoming(old, opBB);
1994 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1995 Builder.CreateCondBr(success, contBB, opBB);
1996 Builder.SetInsertPoint(contBB);
1997 return LHSLV;
1998 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001999
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002000 // Store the result value into the LHS lvalue. Bit-fields are handled
2001 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2002 // 'An assignment expression has the value of the left operand after the
2003 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002004 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002005 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002006 else
John McCall545d9962011-06-25 02:11:03 +00002007 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002008
Douglas Gregor6a03e342010-04-23 04:16:32 +00002009 return LHSLV;
2010}
2011
2012Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2013 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2014 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002015 Value *RHS;
2016 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2017
2018 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002019 if (Ignore)
2020 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002021
John McCallb418d742010-11-16 10:08:07 +00002022 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002023 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002024 return RHS;
2025
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002026 // If the lvalue is non-volatile, return the computed value of the assignment.
2027 if (!LHS.isVolatileQualified())
2028 return RHS;
2029
2030 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002031 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00002032}
2033
Chris Lattner80230302010-09-11 21:47:09 +00002034void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00002035 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Richard Smithc54e25f2012-11-06 02:30:30 +00002036 llvm::Value *Cond = 0;
Chris Lattner80230302010-09-11 21:47:09 +00002037
Will Dietz4f45bc02013-01-18 11:30:38 +00002038 if (CGF.SanOpts->IntegerDivideByZero)
Richard Smithc54e25f2012-11-06 02:30:30 +00002039 Cond = Builder.CreateICmpNE(Ops.RHS, Zero);
2040
Will Dietz4f45bc02013-01-18 11:30:38 +00002041 if (CGF.SanOpts->SignedIntegerOverflow &&
Richard Smithc54e25f2012-11-06 02:30:30 +00002042 Ops.Ty->hasSignedIntegerRepresentation()) {
2043 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2044
Chris Lattner80230302010-09-11 21:47:09 +00002045 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00002046 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00002047 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2048
Richard Smith7ac9ef12012-09-08 02:08:36 +00002049 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2050 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Richard Smithc54e25f2012-11-06 02:30:30 +00002051 llvm::Value *Overflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2052 Cond = Cond ? Builder.CreateAnd(Cond, Overflow, "and") : Overflow;
Chris Lattner80230302010-09-11 21:47:09 +00002053 }
Richard Smithc54e25f2012-11-06 02:30:30 +00002054
2055 if (Cond)
2056 EmitBinOpCheck(Cond, Ops);
Chris Lattner80230302010-09-11 21:47:09 +00002057}
Chris Lattner1f1ded92007-08-24 21:00:35 +00002058
Chris Lattner7f02f722007-08-24 05:35:26 +00002059Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Will Dietz4f45bc02013-01-18 11:30:38 +00002060 if ((CGF.SanOpts->IntegerDivideByZero ||
2061 CGF.SanOpts->SignedIntegerOverflow) &&
Will Dietzb8540362012-11-27 15:01:55 +00002062 Ops.Ty->isIntegerType()) {
Chris Lattner80230302010-09-11 21:47:09 +00002063 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Will Dietzb8540362012-11-27 15:01:55 +00002064 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Will Dietz4f45bc02013-01-18 11:30:38 +00002065 } else if (CGF.SanOpts->FloatDivideByZero &&
Will Dietzb8540362012-11-27 15:01:55 +00002066 Ops.Ty->isRealFloatingType()) {
2067 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2068 EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
Chris Lattner80230302010-09-11 21:47:09 +00002069 }
Will Dietzb8540362012-11-27 15:01:55 +00002070
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002071 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2072 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Richard Smith7edf9e32012-11-01 22:30:59 +00002073 if (CGF.getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002074 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2075 llvm::Type *ValTy = Val->getType();
2076 if (ValTy->isFloatTy() ||
2077 (isa<llvm::VectorType>(ValTy) &&
2078 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00002079 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002080 }
2081 return Val;
2082 }
Douglas Gregorf6094622010-07-23 15:58:24 +00002083 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002084 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2085 else
2086 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2087}
2088
2089Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2090 // Rem in C can't be a floating point type: C99 6.5.5p2.
Will Dietz4f45bc02013-01-18 11:30:38 +00002091 if (CGF.SanOpts->IntegerDivideByZero) {
Chris Lattner80230302010-09-11 21:47:09 +00002092 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2093
Will Dietzb8540362012-11-27 15:01:55 +00002094 if (Ops.Ty->isIntegerType())
Chris Lattner80230302010-09-11 21:47:09 +00002095 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2096 }
2097
Eli Friedman52d68742011-04-10 04:44:11 +00002098 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002099 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2100 else
2101 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2102}
2103
Mike Stump2add4732009-04-01 20:28:16 +00002104Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2105 unsigned IID;
2106 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00002107
Will Dietzb8540362012-11-27 15:01:55 +00002108 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner9a207232010-06-26 21:48:21 +00002109 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00002110 case BO_Add:
2111 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002112 OpID = 1;
Will Dietzb8540362012-11-27 15:01:55 +00002113 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2114 llvm::Intrinsic::uadd_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002115 break;
John McCall2de56d12010-08-25 11:45:40 +00002116 case BO_Sub:
2117 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002118 OpID = 2;
Will Dietzb8540362012-11-27 15:01:55 +00002119 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2120 llvm::Intrinsic::usub_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002121 break;
John McCall2de56d12010-08-25 11:45:40 +00002122 case BO_Mul:
2123 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002124 OpID = 3;
Will Dietzb8540362012-11-27 15:01:55 +00002125 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2126 llvm::Intrinsic::umul_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002127 break;
2128 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002129 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00002130 }
Mike Stump035cf892009-04-02 18:15:54 +00002131 OpID <<= 1;
Will Dietzb8540362012-11-27 15:01:55 +00002132 if (isSigned)
2133 OpID |= 1;
Mike Stump035cf892009-04-02 18:15:54 +00002134
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002135 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00002136
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002137 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00002138
2139 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2140 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2141 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2142
Richard Smith7ac9ef12012-09-08 02:08:36 +00002143 // Handle overflow with llvm.trap if no custom handler has been specified.
2144 const std::string *handlerName =
Richard Smith7edf9e32012-11-01 22:30:59 +00002145 &CGF.getLangOpts().OverflowHandler;
Richard Smith7ac9ef12012-09-08 02:08:36 +00002146 if (handlerName->empty()) {
Richard Smithd6396a62012-11-05 22:21:05 +00002147 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithcc305612012-11-01 22:15:34 +00002148 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Will Dietz4f45bc02013-01-18 11:30:38 +00002149 if (!isSigned || CGF.SanOpts->SignedIntegerOverflow)
Richard Smithcc305612012-11-01 22:15:34 +00002150 EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
2151 else
Chad Rosier78d85b12013-01-29 23:31:22 +00002152 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith7ac9ef12012-09-08 02:08:36 +00002153 return result;
2154 }
2155
Mike Stump2add4732009-04-01 20:28:16 +00002156 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00002157 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00002158 llvm::Function::iterator insertPt = initialBB;
2159 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2160 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00002161 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00002162
2163 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2164
David Chisnall7f18e672010-09-17 18:29:54 +00002165 // If an overflow handler is set, then we want to call it and then use its
2166 // result, if it returns.
2167 Builder.SetInsertPoint(overflowBB);
2168
2169 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00002170 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002171 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00002172 llvm::FunctionType *handlerTy =
2173 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2174 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2175
2176 // Sign extend the args to 64-bit, so that we can use the same handler for
2177 // all types of overflow.
2178 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2179 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2180
2181 // Call the handler with the two arguments, the operation, and the size of
2182 // the result.
John McCallbd7370a2013-02-28 19:01:20 +00002183 llvm::Value *handlerArgs[] = {
2184 lhs,
2185 rhs,
2186 Builder.getInt8(OpID),
2187 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2188 };
2189 llvm::Value *handlerResult =
2190 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnall7f18e672010-09-17 18:29:54 +00002191
2192 // Truncate the result back to the desired size.
2193 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2194 Builder.CreateBr(continueBB);
2195
Mike Stump2add4732009-04-01 20:28:16 +00002196 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002197 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00002198 phi->addIncoming(result, initialBB);
2199 phi->addIncoming(handlerResult, overflowBB);
2200
2201 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00002202}
Chris Lattner7f02f722007-08-24 05:35:26 +00002203
John McCall913dab22011-06-25 01:32:37 +00002204/// Emit pointer + index arithmetic.
2205static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2206 const BinOpInfo &op,
2207 bool isSubtraction) {
2208 // Must have binary (not unary) expr here. Unary pointer
2209 // increment/decrement doesn't use this path.
2210 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Topperd10e5c22013-07-26 06:16:11 +00002211
John McCall913dab22011-06-25 01:32:37 +00002212 Value *pointer = op.LHS;
2213 Expr *pointerOperand = expr->getLHS();
2214 Value *index = op.RHS;
2215 Expr *indexOperand = expr->getRHS();
2216
2217 // In a subtraction, the LHS is always the pointer.
2218 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2219 std::swap(pointer, index);
2220 std::swap(pointerOperand, indexOperand);
2221 }
2222
2223 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2224 if (width != CGF.PointerWidthInBits) {
2225 // Zero-extend or sign-extend the pointer value according to
2226 // whether the index is signed or not.
2227 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2228 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2229 "idx.ext");
2230 }
2231
2232 // If this is subtraction, negate the index.
2233 if (isSubtraction)
2234 index = CGF.Builder.CreateNeg(index, "idx.neg");
2235
Richard Smitha0a628f2013-02-23 02:53:19 +00002236 if (CGF.SanOpts->Bounds)
2237 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2238 /*Accessed*/ false);
2239
John McCall913dab22011-06-25 01:32:37 +00002240 const PointerType *pointerType
2241 = pointerOperand->getType()->getAs<PointerType>();
2242 if (!pointerType) {
2243 QualType objectType = pointerOperand->getType()
2244 ->castAs<ObjCObjectPointerType>()
2245 ->getPointeeType();
2246 llvm::Value *objectSize
2247 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2248
2249 index = CGF.Builder.CreateMul(index, objectSize);
2250
2251 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2252 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2253 return CGF.Builder.CreateBitCast(result, pointer->getType());
2254 }
2255
2256 QualType elementType = pointerType->getPointeeType();
2257 if (const VariableArrayType *vla
2258 = CGF.getContext().getAsVariableArrayType(elementType)) {
2259 // The element count here is the total number of non-VLA elements.
2260 llvm::Value *numElements = CGF.getVLASize(vla).first;
2261
2262 // Effectively, the multiply by the VLA size is part of the GEP.
2263 // GEP indexes are signed, and scaling an index isn't permitted to
2264 // signed-overflow, so we use the same semantics for our explicit
2265 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00002266 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00002267 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2268 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2269 } else {
2270 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2271 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00002272 }
John McCall913dab22011-06-25 01:32:37 +00002273 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002274 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00002275
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002276 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2277 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2278 // future proof.
John McCall913dab22011-06-25 01:32:37 +00002279 if (elementType->isVoidType() || elementType->isFunctionType()) {
2280 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2281 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2282 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002283 }
2284
David Blaikie4e4d0842012-03-11 07:00:24 +00002285 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00002286 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2287
2288 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00002289}
2290
Lang Hamesbe9af122012-10-02 04:45:10 +00002291// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2292// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2293// the add operand respectively. This allows fmuladd to represent a*b-c, or
2294// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2295// efficient operations.
2296static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2297 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2298 bool negMul, bool negAdd) {
2299 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Topperd10e5c22013-07-26 06:16:11 +00002300
Lang Hamesbe9af122012-10-02 04:45:10 +00002301 Value *MulOp0 = MulOp->getOperand(0);
2302 Value *MulOp1 = MulOp->getOperand(1);
2303 if (negMul) {
2304 MulOp0 =
2305 Builder.CreateFSub(
2306 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2307 "neg");
2308 } else if (negAdd) {
2309 Addend =
2310 Builder.CreateFSub(
2311 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2312 "neg");
2313 }
2314
2315 Value *FMulAdd =
2316 Builder.CreateCall3(
2317 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2318 MulOp0, MulOp1, Addend);
2319 MulOp->eraseFromParent();
2320
2321 return FMulAdd;
2322}
2323
2324// Check whether it would be legal to emit an fmuladd intrinsic call to
2325// represent op and if so, build the fmuladd.
2326//
2327// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2328// Does NOT check the type of the operation - it's assumed that this function
2329// will be called from contexts where it's known that the type is contractable.
Craig Topperd10e5c22013-07-26 06:16:11 +00002330static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hamesbe9af122012-10-02 04:45:10 +00002331 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2332 bool isSub=false) {
2333
2334 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2335 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2336 "Only fadd/fsub can be the root of an fmuladd.");
2337
2338 // Check whether this op is marked as fusable.
2339 if (!op.FPContractable)
2340 return 0;
2341
2342 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2343 // either disabled, or handled entirely by the LLVM backend).
Lang Hames931c0832012-11-15 07:51:26 +00002344 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Lang Hamesbe9af122012-10-02 04:45:10 +00002345 return 0;
2346
2347 // We have a potentially fusable op. Look for a mul on one of the operands.
2348 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2349 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002350 assert(LHSBinOp->getNumUses() == 0 &&
2351 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002352 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2353 }
2354 } else if (llvm::BinaryOperator* RHSBinOp =
2355 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2356 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002357 assert(RHSBinOp->getNumUses() == 0 &&
2358 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002359 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2360 }
2361 }
2362
2363 return 0;
2364}
2365
John McCall913dab22011-06-25 01:32:37 +00002366Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2367 if (op.LHS->getType()->isPointerTy() ||
2368 op.RHS->getType()->isPointerTy())
2369 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2370
2371 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002372 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002373 case LangOptions::SOB_Defined:
2374 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002375 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +00002376 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +00002377 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2378 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002379 case LangOptions::SOB_Trapping:
2380 return EmitOverflowCheckedBinOp(op);
2381 }
2382 }
Will Dietzb8540362012-11-27 15:01:55 +00002383
Will Dietz4f45bc02013-01-18 11:30:38 +00002384 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
Will Dietzb8540362012-11-27 15:01:55 +00002385 return EmitOverflowCheckedBinOp(op);
2386
Lang Hamesbe9af122012-10-02 04:45:10 +00002387 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2388 // Try to form an fmuladd.
2389 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2390 return FMulAdd;
2391
John McCall913dab22011-06-25 01:32:37 +00002392 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002393 }
John McCall913dab22011-06-25 01:32:37 +00002394
2395 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2396}
2397
2398Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2399 // The LHS is always a pointer if either side is.
2400 if (!op.LHS->getType()->isPointerTy()) {
2401 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002402 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002403 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002404 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002405 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +00002406 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +00002407 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2408 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002409 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002410 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002411 }
2412 }
Will Dietzb8540362012-11-27 15:01:55 +00002413
Will Dietz4f45bc02013-01-18 11:30:38 +00002414 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
Will Dietzb8540362012-11-27 15:01:55 +00002415 return EmitOverflowCheckedBinOp(op);
2416
Lang Hamesbe9af122012-10-02 04:45:10 +00002417 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2418 // Try to form an fmuladd.
2419 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2420 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002421 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002422 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002423
John McCall913dab22011-06-25 01:32:37 +00002424 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002425 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002426
John McCall913dab22011-06-25 01:32:37 +00002427 // If the RHS is not a pointer, then we have normal pointer
2428 // arithmetic.
2429 if (!op.RHS->getType()->isPointerTy())
2430 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002431
John McCall913dab22011-06-25 01:32:37 +00002432 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002433
John McCall913dab22011-06-25 01:32:37 +00002434 // Do the raw subtraction part.
2435 llvm::Value *LHS
2436 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2437 llvm::Value *RHS
2438 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2439 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002440
John McCall913dab22011-06-25 01:32:37 +00002441 // Okay, figure out the element size.
2442 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2443 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002444
John McCall913dab22011-06-25 01:32:37 +00002445 llvm::Value *divisor = 0;
2446
2447 // For a variable-length array, this is going to be non-constant.
2448 if (const VariableArrayType *vla
2449 = CGF.getContext().getAsVariableArrayType(elementType)) {
2450 llvm::Value *numElements;
2451 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2452
2453 divisor = numElements;
2454
2455 // Scale the number of non-VLA elements by the non-VLA element size.
2456 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2457 if (!eltSize.isOne())
2458 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2459
2460 // For everything elese, we can just compute it, safe in the
2461 // assumption that Sema won't let anything through that we can't
2462 // safely compute the size of.
2463 } else {
2464 CharUnits elementSize;
2465 // Handle GCC extension for pointer arithmetic on void* and
2466 // function pointer types.
2467 if (elementType->isVoidType() || elementType->isFunctionType())
2468 elementSize = CharUnits::One();
2469 else
2470 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2471
2472 // Don't even emit the divide for element size of 1.
2473 if (elementSize.isOne())
2474 return diffInChars;
2475
2476 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002477 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002478
Chris Lattner2cb42222011-03-01 00:03:48 +00002479 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2480 // pointer difference in C is only defined in the case where both operands
2481 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002482 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002483}
2484
David Tweed7a834212013-01-07 16:43:27 +00002485Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweedf20318f2013-01-10 09:11:33 +00002486 llvm::IntegerType *Ty;
2487 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2488 Ty = cast<llvm::IntegerType>(VT->getElementType());
2489 else
2490 Ty = cast<llvm::IntegerType>(LHS->getType());
2491 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed7a834212013-01-07 16:43:27 +00002492}
2493
Chris Lattner7f02f722007-08-24 05:35:26 +00002494Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2495 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2496 // RHS to the same size as the LHS.
2497 Value *RHS = Ops.RHS;
2498 if (Ops.LHS->getType() != RHS->getType())
2499 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002500
Will Dietz4f45bc02013-01-18 11:30:38 +00002501 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2502 isa<llvm::IntegerType>(Ops.LHS->getType())) {
David Tweed7a834212013-01-07 16:43:27 +00002503 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
Will Dietzbb60fc62013-02-25 22:37:49 +00002504 llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
Richard Smith9d3e2262012-08-25 00:32:28 +00002505
2506 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Will Dietzbb60fc62013-02-25 22:37:49 +00002507 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2508 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2509 llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2510 Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2511
Richard Smith9d3e2262012-08-25 00:32:28 +00002512 // Check whether we are shifting any non-zero bits off the top of the
2513 // integer.
Will Dietzbb60fc62013-02-25 22:37:49 +00002514 CGF.EmitBlock(CheckBitsShifted);
Richard Smith9d3e2262012-08-25 00:32:28 +00002515 llvm::Value *BitsShiftedOff =
2516 Builder.CreateLShr(Ops.LHS,
2517 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2518 /*NUW*/true, /*NSW*/true),
2519 "shl.check");
2520 if (CGF.getLangOpts().CPlusPlus) {
2521 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2522 // Under C++11's rules, shifting a 1 bit into the sign bit is
2523 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2524 // define signed left shifts, so we use the C99 and C++11 rules there).
2525 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2526 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2527 }
2528 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Will Dietzbb60fc62013-02-25 22:37:49 +00002529 llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2530 CGF.EmitBlock(Cont);
2531 llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2532 P->addIncoming(Valid, Orig);
2533 P->addIncoming(SecondCheck, CheckBitsShifted);
2534 Valid = P;
Richard Smith9d3e2262012-08-25 00:32:28 +00002535 }
Will Dietzbb60fc62013-02-25 22:37:49 +00002536
2537 EmitBinOpCheck(Valid, Ops);
Mike Stumpbe07f602009-12-14 21:58:14 +00002538 }
David Tweed7a834212013-01-07 16:43:27 +00002539 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2540 if (CGF.getLangOpts().OpenCL)
2541 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002542
Chris Lattner7f02f722007-08-24 05:35:26 +00002543 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2544}
2545
2546Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2547 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2548 // RHS to the same size as the LHS.
2549 Value *RHS = Ops.RHS;
2550 if (Ops.LHS->getType() != RHS->getType())
2551 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002552
Will Dietz4f45bc02013-01-18 11:30:38 +00002553 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2554 isa<llvm::IntegerType>(Ops.LHS->getType()))
David Tweed7a834212013-01-07 16:43:27 +00002555 EmitBinOpCheck(Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)), Ops);
2556
2557 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2558 if (CGF.getLangOpts().OpenCL)
2559 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002560
Douglas Gregorf6094622010-07-23 15:58:24 +00002561 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002562 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2563 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2564}
2565
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002566enum IntrinsicType { VCMPEQ, VCMPGT };
2567// return corresponding comparison intrinsic for given vector type
2568static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2569 BuiltinType::Kind ElemKind) {
2570 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002571 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002572 case BuiltinType::Char_U:
2573 case BuiltinType::UChar:
2574 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2575 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002576 case BuiltinType::Char_S:
2577 case BuiltinType::SChar:
2578 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2579 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002580 case BuiltinType::UShort:
2581 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2582 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002583 case BuiltinType::Short:
2584 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2585 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002586 case BuiltinType::UInt:
2587 case BuiltinType::ULong:
2588 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2589 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002590 case BuiltinType::Int:
2591 case BuiltinType::Long:
2592 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2593 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002594 case BuiltinType::Float:
2595 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2596 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002597 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002598}
2599
Chris Lattner7f02f722007-08-24 05:35:26 +00002600Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2601 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002602 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002603 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002604 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002605 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002606 assert(E->getOpcode() == BO_EQ ||
2607 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002608 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2609 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002610 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002611 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002612 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002613 Value *LHS = Visit(E->getLHS());
2614 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002615
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002616 // If AltiVec, the comparison results in a numeric type, so we use
2617 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002618 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002619 // constants for mapping CR6 register bits to predicate result
2620 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2621
2622 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2623
2624 // in several cases vector arguments order will be reversed
2625 Value *FirstVecArg = LHS,
2626 *SecondVecArg = RHS;
2627
2628 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002629 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002630 BuiltinType::Kind ElementKind = BTy->getKind();
2631
2632 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002633 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002634 case BO_EQ:
2635 CR6 = CR6_LT;
2636 ID = GetIntrinsic(VCMPEQ, ElementKind);
2637 break;
2638 case BO_NE:
2639 CR6 = CR6_EQ;
2640 ID = GetIntrinsic(VCMPEQ, ElementKind);
2641 break;
2642 case BO_LT:
2643 CR6 = CR6_LT;
2644 ID = GetIntrinsic(VCMPGT, ElementKind);
2645 std::swap(FirstVecArg, SecondVecArg);
2646 break;
2647 case BO_GT:
2648 CR6 = CR6_LT;
2649 ID = GetIntrinsic(VCMPGT, ElementKind);
2650 break;
2651 case BO_LE:
2652 if (ElementKind == BuiltinType::Float) {
2653 CR6 = CR6_LT;
2654 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2655 std::swap(FirstVecArg, SecondVecArg);
2656 }
2657 else {
2658 CR6 = CR6_EQ;
2659 ID = GetIntrinsic(VCMPGT, ElementKind);
2660 }
2661 break;
2662 case BO_GE:
2663 if (ElementKind == BuiltinType::Float) {
2664 CR6 = CR6_LT;
2665 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2666 }
2667 else {
2668 CR6 = CR6_EQ;
2669 ID = GetIntrinsic(VCMPGT, ElementKind);
2670 std::swap(FirstVecArg, SecondVecArg);
2671 }
2672 break;
2673 }
2674
Chris Lattner48431f92011-04-19 22:55:03 +00002675 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002676 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2677 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2678 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2679 }
2680
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002681 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002682 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002683 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002684 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002685 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002686 LHS, RHS, "cmp");
2687 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002688 // Unsigned integers and pointers.
2689 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002690 LHS, RHS, "cmp");
2691 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002692
2693 // If this is a vector comparison, sign extend the result to the appropriate
2694 // vector integer type and return it (don't convert to bool).
2695 if (LHSTy->isVectorType())
2696 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002697
Chris Lattner7f02f722007-08-24 05:35:26 +00002698 } else {
2699 // Complex Comparison: can only be an equality comparison.
2700 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2701 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002702
John McCall183700f2009-09-21 23:43:11 +00002703 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002704
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002705 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002706 if (CETy->isRealFloatingType()) {
2707 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2708 LHS.first, RHS.first, "cmp.r");
2709 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2710 LHS.second, RHS.second, "cmp.i");
2711 } else {
2712 // Complex comparisons can only be equality comparisons. As such, signed
2713 // and unsigned opcodes are the same.
2714 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2715 LHS.first, RHS.first, "cmp.r");
2716 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2717 LHS.second, RHS.second, "cmp.i");
2718 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002719
John McCall2de56d12010-08-25 11:45:40 +00002720 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002721 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2722 } else {
John McCall2de56d12010-08-25 11:45:40 +00002723 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002724 "Complex comparison other than == or != ?");
2725 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2726 }
2727 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002728
2729 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002730}
2731
2732Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002733 bool Ignore = TestAndClearIgnoreResultAssign();
2734
John McCallf85e1932011-06-15 23:02:42 +00002735 Value *RHS;
2736 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002737
John McCallf85e1932011-06-15 23:02:42 +00002738 switch (E->getLHS()->getType().getObjCLifetime()) {
2739 case Qualifiers::OCL_Strong:
2740 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2741 break;
2742
2743 case Qualifiers::OCL_Autoreleasing:
2744 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2745 break;
2746
2747 case Qualifiers::OCL_Weak:
2748 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002749 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002750 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2751 break;
2752
2753 // No reason to do any of these differently.
2754 case Qualifiers::OCL_None:
2755 case Qualifiers::OCL_ExplicitNone:
2756 // __block variables need to have the rhs evaluated first, plus
2757 // this should improve codegen just a little.
2758 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002759 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002760
2761 // Store the value into the LHS. Bit-fields are handled specially
2762 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2763 // 'An assignment expression has the value of the left operand after
2764 // the assignment...'.
2765 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002766 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002767 else
John McCall545d9962011-06-25 02:11:03 +00002768 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002769 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002770
2771 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002772 if (Ignore)
2773 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002774
John McCallb418d742010-11-16 10:08:07 +00002775 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002776 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002777 return RHS;
2778
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002779 // If the lvalue is non-volatile, return the computed value of the assignment.
2780 if (!LHS.isVolatileQualified())
2781 return RHS;
2782
2783 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002784 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002785}
2786
2787Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002788 // Perform vector logical and on comparisons with zero vectors.
2789 if (E->getType()->isVectorType()) {
2790 Value *LHS = Visit(E->getLHS());
2791 Value *RHS = Visit(E->getRHS());
2792 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00002793 if (LHS->getType()->isFPOrFPVectorTy()) {
2794 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2795 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2796 } else {
2797 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2798 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2799 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00002800 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly52e933b2013-02-21 11:49:56 +00002801 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner4f692c22012-01-16 21:02:28 +00002802 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002803
Chris Lattner2acc6e32011-07-18 04:24:23 +00002804 llvm::Type *ResTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00002805
Chris Lattner20eb09d2008-11-12 08:26:50 +00002806 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2807 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002808 bool LHSCondVal;
2809 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2810 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002811 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002812 // ZExt result to int or bool.
2813 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002814 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002815
Chris Lattner7804bcb2009-10-17 04:24:20 +00002816 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002817 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002818 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002819 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002820
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002821 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2822 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002823
John McCall150b4622011-01-26 04:00:11 +00002824 CodeGenFunction::ConditionalEvaluation eval(CGF);
2825
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002826 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2827 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2828
2829 // Any edges into the ContBlock are now from an (indeterminate number of)
2830 // edges from this first condition. All of these values will be false. Start
2831 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002832 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002833 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002834 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2835 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002836 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002837
John McCall150b4622011-01-26 04:00:11 +00002838 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002839 CGF.EmitBlock(RHSBlock);
2840 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002841 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002842
Chris Lattner7f02f722007-08-24 05:35:26 +00002843 // Reaquire the RHS block, as there may be subblocks inserted.
2844 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002845
2846 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2847 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002848 if (CGF.getDebugInfo())
2849 // There is no need to emit line number for unconditional branch.
2850 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002851 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002852 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002853
Chris Lattner7f02f722007-08-24 05:35:26 +00002854 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002855 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002856}
2857
2858Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002859 // Perform vector logical or on comparisons with zero vectors.
2860 if (E->getType()->isVectorType()) {
2861 Value *LHS = Visit(E->getLHS());
2862 Value *RHS = Visit(E->getRHS());
2863 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00002864 if (LHS->getType()->isFPOrFPVectorTy()) {
2865 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2866 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2867 } else {
2868 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2869 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2870 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00002871 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly52e933b2013-02-21 11:49:56 +00002872 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner4f692c22012-01-16 21:02:28 +00002873 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002874
Chris Lattner2acc6e32011-07-18 04:24:23 +00002875 llvm::Type *ResTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00002876
Chris Lattner20eb09d2008-11-12 08:26:50 +00002877 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2878 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002879 bool LHSCondVal;
2880 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2881 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002882 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002883 // ZExt result to int or bool.
2884 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002885 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002886
Chris Lattner7804bcb2009-10-17 04:24:20 +00002887 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002888 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002889 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002890 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002891
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002892 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2893 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002894
John McCall150b4622011-01-26 04:00:11 +00002895 CodeGenFunction::ConditionalEvaluation eval(CGF);
2896
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002897 // Branch on the LHS first. If it is true, go to the success (cont) block.
2898 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2899
2900 // Any edges into the ContBlock are now from an (indeterminate number of)
2901 // edges from this first condition. All of these values will be true. Start
2902 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002903 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002904 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002905 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2906 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002907 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002908
John McCall150b4622011-01-26 04:00:11 +00002909 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002910
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002911 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002912 CGF.EmitBlock(RHSBlock);
2913 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002914
John McCall150b4622011-01-26 04:00:11 +00002915 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002916
Chris Lattner7f02f722007-08-24 05:35:26 +00002917 // Reaquire the RHS block, as there may be subblocks inserted.
2918 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002919
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002920 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2921 // into the phi node for the edge with the value of RHSCond.
2922 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002923 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002924
Chris Lattner7f02f722007-08-24 05:35:26 +00002925 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002926 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002927}
2928
2929Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002930 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002931 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002932 return Visit(E->getRHS());
2933}
2934
2935//===----------------------------------------------------------------------===//
2936// Other Operators
2937//===----------------------------------------------------------------------===//
2938
Chris Lattner9802a512008-11-12 08:55:54 +00002939/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2940/// expression is cheap enough and side-effect-free enough to evaluate
2941/// unconditionally instead of conditionally. This is used to convert control
2942/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002943static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2944 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002945 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002946
Chris Lattnerc6bea672011-04-16 23:15:35 +00002947 // Anything that is an integer or floating point constant is fine.
Eli Friedman21cde052013-07-16 22:40:53 +00002948 if (E->isEvaluatable(CGF.getContext()))
Chris Lattner9802a512008-11-12 08:55:54 +00002949 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002950
Chris Lattner9802a512008-11-12 08:55:54 +00002951 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2952 // X and Y are local variables.
2953 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2954 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002955 if (VD->hasLocalStorage() && !(CGF.getContext()
2956 .getCanonicalType(VD->getType())
2957 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002958 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002959
Chris Lattner9802a512008-11-12 08:55:54 +00002960 return false;
2961}
2962
2963
Chris Lattner7f02f722007-08-24 05:35:26 +00002964Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002965VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002966 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002967
2968 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002969 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002970
2971 Expr *condExpr = E->getCond();
2972 Expr *lhsExpr = E->getTrueExpr();
2973 Expr *rhsExpr = E->getFalseExpr();
2974
Chris Lattner31a09842008-11-12 08:04:58 +00002975 // If the condition constant folds and can be elided, try to avoid emitting
2976 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002977 bool CondExprBool;
2978 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002979 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002980 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002981
Eli Friedmanc8645e32011-10-15 02:10:40 +00002982 // If the dead side doesn't have labels we need, just emit the Live part.
2983 if (!CGF.ContainsLabel(dead)) {
2984 Value *Result = Visit(live);
2985
2986 // If the live part is a throw expression, it acts like it has a void
2987 // type, so evaluating it returns a null Value*. However, a conditional
2988 // with non-void type must return a non-null Value*.
2989 if (!Result && !E->getType()->isVoidType())
2990 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2991
2992 return Result;
2993 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002994 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002995
Nate Begeman6155d732010-09-20 22:41:17 +00002996 // OpenCL: If the condition is a vector, we can treat this condition like
2997 // the select function.
Craig Topperd10e5c22013-07-26 06:16:11 +00002998 if (CGF.getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002999 && condExpr->getType()->isVectorType()) {
3000 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3001 llvm::Value *LHS = Visit(lhsExpr);
3002 llvm::Value *RHS = Visit(rhsExpr);
Craig Topperd10e5c22013-07-26 06:16:11 +00003003
Chris Lattner2acc6e32011-07-18 04:24:23 +00003004 llvm::Type *condType = ConvertType(condExpr->getType());
3005 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Topperd10e5c22013-07-26 06:16:11 +00003006
3007 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00003008 llvm::Type *elemType = vecTy->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003009
Chris Lattner2ce88422012-01-25 05:34:41 +00003010 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00003011 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Topperd10e5c22013-07-26 06:16:11 +00003012 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begeman6155d732010-09-20 22:41:17 +00003013 llvm::VectorType::get(elemType,
Craig Topperd10e5c22013-07-26 06:16:11 +00003014 numElem),
Nate Begeman6155d732010-09-20 22:41:17 +00003015 "sext");
3016 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Topperd10e5c22013-07-26 06:16:11 +00003017
Nate Begeman6155d732010-09-20 22:41:17 +00003018 // Cast float to int to perform ANDs if necessary.
3019 llvm::Value *RHSTmp = RHS;
3020 llvm::Value *LHSTmp = LHS;
3021 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00003022 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00003023 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00003024 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3025 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3026 wasCast = true;
3027 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003028
Nate Begeman6155d732010-09-20 22:41:17 +00003029 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3030 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3031 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3032 if (wasCast)
3033 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3034
3035 return tmp5;
3036 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003037
Chris Lattner9802a512008-11-12 08:55:54 +00003038 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3039 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00003040 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00003041 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3042 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
3043 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3044 llvm::Value *LHS = Visit(lhsExpr);
3045 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00003046 if (!LHS) {
3047 // If the conditional has void type, make sure we return a null Value*.
3048 assert(!RHS && "LHS and RHS types must match");
3049 return 0;
3050 }
Chris Lattner9802a512008-11-12 08:55:54 +00003051 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3052 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003053
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00003054 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3055 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003056 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00003057
3058 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003059 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00003060
Chris Lattner7f02f722007-08-24 05:35:26 +00003061 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00003062 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003063 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00003064 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003065
Chris Lattner7f02f722007-08-24 05:35:26 +00003066 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00003067 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003068
Chris Lattner7f02f722007-08-24 05:35:26 +00003069 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00003070 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003071 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00003072 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003073
John McCall150b4622011-01-26 04:00:11 +00003074 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00003075 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003076
Eli Friedman48daf592009-12-07 20:25:53 +00003077 // If the LHS or RHS is a throw expression, it will be legitimately null.
3078 if (!LHS)
3079 return RHS;
3080 if (!RHS)
3081 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003082
Chris Lattner7f02f722007-08-24 05:35:26 +00003083 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003084 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00003085 PN->addIncoming(LHS, LHSBlock);
3086 PN->addIncoming(RHS, RHSBlock);
3087 return PN;
3088}
3089
3090Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmana5e66012013-07-20 00:40:58 +00003091 return Visit(E->getChosenSubExpr());
Chris Lattner7f02f722007-08-24 05:35:26 +00003092}
3093
Chris Lattner2202bce2007-11-30 17:56:23 +00003094Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00003095 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003096 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
3097
3098 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003099 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003100 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
3101
Mike Stump7f79f9b2009-05-29 15:46:01 +00003102 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003103 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003104}
3105
John McCall6b5a61b2011-02-07 10:33:21 +00003106Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3107 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00003108}
3109
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003110Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3111 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00003112 llvm::Type *DstTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003113
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003114 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3115 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003116 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003117 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3118 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3119 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
Craig Topperd10e5c22013-07-26 06:16:11 +00003120 if ((numElementsDst == 3 && numElementsSrc == 4)
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003121 || (numElementsDst == 4 && numElementsSrc == 3)) {
Craig Topperd10e5c22013-07-26 06:16:11 +00003122
3123
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003124 // In the case of going from int4->float3, a bitcast is needed before
3125 // doing a shuffle.
Craig Topperd10e5c22013-07-26 06:16:11 +00003126 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003127 cast<llvm::VectorType>(SrcTy)->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003128 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003129 cast<llvm::VectorType>(DstTy)->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003130
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003131 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3132 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3133 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003134 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003135 numElementsSrc);
Craig Topperd10e5c22013-07-26 06:16:11 +00003136
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003137 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3138 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003139
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003140 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003141
Chris Lattner5f9e2722011-07-23 10:55:15 +00003142 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003143 Args.push_back(Builder.getInt32(0));
3144 Args.push_back(Builder.getInt32(1));
3145 Args.push_back(Builder.getInt32(2));
Craig Topperd10e5c22013-07-26 06:16:11 +00003146
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003147 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00003148 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Craig Topperd10e5c22013-07-26 06:16:11 +00003149
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003150 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Craig Topperd10e5c22013-07-26 06:16:11 +00003151
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003152 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3153 }
3154 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003155
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003156 return Builder.CreateBitCast(Src, DstTy, "astype");
3157}
3158
Eli Friedman276b0612011-10-11 02:20:01 +00003159Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3160 return CGF.EmitAtomicExpr(E).getScalarVal();
3161}
3162
Chris Lattner7f02f722007-08-24 05:35:26 +00003163//===----------------------------------------------------------------------===//
3164// Entry Point into this File
3165//===----------------------------------------------------------------------===//
3166
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003167/// EmitScalarExpr - Emit the computation of the specified expression of scalar
3168/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00003169Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall9d232c82013-03-07 21:37:08 +00003170 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner7f02f722007-08-24 05:35:26 +00003171 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003172
Devang Patel5de7a0e2011-03-07 18:29:53 +00003173 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003174 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003175 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00003176 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00003177 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003178 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003179 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00003180}
Chris Lattner3707b252007-08-26 06:48:56 +00003181
3182/// EmitScalarConversion - Emit a conversion from the specified type to the
3183/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003184Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3185 QualType DstTy) {
John McCall9d232c82013-03-07 21:37:08 +00003186 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3707b252007-08-26 06:48:56 +00003187 "Invalid scalar expression to emit");
3188 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3189}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003190
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003191/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3192/// type to the specified destination type, where the destination type is an
3193/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003194Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3195 QualType SrcTy,
3196 QualType DstTy) {
John McCall9d232c82013-03-07 21:37:08 +00003197 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003198 "Invalid complex -> scalar conversion");
3199 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3200 DstTy);
3201}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00003202
Chris Lattner8c11a652010-06-26 22:09:34 +00003203
3204llvm::Value *CodeGenFunction::
3205EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3206 bool isInc, bool isPre) {
3207 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3208}
3209
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003210LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3211 llvm::Value *V;
3212 // object->isa or (*object).isa
3213 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003214 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00003215 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003216
3217 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00003218 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00003219 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003220 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3221 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003222 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00003223 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003224 } else {
3225 if (E->isArrow())
3226 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3227 else
3228 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003229 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003230
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003231 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003232 ClassPtrTy = ClassPtrTy->getPointerTo();
3233 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00003234 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003235}
3236
Douglas Gregor6a03e342010-04-23 04:16:32 +00003237
John McCall2a416372010-12-05 02:00:02 +00003238LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00003239 const CompoundAssignOperator *E) {
3240 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003241 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00003242 switch (E->getOpcode()) {
3243#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00003244 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00003245 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003246 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00003247 COMPOUND_OP(Mul);
3248 COMPOUND_OP(Div);
3249 COMPOUND_OP(Rem);
3250 COMPOUND_OP(Add);
3251 COMPOUND_OP(Sub);
3252 COMPOUND_OP(Shl);
3253 COMPOUND_OP(Shr);
3254 COMPOUND_OP(And);
3255 COMPOUND_OP(Xor);
3256 COMPOUND_OP(Or);
3257#undef COMPOUND_OP
Craig Topperd10e5c22013-07-26 06:16:11 +00003258
John McCall2de56d12010-08-25 11:45:40 +00003259 case BO_PtrMemD:
3260 case BO_PtrMemI:
3261 case BO_Mul:
3262 case BO_Div:
3263 case BO_Rem:
3264 case BO_Add:
3265 case BO_Sub:
3266 case BO_Shl:
3267 case BO_Shr:
3268 case BO_LT:
3269 case BO_GT:
3270 case BO_LE:
3271 case BO_GE:
3272 case BO_EQ:
3273 case BO_NE:
3274 case BO_And:
3275 case BO_Xor:
3276 case BO_Or:
3277 case BO_LAnd:
3278 case BO_LOr:
3279 case BO_Assign:
3280 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00003281 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00003282 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003283
Douglas Gregor6a03e342010-04-23 04:16:32 +00003284 llvm_unreachable("Unhandled compound assignment operator");
3285}