blob: 14c4ac64f032fd02ebb2c1c6f26b4b6027480ef7 [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner9fba49a2007-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"
15#include "CodeGenModule.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000022#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000023#include "llvm/Intrinsics.h"
Mike Stumpdb789912009-04-01 20:28:16 +000024#include "llvm/Module.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000026#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000028#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000029
Chris Lattner9fba49a2007-08-24 05:35:26 +000030using namespace clang;
31using namespace CodeGen;
32using llvm::Value;
33
34//===----------------------------------------------------------------------===//
35// Scalar Expression Emitter
36//===----------------------------------------------------------------------===//
37
38struct BinOpInfo {
39 Value *LHS;
40 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000041 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000042 const BinaryOperator *E;
43};
44
45namespace {
46class VISIBILITY_HIDDEN ScalarExprEmitter
47 : public StmtVisitor<ScalarExprEmitter, Value*> {
48 CodeGenFunction &CGF;
Daniel Dunbard916e6e2008-11-01 01:53:16 +000049 CGBuilderTy &Builder;
Mike Stumpb8fc73e2009-05-29 15:46:01 +000050 bool IgnoreResultAssign;
Chris Lattner9fba49a2007-08-24 05:35:26 +000051public:
52
Mike Stumpb8fc73e2009-05-29 15:46:01 +000053 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
54 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000055 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000056
57 //===--------------------------------------------------------------------===//
58 // Utilities
59 //===--------------------------------------------------------------------===//
60
Mike Stumpb8fc73e2009-05-29 15:46:01 +000061 bool TestAndClearIgnoreResultAssign() {
Chris Lattner08ac8522009-07-08 01:08:03 +000062 bool I = IgnoreResultAssign;
63 IgnoreResultAssign = false;
64 return I;
65 }
Mike Stumpb8fc73e2009-05-29 15:46:01 +000066
Chris Lattner9fba49a2007-08-24 05:35:26 +000067 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
68 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
69
70 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000071 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000072 }
73
74 /// EmitLoadOfLValue - Given an expression with complex type that represents a
75 /// value l-value, this method emits the address of the l-value, then loads
76 /// and returns the result.
77 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000078 return EmitLoadOfLValue(EmitLValue(E), E->getType());
79 }
80
Chris Lattnerd8d44222007-08-26 16:42:57 +000081 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000082 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000083 Value *EmitConversionToBool(Value *Src, QualType DstTy);
84
Chris Lattner4e05d1e2007-08-26 06:48:56 +000085 /// EmitScalarConversion - Emit a conversion from the specified type to the
86 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000087 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
88
89 /// EmitComplexToScalarConversion - Emit a conversion from the specified
90 /// complex type to the specified destination type, where the destination
91 /// type is an LLVM scalar type.
92 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
93 QualType SrcTy, QualType DstTy);
Mike Stump4eb81dc2009-02-12 18:29:15 +000094
Chris Lattner9fba49a2007-08-24 05:35:26 +000095 //===--------------------------------------------------------------------===//
96 // Visitor Methods
97 //===--------------------------------------------------------------------===//
98
99 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000100 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000101 assert(0 && "Stmt can't have complex result type!");
102 return 0;
103 }
104 Value *VisitExpr(Expr *S);
105 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
106
107 // Leaves.
108 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
109 return llvm::ConstantInt::get(E->getValue());
110 }
111 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000112 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000113 }
114 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
115 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
116 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000117 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
119 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000120 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Anderson5f1adc22009-07-13 04:10:07 +0000121 return CGF.getLLVMContext().getNullValue(ConvertType(E->getType()));
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000122 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000123 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Anderson5f1adc22009-07-13 04:10:07 +0000124 return CGF.getLLVMContext().getNullValue(ConvertType(E->getType()));
Anders Carlsson774f9c72008-12-21 22:39:40 +0000125 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000126 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
127 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000128 CGF.getContext().typesAreCompatible(
129 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000130 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000131 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000132 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000133 llvm::Value *V =
134 llvm::ConstantInt::get(llvm::Type::Int32Ty,
135 CGF.GetIDForAddrOfLabel(E->getLabel()));
136
137 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000138 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000139
140 // l-values.
141 Value *VisitDeclRefExpr(DeclRefExpr *E) {
142 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
143 return llvm::ConstantInt::get(EC->getInitVal());
144 return EmitLoadOfLValue(E);
145 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000146 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
147 return CGF.EmitObjCSelectorExpr(E);
148 }
149 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
150 return CGF.EmitObjCProtocolExpr(E);
151 }
152 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
153 return EmitLoadOfLValue(E);
154 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000155 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000156 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000157 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000158 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
159 return EmitLoadOfLValue(E);
160 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000161 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
162 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000163 }
164
Chris Lattner9fba49a2007-08-24 05:35:26 +0000165 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000166 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000167 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000168 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000169 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
170 return EmitLoadOfLValue(E);
171 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000172 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerc5d32632009-02-24 22:18:39 +0000173 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
174 return EmitLValue(E).getAddress();
175 }
176
Chris Lattner69909292008-08-10 01:53:14 +0000177 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000178
179 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000180 bool Ignore = TestAndClearIgnoreResultAssign();
181 (void)Ignore;
182 assert (Ignore == false && "init list ignored");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000183 unsigned NumInitElements = E->getNumInits();
184
Douglas Gregor9fddded2009-01-29 19:42:23 +0000185 if (E->hadArrayRangeDesignator()) {
186 CGF.ErrorUnsupported(E, "GNU array range designator extension");
187 }
188
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000189 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000190 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
191
192 // We have a scalar in braces. Just use the first element.
193 if (!VType)
194 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000195
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000196 unsigned NumVectorElements = VType->getNumElements();
197 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000198
199 // Emit individual vector element stores.
200 llvm::Value *V = llvm::UndefValue::get(VType);
201
Anders Carlsson323d5682007-12-18 02:45:33 +0000202 // Emit initializers
203 unsigned i;
204 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000205 Value *NewV = Visit(E->getInit(i));
206 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
207 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000208 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000209
210 // Emit remaining default initializers
211 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
212 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Owen Anderson5f1adc22009-07-13 04:10:07 +0000213 llvm::Value *NewV = CGF.getLLVMContext().getNullValue(ElementType);
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000214 V = Builder.CreateInsertElement(V, NewV, Idx);
215 }
216
Devang Patel32c39832007-10-24 18:05:48 +0000217 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000218 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000219
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000220 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Anderson5f1adc22009-07-13 04:10:07 +0000221 return CGF.getLLVMContext().getNullValue(ConvertType(E->getType()));
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000222 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000223 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmana7ef8e52009-04-20 03:54:15 +0000224 Value *VisitCastExpr(const CastExpr *E) {
225 // Make sure to evaluate VLA bounds now so that we have them for later.
226 if (E->getType()->isVariablyModifiedType())
227 CGF.EmitVLASize(E->getType());
228
Chris Lattner9fba49a2007-08-24 05:35:26 +0000229 return EmitCastExpr(E->getSubExpr(), E->getType());
230 }
231 Value *EmitCastExpr(const Expr *E, QualType T);
232
233 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssoncd295282009-05-27 03:37:57 +0000234 if (E->getCallReturnType()->isReferenceType())
235 return EmitLoadOfLValue(E);
236
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000237 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000238 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000239
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000240 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000241
Mike Stump2b6933f2009-02-28 09:07:16 +0000242 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000243
Chris Lattner9fba49a2007-08-24 05:35:26 +0000244 // Unary Operators.
245 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
246 Value *VisitUnaryPostDec(const UnaryOperator *E) {
247 return VisitPrePostIncDec(E, false, false);
248 }
249 Value *VisitUnaryPostInc(const UnaryOperator *E) {
250 return VisitPrePostIncDec(E, true, false);
251 }
252 Value *VisitUnaryPreDec(const UnaryOperator *E) {
253 return VisitPrePostIncDec(E, false, true);
254 }
255 Value *VisitUnaryPreInc(const UnaryOperator *E) {
256 return VisitPrePostIncDec(E, true, true);
257 }
258 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
259 return EmitLValue(E->getSubExpr()).getAddress();
260 }
261 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
262 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000263 // This differs from gcc, though, most likely due to a bug in gcc.
264 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000265 return Visit(E->getSubExpr());
266 }
267 Value *VisitUnaryMinus (const UnaryOperator *E);
268 Value *VisitUnaryNot (const UnaryOperator *E);
269 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000270 Value *VisitUnaryReal (const UnaryOperator *E);
271 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000272 Value *VisitUnaryExtension(const UnaryOperator *E) {
273 return Visit(E->getSubExpr());
274 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000275 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson49d4a572009-04-14 16:58:56 +0000276
277 // C++
Chris Lattner3e254fb2008-04-08 04:40:51 +0000278 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
279 return Visit(DAE->getExpr());
280 }
Anders Carlsson49d4a572009-04-14 16:58:56 +0000281 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
282 return CGF.LoadCXXThis();
283 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000284
Anders Carlsson272b5f52009-05-19 04:48:36 +0000285 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlssond6775602009-05-31 00:09:15 +0000286 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson272b5f52009-05-19 04:48:36 +0000287 }
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000288 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
289 return CGF.EmitCXXNewExpr(E);
290 }
Anders Carlsson272b5f52009-05-19 04:48:36 +0000291
Chris Lattner9fba49a2007-08-24 05:35:26 +0000292 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000293 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000294 if (CGF.getContext().getLangOptions().OverflowChecking
295 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000296 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +0000297 if (Ops.LHS->getType()->isFPOrFPVector())
298 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000299 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
300 }
Mike Stumpdb789912009-04-01 20:28:16 +0000301 /// Create a binary op that checks for overflow.
302 /// Currently only supports +, - and *.
303 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000304 Value *EmitDiv(const BinOpInfo &Ops);
305 Value *EmitRem(const BinOpInfo &Ops);
306 Value *EmitAdd(const BinOpInfo &Ops);
307 Value *EmitSub(const BinOpInfo &Ops);
308 Value *EmitShl(const BinOpInfo &Ops);
309 Value *EmitShr(const BinOpInfo &Ops);
310 Value *EmitAnd(const BinOpInfo &Ops) {
311 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
312 }
313 Value *EmitXor(const BinOpInfo &Ops) {
314 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
315 }
316 Value *EmitOr (const BinOpInfo &Ops) {
317 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
318 }
319
Chris Lattner660e31d2007-08-24 21:00:35 +0000320 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000321 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000322 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
323
324 // Binary operators and binary compound assignment operators.
325#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000326 Value *VisitBin ## OP(const BinaryOperator *E) { \
327 return Emit ## OP(EmitBinOps(E)); \
328 } \
329 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
330 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000331 }
332 HANDLEBINOP(Mul);
333 HANDLEBINOP(Div);
334 HANDLEBINOP(Rem);
335 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000336 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000337 HANDLEBINOP(Shl);
338 HANDLEBINOP(Shr);
339 HANDLEBINOP(And);
340 HANDLEBINOP(Xor);
341 HANDLEBINOP(Or);
342#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000343
Chris Lattner9fba49a2007-08-24 05:35:26 +0000344 // Comparisons.
345 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
346 unsigned SICmpOpc, unsigned FCmpOpc);
347#define VISITCOMP(CODE, UI, SI, FP) \
348 Value *VisitBin##CODE(const BinaryOperator *E) { \
349 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
350 llvm::FCmpInst::FP); }
351 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
352 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
353 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
354 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
355 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
356 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
357#undef VISITCOMP
358
359 Value *VisitBinAssign (const BinaryOperator *E);
360
361 Value *VisitBinLAnd (const BinaryOperator *E);
362 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000363 Value *VisitBinComma (const BinaryOperator *E);
364
365 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000366 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000367 Value *VisitConditionalOperator(const ConditionalOperator *CO);
368 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000369 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000370 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
371 return CGF.EmitObjCStringLiteral(E);
372 }
373};
374} // end anonymous namespace.
375
376//===----------------------------------------------------------------------===//
377// Utilities
378//===----------------------------------------------------------------------===//
379
Chris Lattnerd8d44222007-08-26 16:42:57 +0000380/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000381/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000382Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
383 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
384
385 if (SrcType->isRealFloatingType()) {
386 // Compare against 0.0 for fp scalars.
Owen Anderson5f1adc22009-07-13 04:10:07 +0000387 llvm::Value *Zero = CGF.getLLVMContext().getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000388 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
389 }
390
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000391 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000392 "Unknown scalar type to convert");
393
394 // Because of the type rules of C, we often end up computing a logical value,
395 // then zero extending it to int, then wanting it as a logical value again.
396 // Optimize this common case.
397 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
398 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
399 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000400 // If there aren't any more uses, zap the instruction to save space.
401 // Note that there can be more uses, for example if this
402 // is the result of an assignment.
403 if (ZI->use_empty())
404 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000405 return Result;
406 }
407 }
408
409 // Compare against an integer or pointer null.
Owen Anderson5f1adc22009-07-13 04:10:07 +0000410 llvm::Value *Zero = CGF.getLLVMContext().getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000411 return Builder.CreateICmpNE(Src, Zero, "tobool");
412}
413
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000414/// EmitScalarConversion - Emit a conversion from the specified type to the
415/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000416Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
417 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000418 SrcType = CGF.getContext().getCanonicalType(SrcType);
419 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000420 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000421
422 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000423
424 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000425 if (DstType->isBooleanType())
426 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000427
428 const llvm::Type *DstTy = ConvertType(DstType);
429
430 // Ignore conversions like int -> uint.
431 if (Src->getType() == DstTy)
432 return Src;
433
Daniel Dunbar238335f2008-08-25 09:51:32 +0000434 // Handle pointer conversions next: pointers can only be converted
435 // to/from other pointers and integers. Check for pointer types in
436 // terms of LLVM, as some native types (like Obj-C id) may map to a
437 // pointer type.
438 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000439 // The source value may be an integer, or a pointer.
440 if (isa<llvm::PointerType>(Src->getType()))
441 return Builder.CreateBitCast(Src, DstTy, "conv");
442 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000443 // First, convert to the correct width so that we control the kind of
444 // extension.
445 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
446 bool InputSigned = SrcType->isSignedIntegerType();
447 llvm::Value* IntResult =
448 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
449 // Then, cast to pointer.
450 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000451 }
452
Daniel Dunbar238335f2008-08-25 09:51:32 +0000453 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000454 // Must be an ptr to int cast.
455 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000456 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000457 }
458
Nate Begemanaf6ed502008-04-18 23:10:10 +0000459 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000460 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
461 // Cast the scalar to element type
462 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
463 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
464
465 // Insert the element in element zero of an undef vector
466 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
467 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
468 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
469
470 // Splat the element across to all elements
471 llvm::SmallVector<llvm::Constant*, 16> Args;
472 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
473 for (unsigned i = 0; i < NumElements; i++)
474 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
475
476 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
477 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
478 return Yay;
479 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000480
Chris Lattner4f025a42008-02-02 04:51:41 +0000481 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000482 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000483 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000484 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000485
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000486 // Finally, we have the arithmetic types: real int/float.
487 if (isa<llvm::IntegerType>(Src->getType())) {
488 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000489 if (isa<llvm::IntegerType>(DstTy))
490 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
491 else if (InputSigned)
492 return Builder.CreateSIToFP(Src, DstTy, "conv");
493 else
494 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000495 }
496
497 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
498 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000499 if (DstType->isSignedIntegerType())
500 return Builder.CreateFPToSI(Src, DstTy, "conv");
501 else
502 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000503 }
504
505 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000506 if (DstTy->getTypeID() < Src->getType()->getTypeID())
507 return Builder.CreateFPTrunc(Src, DstTy, "conv");
508 else
509 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000510}
511
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000512/// EmitComplexToScalarConversion - Emit a conversion from the specified
513/// complex type to the specified destination type, where the destination
514/// type is an LLVM scalar type.
515Value *ScalarExprEmitter::
516EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
517 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000518 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000519 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000520
521 // Handle conversions to bool first, they are special: comparisons against 0.
522 if (DstTy->isBooleanType()) {
523 // Complex != 0 -> (Real != 0) | (Imag != 0)
524 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
525 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
526 return Builder.CreateOr(Src.first, Src.second, "tobool");
527 }
528
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000529 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
530 // the imaginary part of the complex value is discarded and the value of the
531 // real part is converted according to the conversion rules for the
532 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000533 return EmitScalarConversion(Src.first, SrcTy, DstTy);
534}
535
536
Chris Lattner9fba49a2007-08-24 05:35:26 +0000537//===----------------------------------------------------------------------===//
538// Visitor Methods
539//===----------------------------------------------------------------------===//
540
541Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000542 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000543 if (E->getType()->isVoidType())
544 return 0;
545 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
546}
547
Eli Friedmand0e9d092008-05-14 19:38:39 +0000548Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
549 llvm::SmallVector<llvm::Constant*, 32> indices;
550 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
551 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
552 }
553 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
554 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
555 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
556 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
557}
558
Chris Lattner9fba49a2007-08-24 05:35:26 +0000559Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000560 TestAndClearIgnoreResultAssign();
561
Chris Lattner9fba49a2007-08-24 05:35:26 +0000562 // Emit subscript expressions in rvalue context's. For most cases, this just
563 // loads the lvalue formed by the subscript expr. However, we have to be
564 // careful, because the base of a vector subscript is occasionally an rvalue,
565 // so we can't get it as an lvalue.
566 if (!E->getBase()->getType()->isVectorType())
567 return EmitLoadOfLValue(E);
568
569 // Handle the vector case. The base must be a vector, the index must be an
570 // integer value.
571 Value *Base = Visit(E->getBase());
572 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000573 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedmand4531942009-03-28 03:27:06 +0000574 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
575 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000576 return Builder.CreateExtractElement(Base, Idx, "vecext");
577}
578
579/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
580/// also handle things like function to pointer-to-function decay, and array to
581/// pointer decay.
582Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
583 const Expr *Op = E->getSubExpr();
584
585 // If this is due to array->pointer conversion, emit the array expression as
586 // an l-value.
587 if (Op->getType()->isArrayType()) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000588 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000589
Eli Friedman4a0073b2009-03-28 02:45:41 +0000590 // Note that VLA pointers are always decayed, so we don't need to do
591 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000592 if (!Op->getType()->isVariableArrayType()) {
593 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
594 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
595 ->getElementType()) &&
596 "Expected pointer to array");
597 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000598 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000599
600 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000601 // types as well (e.g. void*) and can be implicitly converted to integer.
602 const llvm::Type *DestTy = ConvertType(E->getType());
603 if (V->getType() != DestTy) {
604 if (isa<llvm::PointerType>(DestTy))
605 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
606 else {
607 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
608 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
609 }
610 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000611 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000612 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000613
Chris Lattner9fba49a2007-08-24 05:35:26 +0000614 return EmitCastExpr(Op, E->getType());
615}
616
617
618// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
619// have to handle a more broad range of conversions than explicit casts, as they
620// handle things like function to ptr-to-function decay etc.
621Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000622 if (!DestTy->isVoidType())
623 TestAndClearIgnoreResultAssign();
624
Chris Lattner82e10392007-08-26 07:26:12 +0000625 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000626
627 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000628 Value *Src = Visit(const_cast<Expr*>(E));
629
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000630 // Use EmitScalarConversion to perform the conversion.
631 return EmitScalarConversion(Src, E->getType(), DestTy);
632 }
Chris Lattner77288792008-02-16 23:55:16 +0000633
Chris Lattnerde0908b2008-04-04 16:54:41 +0000634 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000635 // Handle cases where the source is a complex type.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000636 bool IgnoreImag = true;
637 bool IgnoreImagAssign = true;
638 bool IgnoreReal = IgnoreResultAssign;
639 bool IgnoreRealAssign = IgnoreResultAssign;
640 if (DestTy->isBooleanType())
641 IgnoreImagAssign = IgnoreImag = false;
642 else if (DestTy->isVoidType()) {
643 IgnoreReal = IgnoreImag = false;
644 IgnoreRealAssign = IgnoreImagAssign = true;
645 }
646 CodeGenFunction::ComplexPairTy V
647 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
648 IgnoreImagAssign);
649 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner77288792008-02-16 23:55:16 +0000650 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000651
Chris Lattner77288792008-02-16 23:55:16 +0000652 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
653 // evaluate the result and return.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000654 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner77288792008-02-16 23:55:16 +0000655 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000656}
657
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000658Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000659 return CGF.EmitCompoundStmt(*E->getSubStmt(),
660 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000661}
662
Mike Stump2b6933f2009-02-28 09:07:16 +0000663Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
664 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000665}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000666
Chris Lattner9fba49a2007-08-24 05:35:26 +0000667//===----------------------------------------------------------------------===//
668// Unary Operators
669//===----------------------------------------------------------------------===//
670
671Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000672 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000673 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000674 QualType ValTy = E->getSubExpr()->getType();
675 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000676
677 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000678
679 if (ValTy->isPointerType() &&
680 ValTy->getAsPointerType()->isVariableArrayType()) {
681 // The amount of the addition/subtraction needs to account for the VLA size
682 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
683 }
684
Chris Lattner9fba49a2007-08-24 05:35:26 +0000685 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000686 if (const llvm::PointerType *PT =
687 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner8360c612009-03-18 04:25:13 +0000688 llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
689 if (!isa<llvm::FunctionType>(PT->getElementType())) {
690 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
691 } else {
692 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
693 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
694 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
695 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
696 }
Chris Lattner49083172009-02-11 07:40:06 +0000697 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
698 // Bool++ is an interesting case, due to promotion rules, we get:
699 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
700 // Bool = ((int)Bool+1) != 0
701 // An interesting aspect of this is that increment is always true.
702 // Decrement does not have this property.
703 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner291a2b32009-06-17 06:36:24 +0000704 } else if (isa<llvm::IntegerType>(InVal->getType())) {
705 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
706 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000707 } else {
708 // Add the inc/dec to the real part.
Chris Lattner291a2b32009-06-17 06:36:24 +0000709 if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000710 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000711 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000712 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000713 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000714 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000715 else {
716 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000717 bool ignored;
718 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
719 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000720 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000721 }
Chris Lattner291a2b32009-06-17 06:36:24 +0000722 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000723 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000724
725 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000726 if (LV.isBitfield())
727 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
728 &NextVal);
729 else
730 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000731
732 // If this is a postinc, return the value read from memory, otherwise use the
733 // updated value.
734 return isPre ? NextVal : InVal;
735}
736
737
738Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000739 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000740 Value *Op = Visit(E->getSubExpr());
Chris Lattner291a2b32009-06-17 06:36:24 +0000741 if (Op->getType()->isFPOrFPVector())
742 return Builder.CreateFNeg(Op, "neg");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000743 return Builder.CreateNeg(Op, "neg");
744}
745
746Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000747 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000748 Value *Op = Visit(E->getSubExpr());
749 return Builder.CreateNot(Op, "neg");
750}
751
752Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
753 // Compare operand to zero.
754 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
755
756 // Invert value.
757 // TODO: Could dynamically modify easy computations here. For example, if
758 // the operand is an icmp ne, turn into icmp eq.
759 BoolVal = Builder.CreateNot(BoolVal, "lnot");
760
Anders Carlsson62943f32009-05-19 18:44:53 +0000761 // ZExt result to the expr type.
762 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000763}
764
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000765/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
766/// argument of the sizeof expression as an integer.
767Value *
768ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000769 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000770 if (E->isSizeOf()) {
771 if (const VariableArrayType *VAT =
772 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
773 if (E->isArgumentType()) {
774 // sizeof(type) - make sure to emit the VLA size.
775 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000776 } else {
777 // C99 6.5.3.4p2: If the argument is an expression of type
778 // VLA, it is evaluated.
779 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000780 }
Anders Carlssond309f572009-01-30 16:41:04 +0000781
Anders Carlsson8f30de92009-02-05 19:43:10 +0000782 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000783 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000784 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000785
786 // If this isn't sizeof(vla), the result must be constant; use the
787 // constant folding logic so we don't have to duplicate it here.
788 Expr::EvalResult Result;
789 E->Evaluate(Result, CGF.getContext());
790 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000791}
792
Chris Lattner01211af2007-08-24 21:20:17 +0000793Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
794 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000795 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000796 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner01211af2007-08-24 21:20:17 +0000797 return Visit(Op);
798}
799Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
800 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000801 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000802 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000803
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000804 // __imag on a scalar returns zero. Emit the subexpr to ensure side
805 // effects are evaluated, but not the actual value.
806 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
807 CGF.EmitLValue(Op);
808 else
809 CGF.EmitScalarExpr(Op, true);
Owen Anderson5f1adc22009-07-13 04:10:07 +0000810 return CGF.getLLVMContext().getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000811}
812
Anders Carlsson52774ad2008-01-29 15:56:48 +0000813Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
814{
Eli Friedman342d9432009-02-27 06:44:11 +0000815 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000816 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000817 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000818}
Chris Lattner01211af2007-08-24 21:20:17 +0000819
Chris Lattner9fba49a2007-08-24 05:35:26 +0000820//===----------------------------------------------------------------------===//
821// Binary Operators
822//===----------------------------------------------------------------------===//
823
824BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000825 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000826 BinOpInfo Result;
827 Result.LHS = Visit(E->getLHS());
828 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000829 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000830 Result.E = E;
831 return Result;
832}
833
Chris Lattner0d965302007-08-26 21:41:21 +0000834Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000835 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000836 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner660e31d2007-08-24 21:00:35 +0000837 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
838
839 BinOpInfo OpInfo;
840
Eli Friedman3cd92882009-03-28 01:22:36 +0000841 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000842 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000843 // it's a tad complicated to do that... I'm leaving it out for now.
844 // (Note that we do actually need the imaginary part of the RHS for
845 // multiplication and division.)
846 CGF.ErrorUnsupported(E, "complex compound assignment");
847 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
848 }
849
Mike Stump8d962262009-05-22 19:07:20 +0000850 // Emit the RHS first. __block variables need to have the rhs evaluated
851 // first, plus this should improve codegen a little.
852 OpInfo.RHS = Visit(E->getRHS());
853 OpInfo.Ty = E->getComputationResultType();
854 OpInfo.E = E;
Eli Friedman3cd92882009-03-28 01:22:36 +0000855 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000856 LValue LHSLV = EmitLValue(E->getLHS());
857 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000858 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
859 E->getComputationLHSType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000860
861 // Expand the binary operator.
862 Value *Result = (this->*Func)(OpInfo);
863
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000864 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000865 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
866
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000867 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000868 // handled specially because the result is altered by the store,
869 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
870 // the left operand after the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000871 if (LHSLV.isBitfield()) {
872 if (!LHSLV.isVolatileQualified()) {
873 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
874 &Result);
875 return Result;
876 } else
877 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
878 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000879 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000880 if (Ignore)
881 return 0;
882 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000883}
884
885
Chris Lattner9fba49a2007-08-24 05:35:26 +0000886Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000887 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000888 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000889 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000890 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
891 else
892 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
893}
894
895Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
896 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000897 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000898 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
899 else
900 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
901}
902
Mike Stumpdb789912009-04-01 20:28:16 +0000903Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
904 unsigned IID;
905 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000906
Mike Stumpf71b7742009-04-02 18:15:54 +0000907 switch (Ops.E->getOpcode()) {
908 case BinaryOperator::Add:
909 case BinaryOperator::AddAssign:
910 OpID = 1;
911 IID = llvm::Intrinsic::sadd_with_overflow;
912 break;
913 case BinaryOperator::Sub:
914 case BinaryOperator::SubAssign:
915 OpID = 2;
916 IID = llvm::Intrinsic::ssub_with_overflow;
917 break;
918 case BinaryOperator::Mul:
919 case BinaryOperator::MulAssign:
920 OpID = 3;
921 IID = llvm::Intrinsic::smul_with_overflow;
922 break;
923 default:
924 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000925 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000926 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000927 OpID <<= 1;
928 OpID |= 1;
929
Mike Stumpdb789912009-04-01 20:28:16 +0000930 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
931
932 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
933
934 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
935 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
936 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
937
938 // Branch in case of overflow.
939 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
940 llvm::BasicBlock *overflowBB =
941 CGF.createBasicBlock("overflow", CGF.CurFn);
942 llvm::BasicBlock *continueBB =
943 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
944
945 Builder.CreateCondBr(overflow, overflowBB, continueBB);
946
947 // Handle overflow
948
949 Builder.SetInsertPoint(overflowBB);
950
951 // Handler is:
952 // long long *__overflow_handler)(long long a, long long b, char op,
953 // char width)
954 std::vector<const llvm::Type*> handerArgTypes;
955 handerArgTypes.push_back(llvm::Type::Int64Ty);
956 handerArgTypes.push_back(llvm::Type::Int64Ty);
957 handerArgTypes.push_back(llvm::Type::Int8Ty);
958 handerArgTypes.push_back(llvm::Type::Int8Ty);
959 llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
960 handerArgTypes, false);
961 llvm::Value *handlerFunction =
962 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
963 llvm::PointerType::getUnqual(handlerTy));
964 handlerFunction = Builder.CreateLoad(handlerFunction);
965
966 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
967 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
968 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
969 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
970 llvm::ConstantInt::get(llvm::Type::Int8Ty,
971 cast<llvm::IntegerType>(opTy)->getBitWidth()));
972
973 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
974
975 Builder.CreateBr(continueBB);
976
977 // Set up the continuation
978 Builder.SetInsertPoint(continueBB);
979 // Get the correct result
980 llvm::PHINode *phi = Builder.CreatePHI(opTy);
981 phi->reserveOperandSpace(2);
982 phi->addIncoming(result, initialBB);
983 phi->addIncoming(handlerResult, overflowBB);
984
985 return phi;
986}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000987
988Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff79ae19a2009-07-14 18:25:06 +0000989 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner291a2b32009-06-17 06:36:24 +0000990 if (CGF.getContext().getLangOptions().OverflowChecking &&
991 Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000992 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +0000993
994 if (Ops.LHS->getType()->isFPOrFPVector())
995 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
996
Chris Lattner9fba49a2007-08-24 05:35:26 +0000997 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +0000998 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000999
Steve Naroff329ec222009-07-10 23:34:53 +00001000 if (Ops.Ty->isPointerType() &&
1001 Ops.Ty->getAsPointerType()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +00001002 // The amount of the addition needs to account for the VLA size
1003 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1004 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001005 Value *Ptr, *Idx;
1006 Expr *IdxExp;
Steve Naroff329ec222009-07-10 23:34:53 +00001007 const PointerType *PT = Ops.E->getLHS()->getType()->getAsPointerType();
1008 const ObjCObjectPointerType *OPT =
1009 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1010 if (PT || OPT) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001011 Ptr = Ops.LHS;
1012 Idx = Ops.RHS;
1013 IdxExp = Ops.E->getRHS();
Steve Naroff329ec222009-07-10 23:34:53 +00001014 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001015 PT = Ops.E->getRHS()->getType()->getAsPointerType();
Steve Naroff329ec222009-07-10 23:34:53 +00001016 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1017 assert((PT || OPT) && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +00001018 Ptr = Ops.RHS;
1019 Idx = Ops.LHS;
1020 IdxExp = Ops.E->getLHS();
1021 }
1022
1023 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001024 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001025 // Zero or sign extend the pointer value based on whether the index is
1026 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001027 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +00001028 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +00001029 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1030 else
1031 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1032 }
Steve Naroff329ec222009-07-10 23:34:53 +00001033 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001034 // Handle interface types, which are not represented with a concrete
1035 // type.
1036 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1037 llvm::Value *InterfaceSize =
1038 llvm::ConstantInt::get(Idx->getType(),
1039 CGF.getContext().getTypeSize(OIT) / 8);
1040 Idx = Builder.CreateMul(Idx, InterfaceSize);
1041 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1042 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1043 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1044 return Builder.CreateBitCast(Res, Ptr->getType());
1045 }
1046
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001047 // Explicitly handle GNU void* and function pointer arithmetic
1048 // extensions. The GNU void* casts amount to no-ops since our void*
1049 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001050 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1051 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1052 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001053 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001054 return Builder.CreateBitCast(Res, Ptr->getType());
1055 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001056
1057 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001058}
1059
1060Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001061 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001062 if (CGF.getContext().getLangOptions().OverflowChecking
1063 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001064 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +00001065
1066 if (Ops.LHS->getType()->isFPOrFPVector())
1067 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001068 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001069 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001070
Steve Naroff329ec222009-07-10 23:34:53 +00001071 if (Ops.E->getLHS()->getType()->isPointerType() &&
1072 Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +00001073 // The amount of the addition needs to account for the VLA size for
1074 // ptr-int
1075 // The amount of the division needs to account for the VLA size for
1076 // ptr-ptr.
1077 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1078 }
1079
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001080 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00001081 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001082 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1083 // pointer - int
1084 Value *Idx = Ops.RHS;
1085 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001086 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001087 // Zero or sign extend the pointer value based on whether the index is
1088 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001089 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001090 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1091 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1092 else
1093 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1094 }
1095 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001096
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001097 // Handle interface types, which are not represented with a concrete
1098 // type.
1099 if (const ObjCInterfaceType *OIT =
1100 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1101 llvm::Value *InterfaceSize =
1102 llvm::ConstantInt::get(Idx->getType(),
1103 CGF.getContext().getTypeSize(OIT) / 8);
1104 Idx = Builder.CreateMul(Idx, InterfaceSize);
1105 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1106 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1107 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1108 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1109 }
1110
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001111 // Explicitly handle GNU void* and function pointer arithmetic
1112 // extensions. The GNU void* casts amount to no-ops since our
1113 // void* type is i8*, but this is future proof.
1114 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1115 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1116 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1117 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1118 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1119 }
1120
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001121 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001122 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001123 // pointer - pointer
1124 Value *LHS = Ops.LHS;
1125 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001126
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001127 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001128
Chris Lattner6d2e3492009-02-11 07:21:43 +00001129 // Handle GCC extension for pointer arithmetic on void* and function pointer
1130 // types.
1131 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001132 ElementSize = 1;
1133 } else {
1134 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1135 }
1136
1137 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1138 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1139 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1140 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1141
Chris Lattner6d2e3492009-02-11 07:21:43 +00001142 // Optimize out the shift for element size of 1.
1143 if (ElementSize == 1)
1144 return BytesBetween;
1145
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001146 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1147 // remainder. As such, we handle common power-of-two cases here to generate
1148 // better code. See PR2247.
1149 if (llvm::isPowerOf2_64(ElementSize)) {
1150 Value *ShAmt =
1151 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1152 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1153 }
1154
1155 // Otherwise, do a full sdiv.
1156 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1157 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001158 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001159}
1160
1161Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1162 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1163 // RHS to the same size as the LHS.
1164 Value *RHS = Ops.RHS;
1165 if (Ops.LHS->getType() != RHS->getType())
1166 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1167
1168 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1169}
1170
1171Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1172 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1173 // RHS to the same size as the LHS.
1174 Value *RHS = Ops.RHS;
1175 if (Ops.LHS->getType() != RHS->getType())
1176 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1177
Chris Lattner660e31d2007-08-24 21:00:35 +00001178 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001179 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1180 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1181}
1182
1183Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1184 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001185 TestAndClearIgnoreResultAssign();
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001186 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001187 QualType LHSTy = E->getLHS()->getType();
Chris Lattner08ac8522009-07-08 01:08:03 +00001188 if (!LHSTy->isAnyComplexType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001189 Value *LHS = Visit(E->getLHS());
1190 Value *RHS = Visit(E->getRHS());
1191
1192 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001193 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001194 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001195 } else if (LHSTy->isSignedIntegerType()) {
1196 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001197 LHS, RHS, "cmp");
1198 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001199 // Unsigned integers and pointers.
1200 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001201 LHS, RHS, "cmp");
1202 }
Chris Lattner08ac8522009-07-08 01:08:03 +00001203
1204 // If this is a vector comparison, sign extend the result to the appropriate
1205 // vector integer type and return it (don't convert to bool).
1206 if (LHSTy->isVectorType())
1207 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman1591bc52008-07-25 20:16:05 +00001208
Chris Lattner9fba49a2007-08-24 05:35:26 +00001209 } else {
1210 // Complex Comparison: can only be an equality comparison.
1211 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1212 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1213
Chris Lattnerc154ac12008-07-26 22:37:01 +00001214 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001215
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001216 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001217 if (CETy->isRealFloatingType()) {
1218 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1219 LHS.first, RHS.first, "cmp.r");
1220 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1221 LHS.second, RHS.second, "cmp.i");
1222 } else {
1223 // Complex comparisons can only be equality comparisons. As such, signed
1224 // and unsigned opcodes are the same.
1225 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1226 LHS.first, RHS.first, "cmp.r");
1227 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1228 LHS.second, RHS.second, "cmp.i");
1229 }
1230
1231 if (E->getOpcode() == BinaryOperator::EQ) {
1232 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1233 } else {
1234 assert(E->getOpcode() == BinaryOperator::NE &&
1235 "Complex comparison other than == or != ?");
1236 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1237 }
1238 }
Nuno Lopes92577002009-01-11 23:22:37 +00001239
1240 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001241}
1242
1243Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001244 bool Ignore = TestAndClearIgnoreResultAssign();
1245
1246 // __block variables need to have the rhs evaluated first, plus this should
1247 // improve codegen just a little.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001248 Value *RHS = Visit(E->getRHS());
Mike Stump68df15c2009-05-21 21:05:15 +00001249 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001250
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001251 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001252 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1253 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001254 // the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001255 if (LHS.isBitfield()) {
1256 if (!LHS.isVolatileQualified()) {
1257 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1258 &RHS);
1259 return RHS;
1260 } else
1261 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1262 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001263 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001264 if (Ignore)
1265 return 0;
1266 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001267}
1268
1269Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001270 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1271 // If we have 1 && X, just emit X without inserting the control flow.
1272 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1273 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001274 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1275 // ZExt result to int.
1276 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1277 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001278
1279 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1280 if (!CGF.ContainsLabel(E->getRHS()))
Owen Anderson5f1adc22009-07-13 04:10:07 +00001281 return CGF.getLLVMContext().getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001282 }
1283
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001284 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1285 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001286
Chris Lattner7f80bb32008-11-12 08:38:24 +00001287 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1288 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1289
1290 // Any edges into the ContBlock are now from an (indeterminate number of)
1291 // edges from this first condition. All of these values will be false. Start
1292 // setting up the PHI node in the Cont Block for this.
1293 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1294 PN->reserveOperandSpace(2); // Normal case, two inputs.
1295 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1296 PI != PE; ++PI)
1297 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001298
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001299 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001300 CGF.EmitBlock(RHSBlock);
1301 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001302 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001303
1304 // Reaquire the RHS block, as there may be subblocks inserted.
1305 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001306
1307 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1308 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001309 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001310 PN->addIncoming(RHSCond, RHSBlock);
1311
1312 // ZExt result to int.
1313 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1314}
1315
1316Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001317 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1318 // If we have 0 || X, just emit X without inserting the control flow.
1319 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1320 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001321 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1322 // ZExt result to int.
1323 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1324 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001325
Eli Friedmanea137cd2008-12-02 16:02:46 +00001326 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001327 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001328 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001329 }
1330
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001331 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1332 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001333
Chris Lattner7f80bb32008-11-12 08:38:24 +00001334 // Branch on the LHS first. If it is true, go to the success (cont) block.
1335 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1336
1337 // Any edges into the ContBlock are now from an (indeterminate number of)
1338 // edges from this first condition. All of these values will be true. Start
1339 // setting up the PHI node in the Cont Block for this.
1340 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1341 PN->reserveOperandSpace(2); // Normal case, two inputs.
1342 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1343 PI != PE; ++PI)
1344 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1345
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001346 CGF.PushConditionalTempDestruction();
1347
Chris Lattner7f80bb32008-11-12 08:38:24 +00001348 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001349 CGF.EmitBlock(RHSBlock);
1350 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1351
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001352 CGF.PopConditionalTempDestruction();
1353
Chris Lattner9fba49a2007-08-24 05:35:26 +00001354 // Reaquire the RHS block, as there may be subblocks inserted.
1355 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001356
Chris Lattner7f80bb32008-11-12 08:38:24 +00001357 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1358 // into the phi node for the edge with the value of RHSCond.
1359 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001360 PN->addIncoming(RHSCond, RHSBlock);
1361
1362 // ZExt result to int.
1363 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1364}
1365
1366Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1367 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001368 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001369 return Visit(E->getRHS());
1370}
1371
1372//===----------------------------------------------------------------------===//
1373// Other Operators
1374//===----------------------------------------------------------------------===//
1375
Chris Lattner504a5282008-11-12 08:55:54 +00001376/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1377/// expression is cheap enough and side-effect-free enough to evaluate
1378/// unconditionally instead of conditionally. This is used to convert control
1379/// flow into selects in some cases.
1380static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1381 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1382 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1383
1384 // TODO: Allow anything we can constant fold to an integer or fp constant.
1385 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1386 isa<FloatingLiteral>(E))
1387 return true;
1388
1389 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1390 // X and Y are local variables.
1391 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1392 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1393 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1394 return true;
1395
1396 return false;
1397}
1398
1399
Chris Lattner9fba49a2007-08-24 05:35:26 +00001400Value *ScalarExprEmitter::
1401VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001402 TestAndClearIgnoreResultAssign();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001403 // If the condition constant folds and can be elided, try to avoid emitting
1404 // the condition and the dead arm.
1405 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001406 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001407 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001408 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001409
1410 // If the dead side doesn't have labels we need, and if the Live side isn't
1411 // the gnu missing ?: extension (which we could handle, but don't bother
1412 // to), just emit the Live part.
1413 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1414 Live) // Live part isn't missing.
1415 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001416 }
1417
Chris Lattner504a5282008-11-12 08:55:54 +00001418
1419 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1420 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001421 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001422 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1423 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1424 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1425 llvm::Value *LHS = Visit(E->getLHS());
1426 llvm::Value *RHS = Visit(E->getRHS());
1427 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1428 }
1429
1430
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001431 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1432 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001433 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001434 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001435
Chris Lattner86031712009-02-13 23:35:32 +00001436 // If we don't have the GNU missing condition extension, emit a branch on
1437 // bool the normal way.
1438 if (E->getLHS()) {
1439 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1440 // the branch on bool.
1441 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1442 } else {
1443 // Otherwise, for the ?: extension, evaluate the conditional and then
1444 // convert it to bool the hard way. We do this explicitly because we need
1445 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001446 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001447
1448 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1449 // if there are no extra uses (an optimization). Inhibit this by making an
1450 // extra dead use, because we're going to add a use of CondVal later. We
1451 // don't use the builder for this, because we don't want it to get optimized
1452 // away. This leaves dead code, but the ?: extension isn't common.
1453 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1454 Builder.GetInsertBlock());
1455
Chris Lattner67e22462008-11-12 08:08:13 +00001456 Value *CondBoolVal =
1457 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1458 CGF.getContext().BoolTy);
1459 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001460 }
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001461
1462 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001463 CGF.EmitBlock(LHSBlock);
1464
1465 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001466 Value *LHS;
1467 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001468 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001469 else // Perform promotions, to handle cases like "short ?: int"
1470 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1471
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001472 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001473 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001474 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001475
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001476 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001477 CGF.EmitBlock(RHSBlock);
1478
Eli Friedmance8d7032008-05-16 20:38:39 +00001479 Value *RHS = Visit(E->getRHS());
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001480 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001481 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001482 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001483
1484 CGF.EmitBlock(ContBlock);
1485
Nuno Lopesb62ff242008-06-04 19:15:45 +00001486 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001487 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1488 return 0;
1489 }
1490
Chris Lattner9fba49a2007-08-24 05:35:26 +00001491 // Create a PHI node for the real part.
1492 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1493 PN->reserveOperandSpace(2);
1494 PN->addIncoming(LHS, LHSBlock);
1495 PN->addIncoming(RHS, RHSBlock);
1496 return PN;
1497}
1498
1499Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001500 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001501}
1502
Chris Lattner307da022007-11-30 17:56:23 +00001503Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001504 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001505 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1506
1507 // If EmitVAArg fails, we fall back to the LLVM instruction.
1508 if (!ArgPtr)
1509 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1510
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001511 // FIXME Volatility.
Anders Carlsson285611e2008-11-04 05:30:00 +00001512 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001513}
1514
Mike Stump4eb81dc2009-02-12 18:29:15 +00001515Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001516 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001517}
1518
Chris Lattner9fba49a2007-08-24 05:35:26 +00001519//===----------------------------------------------------------------------===//
1520// Entry Point into this File
1521//===----------------------------------------------------------------------===//
1522
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001523/// EmitScalarExpr - Emit the computation of the specified expression of
1524/// scalar type, ignoring the result.
1525Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001526 assert(E && !hasAggregateLLVMType(E->getType()) &&
1527 "Invalid scalar expression to emit");
1528
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001529 return ScalarExprEmitter(*this, IgnoreResultAssign)
1530 .Visit(const_cast<Expr*>(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001531}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001532
1533/// EmitScalarConversion - Emit a conversion from the specified type to the
1534/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001535Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1536 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001537 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1538 "Invalid scalar expression to emit");
1539 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1540}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001541
1542/// EmitComplexToScalarConversion - Emit a conversion from the specified
1543/// complex type to the specified destination type, where the destination
1544/// type is an LLVM scalar type.
1545Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1546 QualType SrcTy,
1547 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001548 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001549 "Invalid complex -> scalar conversion");
1550 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1551 DstTy);
1552}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001553
1554Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1555 assert(V1->getType() == V2->getType() &&
1556 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001557 unsigned NumElements =
1558 cast<llvm::VectorType>(V1->getType())->getNumElements();
1559
1560 va_list va;
1561 va_start(va, V2);
1562
1563 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001564 for (unsigned i = 0; i < NumElements; i++) {
1565 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001566 assert(n >= 0 && n < (int)NumElements * 2 &&
1567 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001568 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1569 }
1570
1571 const char *Name = va_arg(va, const char *);
1572 va_end(va);
1573
1574 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1575
1576 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1577}
1578
Anders Carlsson68b8be92007-12-15 21:23:30 +00001579llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001580 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001581 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001582 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001583
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001584 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001585 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001586 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001587 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001588 }
1589
1590 return Vec;
1591}