blob: 161cd5741806056e4c789b36d15d4e68a227d449 [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"
Eli Friedmanccffea92009-01-24 22:38:55 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stumpdb789912009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000030
Chris Lattner9fba49a2007-08-24 05:35:26 +000031using namespace clang;
32using namespace CodeGen;
33using llvm::Value;
34
35//===----------------------------------------------------------------------===//
36// Scalar Expression Emitter
37//===----------------------------------------------------------------------===//
38
39struct BinOpInfo {
40 Value *LHS;
41 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000043 const BinaryOperator *E;
44};
45
46namespace {
47class VISIBILITY_HIDDEN ScalarExprEmitter
48 : public StmtVisitor<ScalarExprEmitter, Value*> {
49 CodeGenFunction &CGF;
Daniel Dunbard916e6e2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Mike Stumpb8fc73e2009-05-29 15:46:01 +000051 bool IgnoreResultAssign;
Chris Lattner9fba49a2007-08-24 05:35:26 +000052public:
53
Mike Stumpb8fc73e2009-05-29 15:46:01 +000054 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
55 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000056 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000057
58 //===--------------------------------------------------------------------===//
59 // Utilities
60 //===--------------------------------------------------------------------===//
61
Mike Stumpb8fc73e2009-05-29 15:46:01 +000062 bool TestAndClearIgnoreResultAssign() {
Chris Lattner08ac8522009-07-08 01:08:03 +000063 bool I = IgnoreResultAssign;
64 IgnoreResultAssign = false;
65 return I;
66 }
Mike Stumpb8fc73e2009-05-29 15:46:01 +000067
Chris Lattner9fba49a2007-08-24 05:35:26 +000068 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
69 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
70
71 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000072 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000073 }
74
75 /// EmitLoadOfLValue - Given an expression with complex type that represents a
76 /// value l-value, this method emits the address of the l-value, then loads
77 /// and returns the result.
78 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000079 return EmitLoadOfLValue(EmitLValue(E), E->getType());
80 }
81
Chris Lattnerd8d44222007-08-26 16:42:57 +000082 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000083 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000084 Value *EmitConversionToBool(Value *Src, QualType DstTy);
85
Chris Lattner4e05d1e2007-08-26 06:48:56 +000086 /// EmitScalarConversion - Emit a conversion from the specified type to the
87 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000088 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
89
90 /// EmitComplexToScalarConversion - Emit a conversion from the specified
91 /// complex type to the specified destination type, where the destination
92 /// type is an LLVM scalar type.
93 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
94 QualType SrcTy, QualType DstTy);
Mike Stump4eb81dc2009-02-12 18:29:15 +000095
Chris Lattner9fba49a2007-08-24 05:35:26 +000096 //===--------------------------------------------------------------------===//
97 // Visitor Methods
98 //===--------------------------------------------------------------------===//
99
100 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000101 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000102 assert(0 && "Stmt can't have complex result type!");
103 return 0;
104 }
105 Value *VisitExpr(Expr *S);
106 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
107
108 // Leaves.
109 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
110 return llvm::ConstantInt::get(E->getValue());
111 }
112 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000113 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000114 }
115 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
116 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
117 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000118 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
119 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
120 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000121 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
122 return llvm::Constant::getNullValue(ConvertType(E->getType()));
123 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000124 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
125 return llvm::Constant::getNullValue(ConvertType(E->getType()));
126 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000127 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
128 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000129 CGF.getContext().typesAreCompatible(
130 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000131 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000132 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000133 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000134 llvm::Value *V =
135 llvm::ConstantInt::get(llvm::Type::Int32Ty,
136 CGF.GetIDForAddrOfLabel(E->getLabel()));
137
138 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000139 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000140
141 // l-values.
142 Value *VisitDeclRefExpr(DeclRefExpr *E) {
143 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
144 return llvm::ConstantInt::get(EC->getInitVal());
145 return EmitLoadOfLValue(E);
146 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000147 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
148 return CGF.EmitObjCSelectorExpr(E);
149 }
150 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
151 return CGF.EmitObjCProtocolExpr(E);
152 }
153 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
154 return EmitLoadOfLValue(E);
155 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000156 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000157 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000158 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000159 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
160 return EmitLoadOfLValue(E);
161 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000162 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
163 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000164 }
165
Chris Lattner9fba49a2007-08-24 05:35:26 +0000166 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000167 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000168 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000169 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000170 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
171 return EmitLoadOfLValue(E);
172 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000173 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerc5d32632009-02-24 22:18:39 +0000174 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
175 return EmitLValue(E).getAddress();
176 }
177
Chris Lattner69909292008-08-10 01:53:14 +0000178 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000179
180 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000181 bool Ignore = TestAndClearIgnoreResultAssign();
182 (void)Ignore;
183 assert (Ignore == false && "init list ignored");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000184 unsigned NumInitElements = E->getNumInits();
185
Douglas Gregor9fddded2009-01-29 19:42:23 +0000186 if (E->hadArrayRangeDesignator()) {
187 CGF.ErrorUnsupported(E, "GNU array range designator extension");
188 }
189
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000190 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000191 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
192
193 // We have a scalar in braces. Just use the first element.
194 if (!VType)
195 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000196
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000197 unsigned NumVectorElements = VType->getNumElements();
198 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000199
200 // Emit individual vector element stores.
201 llvm::Value *V = llvm::UndefValue::get(VType);
202
Anders Carlsson323d5682007-12-18 02:45:33 +0000203 // Emit initializers
204 unsigned i;
205 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000206 Value *NewV = Visit(E->getInit(i));
207 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
208 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000209 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000210
211 // Emit remaining default initializers
212 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
213 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
214 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
215 V = Builder.CreateInsertElement(V, NewV, Idx);
216 }
217
Devang Patel32c39832007-10-24 18:05:48 +0000218 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000219 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000220
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000221 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
222 return llvm::Constant::getNullValue(ConvertType(E->getType()));
223 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000224 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmana7ef8e52009-04-20 03:54:15 +0000225 Value *VisitCastExpr(const CastExpr *E) {
226 // Make sure to evaluate VLA bounds now so that we have them for later.
227 if (E->getType()->isVariablyModifiedType())
228 CGF.EmitVLASize(E->getType());
229
Chris Lattner9fba49a2007-08-24 05:35:26 +0000230 return EmitCastExpr(E->getSubExpr(), E->getType());
231 }
232 Value *EmitCastExpr(const Expr *E, QualType T);
233
234 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssoncd295282009-05-27 03:37:57 +0000235 if (E->getCallReturnType()->isReferenceType())
236 return EmitLoadOfLValue(E);
237
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000238 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000239 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000240
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000241 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000242
Mike Stump2b6933f2009-02-28 09:07:16 +0000243 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000244
Chris Lattner9fba49a2007-08-24 05:35:26 +0000245 // Unary Operators.
246 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
247 Value *VisitUnaryPostDec(const UnaryOperator *E) {
248 return VisitPrePostIncDec(E, false, false);
249 }
250 Value *VisitUnaryPostInc(const UnaryOperator *E) {
251 return VisitPrePostIncDec(E, true, false);
252 }
253 Value *VisitUnaryPreDec(const UnaryOperator *E) {
254 return VisitPrePostIncDec(E, false, true);
255 }
256 Value *VisitUnaryPreInc(const UnaryOperator *E) {
257 return VisitPrePostIncDec(E, true, true);
258 }
259 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
260 return EmitLValue(E->getSubExpr()).getAddress();
261 }
262 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
263 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000264 // This differs from gcc, though, most likely due to a bug in gcc.
265 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000266 return Visit(E->getSubExpr());
267 }
268 Value *VisitUnaryMinus (const UnaryOperator *E);
269 Value *VisitUnaryNot (const UnaryOperator *E);
270 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000271 Value *VisitUnaryReal (const UnaryOperator *E);
272 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000273 Value *VisitUnaryExtension(const UnaryOperator *E) {
274 return Visit(E->getSubExpr());
275 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000276 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson49d4a572009-04-14 16:58:56 +0000277
278 // C++
Chris Lattner3e254fb2008-04-08 04:40:51 +0000279 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
280 return Visit(DAE->getExpr());
281 }
Anders Carlsson49d4a572009-04-14 16:58:56 +0000282 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
283 return CGF.LoadCXXThis();
284 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000285
Anders Carlsson272b5f52009-05-19 04:48:36 +0000286 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlssond6775602009-05-31 00:09:15 +0000287 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson272b5f52009-05-19 04:48:36 +0000288 }
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000289 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
290 return CGF.EmitCXXNewExpr(E);
291 }
Anders Carlsson272b5f52009-05-19 04:48:36 +0000292
Chris Lattner9fba49a2007-08-24 05:35:26 +0000293 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000294 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000295 if (CGF.getContext().getLangOptions().OverflowChecking
296 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000297 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +0000298 if (Ops.LHS->getType()->isFPOrFPVector())
299 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000300 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
301 }
Mike Stumpdb789912009-04-01 20:28:16 +0000302 /// Create a binary op that checks for overflow.
303 /// Currently only supports +, - and *.
304 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000305 Value *EmitDiv(const BinOpInfo &Ops);
306 Value *EmitRem(const BinOpInfo &Ops);
307 Value *EmitAdd(const BinOpInfo &Ops);
308 Value *EmitSub(const BinOpInfo &Ops);
309 Value *EmitShl(const BinOpInfo &Ops);
310 Value *EmitShr(const BinOpInfo &Ops);
311 Value *EmitAnd(const BinOpInfo &Ops) {
312 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
313 }
314 Value *EmitXor(const BinOpInfo &Ops) {
315 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
316 }
317 Value *EmitOr (const BinOpInfo &Ops) {
318 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
319 }
320
Chris Lattner660e31d2007-08-24 21:00:35 +0000321 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000322 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000323 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
324
325 // Binary operators and binary compound assignment operators.
326#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000327 Value *VisitBin ## OP(const BinaryOperator *E) { \
328 return Emit ## OP(EmitBinOps(E)); \
329 } \
330 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
331 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000332 }
333 HANDLEBINOP(Mul);
334 HANDLEBINOP(Div);
335 HANDLEBINOP(Rem);
336 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000337 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000338 HANDLEBINOP(Shl);
339 HANDLEBINOP(Shr);
340 HANDLEBINOP(And);
341 HANDLEBINOP(Xor);
342 HANDLEBINOP(Or);
343#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000344
Chris Lattner9fba49a2007-08-24 05:35:26 +0000345 // Comparisons.
346 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
347 unsigned SICmpOpc, unsigned FCmpOpc);
348#define VISITCOMP(CODE, UI, SI, FP) \
349 Value *VisitBin##CODE(const BinaryOperator *E) { \
350 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
351 llvm::FCmpInst::FP); }
352 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
353 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
354 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
355 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
356 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
357 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
358#undef VISITCOMP
359
360 Value *VisitBinAssign (const BinaryOperator *E);
361
362 Value *VisitBinLAnd (const BinaryOperator *E);
363 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000364 Value *VisitBinComma (const BinaryOperator *E);
365
366 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000367 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000368 Value *VisitConditionalOperator(const ConditionalOperator *CO);
369 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000370 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000371 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
372 return CGF.EmitObjCStringLiteral(E);
373 }
374};
375} // end anonymous namespace.
376
377//===----------------------------------------------------------------------===//
378// Utilities
379//===----------------------------------------------------------------------===//
380
Chris Lattnerd8d44222007-08-26 16:42:57 +0000381/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000382/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000383Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
384 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
385
386 if (SrcType->isRealFloatingType()) {
387 // Compare against 0.0 for fp scalars.
388 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000389 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
390 }
391
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000392 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000393 "Unknown scalar type to convert");
394
395 // Because of the type rules of C, we often end up computing a logical value,
396 // then zero extending it to int, then wanting it as a logical value again.
397 // Optimize this common case.
398 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
399 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
400 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000401 // If there aren't any more uses, zap the instruction to save space.
402 // Note that there can be more uses, for example if this
403 // is the result of an assignment.
404 if (ZI->use_empty())
405 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000406 return Result;
407 }
408 }
409
410 // Compare against an integer or pointer null.
411 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
412 return Builder.CreateICmpNE(Src, Zero, "tobool");
413}
414
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000415/// EmitScalarConversion - Emit a conversion from the specified type to the
416/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000417Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
418 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000419 SrcType = CGF.getContext().getCanonicalType(SrcType);
420 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000421 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000422
423 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000424
425 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000426 if (DstType->isBooleanType())
427 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000428
429 const llvm::Type *DstTy = ConvertType(DstType);
430
431 // Ignore conversions like int -> uint.
432 if (Src->getType() == DstTy)
433 return Src;
434
Daniel Dunbar238335f2008-08-25 09:51:32 +0000435 // Handle pointer conversions next: pointers can only be converted
436 // to/from other pointers and integers. Check for pointer types in
437 // terms of LLVM, as some native types (like Obj-C id) may map to a
438 // pointer type.
439 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000440 // The source value may be an integer, or a pointer.
441 if (isa<llvm::PointerType>(Src->getType()))
442 return Builder.CreateBitCast(Src, DstTy, "conv");
443 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000444 // First, convert to the correct width so that we control the kind of
445 // extension.
446 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
447 bool InputSigned = SrcType->isSignedIntegerType();
448 llvm::Value* IntResult =
449 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
450 // Then, cast to pointer.
451 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000452 }
453
Daniel Dunbar238335f2008-08-25 09:51:32 +0000454 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000455 // Must be an ptr to int cast.
456 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000457 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000458 }
459
Nate Begemanaf6ed502008-04-18 23:10:10 +0000460 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000461 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
462 // Cast the scalar to element type
463 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
464 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
465
466 // Insert the element in element zero of an undef vector
467 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
468 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
469 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
470
471 // Splat the element across to all elements
472 llvm::SmallVector<llvm::Constant*, 16> Args;
473 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
474 for (unsigned i = 0; i < NumElements; i++)
475 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
476
477 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
478 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
479 return Yay;
480 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000481
Chris Lattner4f025a42008-02-02 04:51:41 +0000482 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000483 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000484 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000485 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000486
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000487 // Finally, we have the arithmetic types: real int/float.
488 if (isa<llvm::IntegerType>(Src->getType())) {
489 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000490 if (isa<llvm::IntegerType>(DstTy))
491 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
492 else if (InputSigned)
493 return Builder.CreateSIToFP(Src, DstTy, "conv");
494 else
495 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000496 }
497
498 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
499 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000500 if (DstType->isSignedIntegerType())
501 return Builder.CreateFPToSI(Src, DstTy, "conv");
502 else
503 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000504 }
505
506 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000507 if (DstTy->getTypeID() < Src->getType()->getTypeID())
508 return Builder.CreateFPTrunc(Src, DstTy, "conv");
509 else
510 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000511}
512
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000513/// EmitComplexToScalarConversion - Emit a conversion from the specified
514/// complex type to the specified destination type, where the destination
515/// type is an LLVM scalar type.
516Value *ScalarExprEmitter::
517EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
518 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000519 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000520 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000521
522 // Handle conversions to bool first, they are special: comparisons against 0.
523 if (DstTy->isBooleanType()) {
524 // Complex != 0 -> (Real != 0) | (Imag != 0)
525 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
526 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
527 return Builder.CreateOr(Src.first, Src.second, "tobool");
528 }
529
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000530 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
531 // the imaginary part of the complex value is discarded and the value of the
532 // real part is converted according to the conversion rules for the
533 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000534 return EmitScalarConversion(Src.first, SrcTy, DstTy);
535}
536
537
Chris Lattner9fba49a2007-08-24 05:35:26 +0000538//===----------------------------------------------------------------------===//
539// Visitor Methods
540//===----------------------------------------------------------------------===//
541
542Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000543 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000544 if (E->getType()->isVoidType())
545 return 0;
546 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
547}
548
Eli Friedmand0e9d092008-05-14 19:38:39 +0000549Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
550 llvm::SmallVector<llvm::Constant*, 32> indices;
551 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
552 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
553 }
554 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
555 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
556 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
557 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
558}
559
Chris Lattner9fba49a2007-08-24 05:35:26 +0000560Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000561 TestAndClearIgnoreResultAssign();
562
Chris Lattner9fba49a2007-08-24 05:35:26 +0000563 // Emit subscript expressions in rvalue context's. For most cases, this just
564 // loads the lvalue formed by the subscript expr. However, we have to be
565 // careful, because the base of a vector subscript is occasionally an rvalue,
566 // so we can't get it as an lvalue.
567 if (!E->getBase()->getType()->isVectorType())
568 return EmitLoadOfLValue(E);
569
570 // Handle the vector case. The base must be a vector, the index must be an
571 // integer value.
572 Value *Base = Visit(E->getBase());
573 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000574 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedmand4531942009-03-28 03:27:06 +0000575 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
576 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000577 return Builder.CreateExtractElement(Base, Idx, "vecext");
578}
579
580/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
581/// also handle things like function to pointer-to-function decay, and array to
582/// pointer decay.
583Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
584 const Expr *Op = E->getSubExpr();
585
586 // If this is due to array->pointer conversion, emit the array expression as
587 // an l-value.
588 if (Op->getType()->isArrayType()) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000589 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000590
Eli Friedman4a0073b2009-03-28 02:45:41 +0000591 // Note that VLA pointers are always decayed, so we don't need to do
592 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000593 if (!Op->getType()->isVariableArrayType()) {
594 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
595 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
596 ->getElementType()) &&
597 "Expected pointer to array");
598 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000599 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000600
601 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000602 // types as well (e.g. void*) and can be implicitly converted to integer.
603 const llvm::Type *DestTy = ConvertType(E->getType());
604 if (V->getType() != DestTy) {
605 if (isa<llvm::PointerType>(DestTy))
606 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
607 else {
608 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
609 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
610 }
611 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000612 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000613 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000614
Chris Lattner9fba49a2007-08-24 05:35:26 +0000615 return EmitCastExpr(Op, E->getType());
616}
617
618
619// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
620// have to handle a more broad range of conversions than explicit casts, as they
621// handle things like function to ptr-to-function decay etc.
622Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000623 if (!DestTy->isVoidType())
624 TestAndClearIgnoreResultAssign();
625
Chris Lattner82e10392007-08-26 07:26:12 +0000626 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000627
628 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000629 Value *Src = Visit(const_cast<Expr*>(E));
630
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000631 // Use EmitScalarConversion to perform the conversion.
632 return EmitScalarConversion(Src, E->getType(), DestTy);
633 }
Chris Lattner77288792008-02-16 23:55:16 +0000634
Chris Lattnerde0908b2008-04-04 16:54:41 +0000635 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000636 // Handle cases where the source is a complex type.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000637 bool IgnoreImag = true;
638 bool IgnoreImagAssign = true;
639 bool IgnoreReal = IgnoreResultAssign;
640 bool IgnoreRealAssign = IgnoreResultAssign;
641 if (DestTy->isBooleanType())
642 IgnoreImagAssign = IgnoreImag = false;
643 else if (DestTy->isVoidType()) {
644 IgnoreReal = IgnoreImag = false;
645 IgnoreRealAssign = IgnoreImagAssign = true;
646 }
647 CodeGenFunction::ComplexPairTy V
648 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
649 IgnoreImagAssign);
650 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner77288792008-02-16 23:55:16 +0000651 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000652
Chris Lattner77288792008-02-16 23:55:16 +0000653 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
654 // evaluate the result and return.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000655 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner77288792008-02-16 23:55:16 +0000656 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000657}
658
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000659Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000660 return CGF.EmitCompoundStmt(*E->getSubStmt(),
661 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000662}
663
Mike Stump2b6933f2009-02-28 09:07:16 +0000664Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
665 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000666}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000667
Chris Lattner9fba49a2007-08-24 05:35:26 +0000668//===----------------------------------------------------------------------===//
669// Unary Operators
670//===----------------------------------------------------------------------===//
671
672Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000673 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000674 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000675 QualType ValTy = E->getSubExpr()->getType();
676 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000677
678 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000679
680 if (ValTy->isPointerType() &&
681 ValTy->getAsPointerType()->isVariableArrayType()) {
682 // The amount of the addition/subtraction needs to account for the VLA size
683 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
684 }
685
Chris Lattner9fba49a2007-08-24 05:35:26 +0000686 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000687 if (const llvm::PointerType *PT =
688 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner8360c612009-03-18 04:25:13 +0000689 llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
690 if (!isa<llvm::FunctionType>(PT->getElementType())) {
691 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
692 } else {
693 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
694 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
695 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
696 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
697 }
Chris Lattner49083172009-02-11 07:40:06 +0000698 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
699 // Bool++ is an interesting case, due to promotion rules, we get:
700 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
701 // Bool = ((int)Bool+1) != 0
702 // An interesting aspect of this is that increment is always true.
703 // Decrement does not have this property.
704 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner291a2b32009-06-17 06:36:24 +0000705 } else if (isa<llvm::IntegerType>(InVal->getType())) {
706 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
707 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000708 } else {
709 // Add the inc/dec to the real part.
Chris Lattner291a2b32009-06-17 06:36:24 +0000710 if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000711 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000712 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000713 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000714 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000715 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000716 else {
717 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000718 bool ignored;
719 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
720 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000721 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000722 }
Chris Lattner291a2b32009-06-17 06:36:24 +0000723 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000724 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000725
726 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000727 if (LV.isBitfield())
728 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
729 &NextVal);
730 else
731 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000732
733 // If this is a postinc, return the value read from memory, otherwise use the
734 // updated value.
735 return isPre ? NextVal : InVal;
736}
737
738
739Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000740 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000741 Value *Op = Visit(E->getSubExpr());
Chris Lattner291a2b32009-06-17 06:36:24 +0000742 if (Op->getType()->isFPOrFPVector())
743 return Builder.CreateFNeg(Op, "neg");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000744 return Builder.CreateNeg(Op, "neg");
745}
746
747Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000748 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000749 Value *Op = Visit(E->getSubExpr());
750 return Builder.CreateNot(Op, "neg");
751}
752
753Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
754 // Compare operand to zero.
755 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
756
757 // Invert value.
758 // TODO: Could dynamically modify easy computations here. For example, if
759 // the operand is an icmp ne, turn into icmp eq.
760 BoolVal = Builder.CreateNot(BoolVal, "lnot");
761
Anders Carlsson62943f32009-05-19 18:44:53 +0000762 // ZExt result to the expr type.
763 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000764}
765
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000766/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
767/// argument of the sizeof expression as an integer.
768Value *
769ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000770 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000771 if (E->isSizeOf()) {
772 if (const VariableArrayType *VAT =
773 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
774 if (E->isArgumentType()) {
775 // sizeof(type) - make sure to emit the VLA size.
776 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000777 } else {
778 // C99 6.5.3.4p2: If the argument is an expression of type
779 // VLA, it is evaluated.
780 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000781 }
Anders Carlssond309f572009-01-30 16:41:04 +0000782
Anders Carlsson8f30de92009-02-05 19:43:10 +0000783 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000784 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000785 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000786
787 // If this isn't sizeof(vla), the result must be constant; use the
788 // constant folding logic so we don't have to duplicate it here.
789 Expr::EvalResult Result;
790 E->Evaluate(Result, CGF.getContext());
791 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000792}
793
Chris Lattner01211af2007-08-24 21:20:17 +0000794Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
795 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000796 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000797 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner01211af2007-08-24 21:20:17 +0000798 return Visit(Op);
799}
800Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
801 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000802 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000803 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000804
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000805 // __imag on a scalar returns zero. Emit the subexpr to ensure side
806 // effects are evaluated, but not the actual value.
807 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
808 CGF.EmitLValue(Op);
809 else
810 CGF.EmitScalarExpr(Op, true);
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000811 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000812}
813
Anders Carlsson52774ad2008-01-29 15:56:48 +0000814Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
815{
Eli Friedman342d9432009-02-27 06:44:11 +0000816 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000817 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000818 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000819}
Chris Lattner01211af2007-08-24 21:20:17 +0000820
Chris Lattner9fba49a2007-08-24 05:35:26 +0000821//===----------------------------------------------------------------------===//
822// Binary Operators
823//===----------------------------------------------------------------------===//
824
825BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000826 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000827 BinOpInfo Result;
828 Result.LHS = Visit(E->getLHS());
829 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000830 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000831 Result.E = E;
832 return Result;
833}
834
Chris Lattner0d965302007-08-26 21:41:21 +0000835Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000836 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000837 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner660e31d2007-08-24 21:00:35 +0000838 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
839
840 BinOpInfo OpInfo;
841
Eli Friedman3cd92882009-03-28 01:22:36 +0000842 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000843 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000844 // it's a tad complicated to do that... I'm leaving it out for now.
845 // (Note that we do actually need the imaginary part of the RHS for
846 // multiplication and division.)
847 CGF.ErrorUnsupported(E, "complex compound assignment");
848 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
849 }
850
Mike Stump8d962262009-05-22 19:07:20 +0000851 // Emit the RHS first. __block variables need to have the rhs evaluated
852 // first, plus this should improve codegen a little.
853 OpInfo.RHS = Visit(E->getRHS());
854 OpInfo.Ty = E->getComputationResultType();
855 OpInfo.E = E;
Eli Friedman3cd92882009-03-28 01:22:36 +0000856 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000857 LValue LHSLV = EmitLValue(E->getLHS());
858 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000859 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
860 E->getComputationLHSType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000861
862 // Expand the binary operator.
863 Value *Result = (this->*Func)(OpInfo);
864
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000865 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000866 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
867
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000868 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000869 // handled specially because the result is altered by the store,
870 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
871 // the left operand after the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000872 if (LHSLV.isBitfield()) {
873 if (!LHSLV.isVolatileQualified()) {
874 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
875 &Result);
876 return Result;
877 } else
878 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
879 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000880 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000881 if (Ignore)
882 return 0;
883 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000884}
885
886
Chris Lattner9fba49a2007-08-24 05:35:26 +0000887Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000888 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000889 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000890 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000891 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
892 else
893 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
894}
895
896Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
897 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000898 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000899 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
900 else
901 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
902}
903
Mike Stumpdb789912009-04-01 20:28:16 +0000904Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
905 unsigned IID;
906 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000907
Mike Stumpf71b7742009-04-02 18:15:54 +0000908 switch (Ops.E->getOpcode()) {
909 case BinaryOperator::Add:
910 case BinaryOperator::AddAssign:
911 OpID = 1;
912 IID = llvm::Intrinsic::sadd_with_overflow;
913 break;
914 case BinaryOperator::Sub:
915 case BinaryOperator::SubAssign:
916 OpID = 2;
917 IID = llvm::Intrinsic::ssub_with_overflow;
918 break;
919 case BinaryOperator::Mul:
920 case BinaryOperator::MulAssign:
921 OpID = 3;
922 IID = llvm::Intrinsic::smul_with_overflow;
923 break;
924 default:
925 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000926 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000927 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000928 OpID <<= 1;
929 OpID |= 1;
930
Mike Stumpdb789912009-04-01 20:28:16 +0000931 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
932
933 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
934
935 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
936 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
937 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
938
939 // Branch in case of overflow.
940 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
941 llvm::BasicBlock *overflowBB =
942 CGF.createBasicBlock("overflow", CGF.CurFn);
943 llvm::BasicBlock *continueBB =
944 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
945
946 Builder.CreateCondBr(overflow, overflowBB, continueBB);
947
948 // Handle overflow
949
950 Builder.SetInsertPoint(overflowBB);
951
952 // Handler is:
953 // long long *__overflow_handler)(long long a, long long b, char op,
954 // char width)
955 std::vector<const llvm::Type*> handerArgTypes;
956 handerArgTypes.push_back(llvm::Type::Int64Ty);
957 handerArgTypes.push_back(llvm::Type::Int64Ty);
958 handerArgTypes.push_back(llvm::Type::Int8Ty);
959 handerArgTypes.push_back(llvm::Type::Int8Ty);
960 llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
961 handerArgTypes, false);
962 llvm::Value *handlerFunction =
963 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
964 llvm::PointerType::getUnqual(handlerTy));
965 handlerFunction = Builder.CreateLoad(handlerFunction);
966
967 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
968 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
969 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
970 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
971 llvm::ConstantInt::get(llvm::Type::Int8Ty,
972 cast<llvm::IntegerType>(opTy)->getBitWidth()));
973
974 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
975
976 Builder.CreateBr(continueBB);
977
978 // Set up the continuation
979 Builder.SetInsertPoint(continueBB);
980 // Get the correct result
981 llvm::PHINode *phi = Builder.CreatePHI(opTy);
982 phi->reserveOperandSpace(2);
983 phi->addIncoming(result, initialBB);
984 phi->addIncoming(handlerResult, overflowBB);
985
986 return phi;
987}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000988
989Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +0000990 if (!Ops.Ty->isPointerType()) {
Chris Lattner291a2b32009-06-17 06:36:24 +0000991 if (CGF.getContext().getLangOptions().OverflowChecking &&
992 Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000993 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +0000994
995 if (Ops.LHS->getType()->isFPOrFPVector())
996 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
997
Chris Lattner9fba49a2007-08-24 05:35:26 +0000998 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +0000999 }
Eli Friedman4a0073b2009-03-28 02:45:41 +00001000
1001 if (Ops.Ty->getAsPointerType()->isVariableArrayType()) {
1002 // 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;
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001007 const PointerType *PT;
1008 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001009 Ptr = Ops.LHS;
1010 Idx = Ops.RHS;
1011 IdxExp = Ops.E->getRHS();
1012 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001013 PT = Ops.E->getRHS()->getType()->getAsPointerType();
1014 assert(PT && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +00001015 Ptr = Ops.RHS;
1016 Idx = Ops.LHS;
1017 IdxExp = Ops.E->getLHS();
1018 }
1019
1020 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001021 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001022 // Zero or sign extend the pointer value based on whether the index is
1023 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001024 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +00001025 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +00001026 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1027 else
1028 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1029 }
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001030
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001031 const QualType ElementType = PT->getPointeeType();
1032 // Handle interface types, which are not represented with a concrete
1033 // type.
1034 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1035 llvm::Value *InterfaceSize =
1036 llvm::ConstantInt::get(Idx->getType(),
1037 CGF.getContext().getTypeSize(OIT) / 8);
1038 Idx = Builder.CreateMul(Idx, InterfaceSize);
1039 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1040 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1041 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1042 return Builder.CreateBitCast(Res, Ptr->getType());
1043 }
1044
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001045 // Explicitly handle GNU void* and function pointer arithmetic
1046 // extensions. The GNU void* casts amount to no-ops since our void*
1047 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001048 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1049 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1050 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001051 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001052 return Builder.CreateBitCast(Res, Ptr->getType());
1053 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001054
1055 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001056}
1057
1058Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001059 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001060 if (CGF.getContext().getLangOptions().OverflowChecking
1061 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001062 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +00001063
1064 if (Ops.LHS->getType()->isFPOrFPVector())
1065 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001066 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001067 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001068
Eli Friedman4a0073b2009-03-28 02:45:41 +00001069 if (Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
1070 // The amount of the addition needs to account for the VLA size for
1071 // ptr-int
1072 // The amount of the division needs to account for the VLA size for
1073 // ptr-ptr.
1074 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1075 }
1076
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001077 const QualType LHSType = Ops.E->getLHS()->getType();
1078 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001079 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1080 // pointer - int
1081 Value *Idx = Ops.RHS;
1082 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001083 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001084 // Zero or sign extend the pointer value based on whether the index is
1085 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001086 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001087 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1088 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1089 else
1090 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1091 }
1092 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001093
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001094 // Handle interface types, which are not represented with a concrete
1095 // type.
1096 if (const ObjCInterfaceType *OIT =
1097 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1098 llvm::Value *InterfaceSize =
1099 llvm::ConstantInt::get(Idx->getType(),
1100 CGF.getContext().getTypeSize(OIT) / 8);
1101 Idx = Builder.CreateMul(Idx, InterfaceSize);
1102 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1103 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1104 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1105 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1106 }
1107
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001108 // Explicitly handle GNU void* and function pointer arithmetic
1109 // extensions. The GNU void* casts amount to no-ops since our
1110 // void* type is i8*, but this is future proof.
1111 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1112 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1113 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1114 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1115 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1116 }
1117
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001118 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001119 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001120 // pointer - pointer
1121 Value *LHS = Ops.LHS;
1122 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001123
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001124 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001125
Chris Lattner6d2e3492009-02-11 07:21:43 +00001126 // Handle GCC extension for pointer arithmetic on void* and function pointer
1127 // types.
1128 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001129 ElementSize = 1;
1130 } else {
1131 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1132 }
1133
1134 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1135 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1136 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1137 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1138
Chris Lattner6d2e3492009-02-11 07:21:43 +00001139 // Optimize out the shift for element size of 1.
1140 if (ElementSize == 1)
1141 return BytesBetween;
1142
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001143 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1144 // remainder. As such, we handle common power-of-two cases here to generate
1145 // better code. See PR2247.
1146 if (llvm::isPowerOf2_64(ElementSize)) {
1147 Value *ShAmt =
1148 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1149 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1150 }
1151
1152 // Otherwise, do a full sdiv.
1153 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1154 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001155 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001156}
1157
1158Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1159 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1160 // RHS to the same size as the LHS.
1161 Value *RHS = Ops.RHS;
1162 if (Ops.LHS->getType() != RHS->getType())
1163 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1164
1165 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1166}
1167
1168Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1169 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1170 // RHS to the same size as the LHS.
1171 Value *RHS = Ops.RHS;
1172 if (Ops.LHS->getType() != RHS->getType())
1173 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1174
Chris Lattner660e31d2007-08-24 21:00:35 +00001175 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001176 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1177 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1178}
1179
1180Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1181 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001182 TestAndClearIgnoreResultAssign();
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001183 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001184 QualType LHSTy = E->getLHS()->getType();
Chris Lattner08ac8522009-07-08 01:08:03 +00001185 if (!LHSTy->isAnyComplexType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001186 Value *LHS = Visit(E->getLHS());
1187 Value *RHS = Visit(E->getRHS());
1188
1189 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001190 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001191 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001192 } else if (LHSTy->isSignedIntegerType()) {
1193 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001194 LHS, RHS, "cmp");
1195 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001196 // Unsigned integers and pointers.
1197 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001198 LHS, RHS, "cmp");
1199 }
Chris Lattner08ac8522009-07-08 01:08:03 +00001200
1201 // If this is a vector comparison, sign extend the result to the appropriate
1202 // vector integer type and return it (don't convert to bool).
1203 if (LHSTy->isVectorType())
1204 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman1591bc52008-07-25 20:16:05 +00001205
Chris Lattner9fba49a2007-08-24 05:35:26 +00001206 } else {
1207 // Complex Comparison: can only be an equality comparison.
1208 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1209 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1210
Chris Lattnerc154ac12008-07-26 22:37:01 +00001211 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001212
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001213 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001214 if (CETy->isRealFloatingType()) {
1215 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1216 LHS.first, RHS.first, "cmp.r");
1217 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1218 LHS.second, RHS.second, "cmp.i");
1219 } else {
1220 // Complex comparisons can only be equality comparisons. As such, signed
1221 // and unsigned opcodes are the same.
1222 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1223 LHS.first, RHS.first, "cmp.r");
1224 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1225 LHS.second, RHS.second, "cmp.i");
1226 }
1227
1228 if (E->getOpcode() == BinaryOperator::EQ) {
1229 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1230 } else {
1231 assert(E->getOpcode() == BinaryOperator::NE &&
1232 "Complex comparison other than == or != ?");
1233 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1234 }
1235 }
Nuno Lopes92577002009-01-11 23:22:37 +00001236
1237 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001238}
1239
1240Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001241 bool Ignore = TestAndClearIgnoreResultAssign();
1242
1243 // __block variables need to have the rhs evaluated first, plus this should
1244 // improve codegen just a little.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001245 Value *RHS = Visit(E->getRHS());
Mike Stump68df15c2009-05-21 21:05:15 +00001246 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001247
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001248 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001249 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1250 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001251 // the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001252 if (LHS.isBitfield()) {
1253 if (!LHS.isVolatileQualified()) {
1254 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1255 &RHS);
1256 return RHS;
1257 } else
1258 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1259 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001260 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001261 if (Ignore)
1262 return 0;
1263 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001264}
1265
1266Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001267 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1268 // If we have 1 && X, just emit X without inserting the control flow.
1269 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1270 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001271 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1272 // ZExt result to int.
1273 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1274 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001275
1276 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1277 if (!CGF.ContainsLabel(E->getRHS()))
1278 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001279 }
1280
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001281 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1282 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001283
Chris Lattner7f80bb32008-11-12 08:38:24 +00001284 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1285 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1286
1287 // Any edges into the ContBlock are now from an (indeterminate number of)
1288 // edges from this first condition. All of these values will be false. Start
1289 // setting up the PHI node in the Cont Block for this.
1290 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1291 PN->reserveOperandSpace(2); // Normal case, two inputs.
1292 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1293 PI != PE; ++PI)
1294 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001295
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001296 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001297 CGF.EmitBlock(RHSBlock);
1298 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001299 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001300
1301 // Reaquire the RHS block, as there may be subblocks inserted.
1302 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001303
1304 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1305 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001306 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001307 PN->addIncoming(RHSCond, RHSBlock);
1308
1309 // ZExt result to int.
1310 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1311}
1312
1313Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001314 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1315 // If we have 0 || X, just emit X without inserting the control flow.
1316 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1317 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001318 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1319 // ZExt result to int.
1320 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1321 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001322
Eli Friedmanea137cd2008-12-02 16:02:46 +00001323 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001324 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001325 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001326 }
1327
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001328 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1329 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001330
Chris Lattner7f80bb32008-11-12 08:38:24 +00001331 // Branch on the LHS first. If it is true, go to the success (cont) block.
1332 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1333
1334 // Any edges into the ContBlock are now from an (indeterminate number of)
1335 // edges from this first condition. All of these values will be true. Start
1336 // setting up the PHI node in the Cont Block for this.
1337 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1338 PN->reserveOperandSpace(2); // Normal case, two inputs.
1339 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1340 PI != PE; ++PI)
1341 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1342
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001343 CGF.PushConditionalTempDestruction();
1344
Chris Lattner7f80bb32008-11-12 08:38:24 +00001345 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001346 CGF.EmitBlock(RHSBlock);
1347 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1348
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001349 CGF.PopConditionalTempDestruction();
1350
Chris Lattner9fba49a2007-08-24 05:35:26 +00001351 // Reaquire the RHS block, as there may be subblocks inserted.
1352 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001353
Chris Lattner7f80bb32008-11-12 08:38:24 +00001354 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1355 // into the phi node for the edge with the value of RHSCond.
1356 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001357 PN->addIncoming(RHSCond, RHSBlock);
1358
1359 // ZExt result to int.
1360 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1361}
1362
1363Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1364 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001365 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001366 return Visit(E->getRHS());
1367}
1368
1369//===----------------------------------------------------------------------===//
1370// Other Operators
1371//===----------------------------------------------------------------------===//
1372
Chris Lattner504a5282008-11-12 08:55:54 +00001373/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1374/// expression is cheap enough and side-effect-free enough to evaluate
1375/// unconditionally instead of conditionally. This is used to convert control
1376/// flow into selects in some cases.
1377static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1378 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1379 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1380
1381 // TODO: Allow anything we can constant fold to an integer or fp constant.
1382 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1383 isa<FloatingLiteral>(E))
1384 return true;
1385
1386 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1387 // X and Y are local variables.
1388 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1389 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1390 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1391 return true;
1392
1393 return false;
1394}
1395
1396
Chris Lattner9fba49a2007-08-24 05:35:26 +00001397Value *ScalarExprEmitter::
1398VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001399 TestAndClearIgnoreResultAssign();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001400 // If the condition constant folds and can be elided, try to avoid emitting
1401 // the condition and the dead arm.
1402 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001403 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001404 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001405 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001406
1407 // If the dead side doesn't have labels we need, and if the Live side isn't
1408 // the gnu missing ?: extension (which we could handle, but don't bother
1409 // to), just emit the Live part.
1410 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1411 Live) // Live part isn't missing.
1412 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001413 }
1414
Chris Lattner504a5282008-11-12 08:55:54 +00001415
1416 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1417 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001418 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001419 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1420 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1421 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1422 llvm::Value *LHS = Visit(E->getLHS());
1423 llvm::Value *RHS = Visit(E->getRHS());
1424 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1425 }
1426
1427
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001428 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1429 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001430 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001431 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001432
Chris Lattner86031712009-02-13 23:35:32 +00001433 // If we don't have the GNU missing condition extension, emit a branch on
1434 // bool the normal way.
1435 if (E->getLHS()) {
1436 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1437 // the branch on bool.
1438 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1439 } else {
1440 // Otherwise, for the ?: extension, evaluate the conditional and then
1441 // convert it to bool the hard way. We do this explicitly because we need
1442 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001443 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001444
1445 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1446 // if there are no extra uses (an optimization). Inhibit this by making an
1447 // extra dead use, because we're going to add a use of CondVal later. We
1448 // don't use the builder for this, because we don't want it to get optimized
1449 // away. This leaves dead code, but the ?: extension isn't common.
1450 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1451 Builder.GetInsertBlock());
1452
Chris Lattner67e22462008-11-12 08:08:13 +00001453 Value *CondBoolVal =
1454 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1455 CGF.getContext().BoolTy);
1456 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001457 }
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001458
1459 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001460 CGF.EmitBlock(LHSBlock);
1461
1462 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001463 Value *LHS;
1464 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001465 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001466 else // Perform promotions, to handle cases like "short ?: int"
1467 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1468
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001469 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001470 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001471 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001472
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001473 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001474 CGF.EmitBlock(RHSBlock);
1475
Eli Friedmance8d7032008-05-16 20:38:39 +00001476 Value *RHS = Visit(E->getRHS());
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001477 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001478 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001479 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001480
1481 CGF.EmitBlock(ContBlock);
1482
Nuno Lopesb62ff242008-06-04 19:15:45 +00001483 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001484 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1485 return 0;
1486 }
1487
Chris Lattner9fba49a2007-08-24 05:35:26 +00001488 // Create a PHI node for the real part.
1489 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1490 PN->reserveOperandSpace(2);
1491 PN->addIncoming(LHS, LHSBlock);
1492 PN->addIncoming(RHS, RHSBlock);
1493 return PN;
1494}
1495
1496Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001497 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001498}
1499
Chris Lattner307da022007-11-30 17:56:23 +00001500Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001501 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001502 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1503
1504 // If EmitVAArg fails, we fall back to the LLVM instruction.
1505 if (!ArgPtr)
1506 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1507
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001508 // FIXME Volatility.
Anders Carlsson285611e2008-11-04 05:30:00 +00001509 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001510}
1511
Mike Stump4eb81dc2009-02-12 18:29:15 +00001512Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001513 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001514}
1515
Chris Lattner9fba49a2007-08-24 05:35:26 +00001516//===----------------------------------------------------------------------===//
1517// Entry Point into this File
1518//===----------------------------------------------------------------------===//
1519
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001520/// EmitScalarExpr - Emit the computation of the specified expression of
1521/// scalar type, ignoring the result.
1522Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001523 assert(E && !hasAggregateLLVMType(E->getType()) &&
1524 "Invalid scalar expression to emit");
1525
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001526 return ScalarExprEmitter(*this, IgnoreResultAssign)
1527 .Visit(const_cast<Expr*>(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001528}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001529
1530/// EmitScalarConversion - Emit a conversion from the specified type to the
1531/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001532Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1533 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001534 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1535 "Invalid scalar expression to emit");
1536 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1537}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001538
1539/// EmitComplexToScalarConversion - Emit a conversion from the specified
1540/// complex type to the specified destination type, where the destination
1541/// type is an LLVM scalar type.
1542Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1543 QualType SrcTy,
1544 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001545 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001546 "Invalid complex -> scalar conversion");
1547 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1548 DstTy);
1549}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001550
1551Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1552 assert(V1->getType() == V2->getType() &&
1553 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001554 unsigned NumElements =
1555 cast<llvm::VectorType>(V1->getType())->getNumElements();
1556
1557 va_list va;
1558 va_start(va, V2);
1559
1560 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001561 for (unsigned i = 0; i < NumElements; i++) {
1562 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001563 assert(n >= 0 && n < (int)NumElements * 2 &&
1564 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001565 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1566 }
1567
1568 const char *Name = va_arg(va, const char *);
1569 va_end(va);
1570
1571 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1572
1573 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1574}
1575
Anders Carlsson68b8be92007-12-15 21:23:30 +00001576llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001577 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001578 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001579 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001580
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001581 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001582 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001583 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001584 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001585 }
1586
1587 return Vec;
1588}