blob: 958aa9361cc04c554f182023bca122bb3b12b21a [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 Lattnercbfb5512008-03-01 08:45:05 +000052
Chris Lattner9fba49a2007-08-24 05:35:26 +000053public:
54
Mike Stumpb8fc73e2009-05-29 15:46:01 +000055 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
56 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000057 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000058
59 //===--------------------------------------------------------------------===//
60 // Utilities
61 //===--------------------------------------------------------------------===//
62
Mike Stumpb8fc73e2009-05-29 15:46:01 +000063 bool TestAndClearIgnoreResultAssign() {
64 bool I = IgnoreResultAssign; IgnoreResultAssign = false;
65 return I; }
66
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) {
121 return llvm::Constant::getNullValue(ConvertType(E->getType()));
122 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000123 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
124 return llvm::Constant::getNullValue(ConvertType(E->getType()));
125 }
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);
213 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
214 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) {
221 return llvm::Constant::getNullValue(ConvertType(E->getType()));
222 }
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) {
286 // FIXME: Do something with the temporaries!
287 return Visit(E->getSubExpr());
288 }
289
Chris Lattner9fba49a2007-08-24 05:35:26 +0000290 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000291 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000292 if (CGF.getContext().getLangOptions().OverflowChecking
293 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000294 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000295 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
296 }
Mike Stumpdb789912009-04-01 20:28:16 +0000297 /// Create a binary op that checks for overflow.
298 /// Currently only supports +, - and *.
299 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000300 Value *EmitDiv(const BinOpInfo &Ops);
301 Value *EmitRem(const BinOpInfo &Ops);
302 Value *EmitAdd(const BinOpInfo &Ops);
303 Value *EmitSub(const BinOpInfo &Ops);
304 Value *EmitShl(const BinOpInfo &Ops);
305 Value *EmitShr(const BinOpInfo &Ops);
306 Value *EmitAnd(const BinOpInfo &Ops) {
307 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
308 }
309 Value *EmitXor(const BinOpInfo &Ops) {
310 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
311 }
312 Value *EmitOr (const BinOpInfo &Ops) {
313 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
314 }
315
Chris Lattner660e31d2007-08-24 21:00:35 +0000316 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000317 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000318 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
319
320 // Binary operators and binary compound assignment operators.
321#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000322 Value *VisitBin ## OP(const BinaryOperator *E) { \
323 return Emit ## OP(EmitBinOps(E)); \
324 } \
325 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
326 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000327 }
328 HANDLEBINOP(Mul);
329 HANDLEBINOP(Div);
330 HANDLEBINOP(Rem);
331 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000332 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000333 HANDLEBINOP(Shl);
334 HANDLEBINOP(Shr);
335 HANDLEBINOP(And);
336 HANDLEBINOP(Xor);
337 HANDLEBINOP(Or);
338#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000339
Chris Lattner9fba49a2007-08-24 05:35:26 +0000340 // Comparisons.
341 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
342 unsigned SICmpOpc, unsigned FCmpOpc);
343#define VISITCOMP(CODE, UI, SI, FP) \
344 Value *VisitBin##CODE(const BinaryOperator *E) { \
345 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
346 llvm::FCmpInst::FP); }
347 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
348 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
349 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
350 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
351 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
352 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
353#undef VISITCOMP
354
355 Value *VisitBinAssign (const BinaryOperator *E);
356
357 Value *VisitBinLAnd (const BinaryOperator *E);
358 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000359 Value *VisitBinComma (const BinaryOperator *E);
360
361 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000362 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000363 Value *VisitConditionalOperator(const ConditionalOperator *CO);
364 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000365 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000366 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
367 return CGF.EmitObjCStringLiteral(E);
368 }
369};
370} // end anonymous namespace.
371
372//===----------------------------------------------------------------------===//
373// Utilities
374//===----------------------------------------------------------------------===//
375
Chris Lattnerd8d44222007-08-26 16:42:57 +0000376/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000377/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000378Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
379 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
380
381 if (SrcType->isRealFloatingType()) {
382 // Compare against 0.0 for fp scalars.
383 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000384 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
385 }
386
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000387 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000388 "Unknown scalar type to convert");
389
390 // Because of the type rules of C, we often end up computing a logical value,
391 // then zero extending it to int, then wanting it as a logical value again.
392 // Optimize this common case.
393 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
394 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
395 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000396 // If there aren't any more uses, zap the instruction to save space.
397 // Note that there can be more uses, for example if this
398 // is the result of an assignment.
399 if (ZI->use_empty())
400 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000401 return Result;
402 }
403 }
404
405 // Compare against an integer or pointer null.
406 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
407 return Builder.CreateICmpNE(Src, Zero, "tobool");
408}
409
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000410/// EmitScalarConversion - Emit a conversion from the specified type to the
411/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000412Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
413 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000414 SrcType = CGF.getContext().getCanonicalType(SrcType);
415 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000416 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000417
418 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000419
420 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000421 if (DstType->isBooleanType())
422 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000423
424 const llvm::Type *DstTy = ConvertType(DstType);
425
426 // Ignore conversions like int -> uint.
427 if (Src->getType() == DstTy)
428 return Src;
429
Daniel Dunbar238335f2008-08-25 09:51:32 +0000430 // Handle pointer conversions next: pointers can only be converted
431 // to/from other pointers and integers. Check for pointer types in
432 // terms of LLVM, as some native types (like Obj-C id) may map to a
433 // pointer type.
434 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000435 // The source value may be an integer, or a pointer.
436 if (isa<llvm::PointerType>(Src->getType()))
437 return Builder.CreateBitCast(Src, DstTy, "conv");
438 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000439 // First, convert to the correct width so that we control the kind of
440 // extension.
441 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
442 bool InputSigned = SrcType->isSignedIntegerType();
443 llvm::Value* IntResult =
444 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
445 // Then, cast to pointer.
446 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000447 }
448
Daniel Dunbar238335f2008-08-25 09:51:32 +0000449 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000450 // Must be an ptr to int cast.
451 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000452 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000453 }
454
Nate Begemanaf6ed502008-04-18 23:10:10 +0000455 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000456 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
457 // Cast the scalar to element type
458 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
459 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
460
461 // Insert the element in element zero of an undef vector
462 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
463 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
464 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
465
466 // Splat the element across to all elements
467 llvm::SmallVector<llvm::Constant*, 16> Args;
468 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
469 for (unsigned i = 0; i < NumElements; i++)
470 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
471
472 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
473 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
474 return Yay;
475 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000476
Chris Lattner4f025a42008-02-02 04:51:41 +0000477 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000478 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000479 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000480 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000481
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000482 // Finally, we have the arithmetic types: real int/float.
483 if (isa<llvm::IntegerType>(Src->getType())) {
484 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000485 if (isa<llvm::IntegerType>(DstTy))
486 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
487 else if (InputSigned)
488 return Builder.CreateSIToFP(Src, DstTy, "conv");
489 else
490 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000491 }
492
493 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
494 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000495 if (DstType->isSignedIntegerType())
496 return Builder.CreateFPToSI(Src, DstTy, "conv");
497 else
498 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000499 }
500
501 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000502 if (DstTy->getTypeID() < Src->getType()->getTypeID())
503 return Builder.CreateFPTrunc(Src, DstTy, "conv");
504 else
505 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000506}
507
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000508/// EmitComplexToScalarConversion - Emit a conversion from the specified
509/// complex type to the specified destination type, where the destination
510/// type is an LLVM scalar type.
511Value *ScalarExprEmitter::
512EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
513 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000514 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000515 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000516
517 // Handle conversions to bool first, they are special: comparisons against 0.
518 if (DstTy->isBooleanType()) {
519 // Complex != 0 -> (Real != 0) | (Imag != 0)
520 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
521 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
522 return Builder.CreateOr(Src.first, Src.second, "tobool");
523 }
524
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000525 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
526 // the imaginary part of the complex value is discarded and the value of the
527 // real part is converted according to the conversion rules for the
528 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000529 return EmitScalarConversion(Src.first, SrcTy, DstTy);
530}
531
532
Chris Lattner9fba49a2007-08-24 05:35:26 +0000533//===----------------------------------------------------------------------===//
534// Visitor Methods
535//===----------------------------------------------------------------------===//
536
537Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000538 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000539 if (E->getType()->isVoidType())
540 return 0;
541 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
542}
543
Eli Friedmand0e9d092008-05-14 19:38:39 +0000544Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
545 llvm::SmallVector<llvm::Constant*, 32> indices;
546 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
547 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
548 }
549 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
550 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
551 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
552 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
553}
554
Chris Lattner9fba49a2007-08-24 05:35:26 +0000555Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000556 TestAndClearIgnoreResultAssign();
557
Chris Lattner9fba49a2007-08-24 05:35:26 +0000558 // Emit subscript expressions in rvalue context's. For most cases, this just
559 // loads the lvalue formed by the subscript expr. However, we have to be
560 // careful, because the base of a vector subscript is occasionally an rvalue,
561 // so we can't get it as an lvalue.
562 if (!E->getBase()->getType()->isVectorType())
563 return EmitLoadOfLValue(E);
564
565 // Handle the vector case. The base must be a vector, the index must be an
566 // integer value.
567 Value *Base = Visit(E->getBase());
568 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000569 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedmand4531942009-03-28 03:27:06 +0000570 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
571 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000572 return Builder.CreateExtractElement(Base, Idx, "vecext");
573}
574
575/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
576/// also handle things like function to pointer-to-function decay, and array to
577/// pointer decay.
578Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
579 const Expr *Op = E->getSubExpr();
580
581 // If this is due to array->pointer conversion, emit the array expression as
582 // an l-value.
583 if (Op->getType()->isArrayType()) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000584 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000585
Eli Friedman4a0073b2009-03-28 02:45:41 +0000586 // Note that VLA pointers are always decayed, so we don't need to do
587 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000588 if (!Op->getType()->isVariableArrayType()) {
589 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
590 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
591 ->getElementType()) &&
592 "Expected pointer to array");
593 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000594 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000595
596 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000597 // types as well (e.g. void*) and can be implicitly converted to integer.
598 const llvm::Type *DestTy = ConvertType(E->getType());
599 if (V->getType() != DestTy) {
600 if (isa<llvm::PointerType>(DestTy))
601 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
602 else {
603 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
604 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
605 }
606 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000607 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000608 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000609
Chris Lattner9fba49a2007-08-24 05:35:26 +0000610 return EmitCastExpr(Op, E->getType());
611}
612
613
614// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
615// have to handle a more broad range of conversions than explicit casts, as they
616// handle things like function to ptr-to-function decay etc.
617Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000618 if (!DestTy->isVoidType())
619 TestAndClearIgnoreResultAssign();
620
Chris Lattner82e10392007-08-26 07:26:12 +0000621 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000622
623 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000624 Value *Src = Visit(const_cast<Expr*>(E));
625
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000626 // Use EmitScalarConversion to perform the conversion.
627 return EmitScalarConversion(Src, E->getType(), DestTy);
628 }
Chris Lattner77288792008-02-16 23:55:16 +0000629
Chris Lattnerde0908b2008-04-04 16:54:41 +0000630 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000631 // Handle cases where the source is a complex type.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000632 bool IgnoreImag = true;
633 bool IgnoreImagAssign = true;
634 bool IgnoreReal = IgnoreResultAssign;
635 bool IgnoreRealAssign = IgnoreResultAssign;
636 if (DestTy->isBooleanType())
637 IgnoreImagAssign = IgnoreImag = false;
638 else if (DestTy->isVoidType()) {
639 IgnoreReal = IgnoreImag = false;
640 IgnoreRealAssign = IgnoreImagAssign = true;
641 }
642 CodeGenFunction::ComplexPairTy V
643 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
644 IgnoreImagAssign);
645 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner77288792008-02-16 23:55:16 +0000646 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000647
Chris Lattner77288792008-02-16 23:55:16 +0000648 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
649 // evaluate the result and return.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000650 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner77288792008-02-16 23:55:16 +0000651 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000652}
653
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000654Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000655 return CGF.EmitCompoundStmt(*E->getSubStmt(),
656 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000657}
658
Mike Stump2b6933f2009-02-28 09:07:16 +0000659Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
660 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000661}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000662
Chris Lattner9fba49a2007-08-24 05:35:26 +0000663//===----------------------------------------------------------------------===//
664// Unary Operators
665//===----------------------------------------------------------------------===//
666
667Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000668 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000669 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000670 QualType ValTy = E->getSubExpr()->getType();
671 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000672
673 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000674
675 if (ValTy->isPointerType() &&
676 ValTy->getAsPointerType()->isVariableArrayType()) {
677 // The amount of the addition/subtraction needs to account for the VLA size
678 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
679 }
680
Chris Lattner9fba49a2007-08-24 05:35:26 +0000681 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000682 if (const llvm::PointerType *PT =
683 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner8360c612009-03-18 04:25:13 +0000684 llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
685 if (!isa<llvm::FunctionType>(PT->getElementType())) {
686 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
687 } else {
688 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
689 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
690 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
691 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
692 }
Chris Lattner49083172009-02-11 07:40:06 +0000693 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
694 // Bool++ is an interesting case, due to promotion rules, we get:
695 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
696 // Bool = ((int)Bool+1) != 0
697 // An interesting aspect of this is that increment is always true.
698 // Decrement does not have this property.
699 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner0dc11f62007-08-26 05:10:16 +0000700 } else {
701 // Add the inc/dec to the real part.
702 if (isa<llvm::IntegerType>(InVal->getType()))
703 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000704 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000705 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000706 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000707 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000708 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000709 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000710 else {
711 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000712 bool ignored;
713 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
714 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000715 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000716 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000717 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
718 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000719
720 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000721 if (LV.isBitfield())
722 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
723 &NextVal);
724 else
725 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000726
727 // If this is a postinc, return the value read from memory, otherwise use the
728 // updated value.
729 return isPre ? NextVal : InVal;
730}
731
732
733Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000734 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000735 Value *Op = Visit(E->getSubExpr());
736 return Builder.CreateNeg(Op, "neg");
737}
738
739Value *ScalarExprEmitter::VisitUnaryNot(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());
742 return Builder.CreateNot(Op, "neg");
743}
744
745Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
746 // Compare operand to zero.
747 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
748
749 // Invert value.
750 // TODO: Could dynamically modify easy computations here. For example, if
751 // the operand is an icmp ne, turn into icmp eq.
752 BoolVal = Builder.CreateNot(BoolVal, "lnot");
753
Anders Carlsson62943f32009-05-19 18:44:53 +0000754 // ZExt result to the expr type.
755 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000756}
757
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000758/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
759/// argument of the sizeof expression as an integer.
760Value *
761ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000762 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000763 if (E->isSizeOf()) {
764 if (const VariableArrayType *VAT =
765 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
766 if (E->isArgumentType()) {
767 // sizeof(type) - make sure to emit the VLA size.
768 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000769 } else {
770 // C99 6.5.3.4p2: If the argument is an expression of type
771 // VLA, it is evaluated.
772 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000773 }
Anders Carlssond309f572009-01-30 16:41:04 +0000774
Anders Carlsson8f30de92009-02-05 19:43:10 +0000775 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000776 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000777 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000778
779 // If this isn't sizeof(vla), the result must be constant; use the
780 // constant folding logic so we don't have to duplicate it here.
781 Expr::EvalResult Result;
782 E->Evaluate(Result, CGF.getContext());
783 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000784}
785
Chris Lattner01211af2007-08-24 21:20:17 +0000786Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
787 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000788 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000789 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner01211af2007-08-24 21:20:17 +0000790 return Visit(Op);
791}
792Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
793 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000794 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000795 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000796
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000797 // __imag on a scalar returns zero. Emit the subexpr to ensure side
798 // effects are evaluated, but not the actual value.
799 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
800 CGF.EmitLValue(Op);
801 else
802 CGF.EmitScalarExpr(Op, true);
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000803 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000804}
805
Anders Carlsson52774ad2008-01-29 15:56:48 +0000806Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
807{
Eli Friedman342d9432009-02-27 06:44:11 +0000808 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000809 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000810 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000811}
Chris Lattner01211af2007-08-24 21:20:17 +0000812
Chris Lattner9fba49a2007-08-24 05:35:26 +0000813//===----------------------------------------------------------------------===//
814// Binary Operators
815//===----------------------------------------------------------------------===//
816
817BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000818 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000819 BinOpInfo Result;
820 Result.LHS = Visit(E->getLHS());
821 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000822 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000823 Result.E = E;
824 return Result;
825}
826
Chris Lattner0d965302007-08-26 21:41:21 +0000827Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000828 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000829 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner660e31d2007-08-24 21:00:35 +0000830 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
831
832 BinOpInfo OpInfo;
833
Eli Friedman3cd92882009-03-28 01:22:36 +0000834 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000835 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000836 // it's a tad complicated to do that... I'm leaving it out for now.
837 // (Note that we do actually need the imaginary part of the RHS for
838 // multiplication and division.)
839 CGF.ErrorUnsupported(E, "complex compound assignment");
840 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
841 }
842
Mike Stump8d962262009-05-22 19:07:20 +0000843 // Emit the RHS first. __block variables need to have the rhs evaluated
844 // first, plus this should improve codegen a little.
845 OpInfo.RHS = Visit(E->getRHS());
846 OpInfo.Ty = E->getComputationResultType();
847 OpInfo.E = E;
Eli Friedman3cd92882009-03-28 01:22:36 +0000848 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000849 LValue LHSLV = EmitLValue(E->getLHS());
850 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000851 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
852 E->getComputationLHSType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000853
854 // Expand the binary operator.
855 Value *Result = (this->*Func)(OpInfo);
856
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000857 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000858 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
859
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000860 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000861 // handled specially because the result is altered by the store,
862 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
863 // the left operand after the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000864 if (LHSLV.isBitfield()) {
865 if (!LHSLV.isVolatileQualified()) {
866 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
867 &Result);
868 return Result;
869 } else
870 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
871 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000872 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000873 if (Ignore)
874 return 0;
875 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000876}
877
878
Chris Lattner9fba49a2007-08-24 05:35:26 +0000879Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000880 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000881 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000882 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000883 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
884 else
885 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
886}
887
888Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
889 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000890 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000891 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
892 else
893 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
894}
895
Mike Stumpdb789912009-04-01 20:28:16 +0000896Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
897 unsigned IID;
898 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000899
Mike Stumpf71b7742009-04-02 18:15:54 +0000900 switch (Ops.E->getOpcode()) {
901 case BinaryOperator::Add:
902 case BinaryOperator::AddAssign:
903 OpID = 1;
904 IID = llvm::Intrinsic::sadd_with_overflow;
905 break;
906 case BinaryOperator::Sub:
907 case BinaryOperator::SubAssign:
908 OpID = 2;
909 IID = llvm::Intrinsic::ssub_with_overflow;
910 break;
911 case BinaryOperator::Mul:
912 case BinaryOperator::MulAssign:
913 OpID = 3;
914 IID = llvm::Intrinsic::smul_with_overflow;
915 break;
916 default:
917 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000918 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000919 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000920 OpID <<= 1;
921 OpID |= 1;
922
Mike Stumpdb789912009-04-01 20:28:16 +0000923 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
924
925 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
926
927 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
928 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
929 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
930
931 // Branch in case of overflow.
932 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
933 llvm::BasicBlock *overflowBB =
934 CGF.createBasicBlock("overflow", CGF.CurFn);
935 llvm::BasicBlock *continueBB =
936 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
937
938 Builder.CreateCondBr(overflow, overflowBB, continueBB);
939
940 // Handle overflow
941
942 Builder.SetInsertPoint(overflowBB);
943
944 // Handler is:
945 // long long *__overflow_handler)(long long a, long long b, char op,
946 // char width)
947 std::vector<const llvm::Type*> handerArgTypes;
948 handerArgTypes.push_back(llvm::Type::Int64Ty);
949 handerArgTypes.push_back(llvm::Type::Int64Ty);
950 handerArgTypes.push_back(llvm::Type::Int8Ty);
951 handerArgTypes.push_back(llvm::Type::Int8Ty);
952 llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
953 handerArgTypes, false);
954 llvm::Value *handlerFunction =
955 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
956 llvm::PointerType::getUnqual(handlerTy));
957 handlerFunction = Builder.CreateLoad(handlerFunction);
958
959 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
960 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
961 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
962 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
963 llvm::ConstantInt::get(llvm::Type::Int8Ty,
964 cast<llvm::IntegerType>(opTy)->getBitWidth()));
965
966 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
967
968 Builder.CreateBr(continueBB);
969
970 // Set up the continuation
971 Builder.SetInsertPoint(continueBB);
972 // Get the correct result
973 llvm::PHINode *phi = Builder.CreatePHI(opTy);
974 phi->reserveOperandSpace(2);
975 phi->addIncoming(result, initialBB);
976 phi->addIncoming(handlerResult, overflowBB);
977
978 return phi;
979}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000980
981Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +0000982 if (!Ops.Ty->isPointerType()) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000983 if (CGF.getContext().getLangOptions().OverflowChecking
984 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000985 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000986 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +0000987 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000988
989 if (Ops.Ty->getAsPointerType()->isVariableArrayType()) {
990 // The amount of the addition needs to account for the VLA size
991 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
992 }
Chris Lattner17c0cb02008-01-03 06:36:51 +0000993 Value *Ptr, *Idx;
994 Expr *IdxExp;
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000995 const PointerType *PT;
996 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000997 Ptr = Ops.LHS;
998 Idx = Ops.RHS;
999 IdxExp = Ops.E->getRHS();
1000 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001001 PT = Ops.E->getRHS()->getType()->getAsPointerType();
1002 assert(PT && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +00001003 Ptr = Ops.RHS;
1004 Idx = Ops.LHS;
1005 IdxExp = Ops.E->getLHS();
1006 }
1007
1008 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001009 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001010 // Zero or sign extend the pointer value based on whether the index is
1011 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001012 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +00001013 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +00001014 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1015 else
1016 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1017 }
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001018
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001019 const QualType ElementType = PT->getPointeeType();
1020 // Handle interface types, which are not represented with a concrete
1021 // type.
1022 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1023 llvm::Value *InterfaceSize =
1024 llvm::ConstantInt::get(Idx->getType(),
1025 CGF.getContext().getTypeSize(OIT) / 8);
1026 Idx = Builder.CreateMul(Idx, InterfaceSize);
1027 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1028 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1029 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1030 return Builder.CreateBitCast(Res, Ptr->getType());
1031 }
1032
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001033 // Explicitly handle GNU void* and function pointer arithmetic
1034 // extensions. The GNU void* casts amount to no-ops since our void*
1035 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001036 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1037 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1038 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001039 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001040 return Builder.CreateBitCast(Res, Ptr->getType());
1041 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001042
1043 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001044}
1045
1046Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001047 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001048 if (CGF.getContext().getLangOptions().OverflowChecking
1049 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001050 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001051 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001052 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001053
Eli Friedman4a0073b2009-03-28 02:45:41 +00001054 if (Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
1055 // The amount of the addition needs to account for the VLA size for
1056 // ptr-int
1057 // The amount of the division needs to account for the VLA size for
1058 // ptr-ptr.
1059 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1060 }
1061
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001062 const QualType LHSType = Ops.E->getLHS()->getType();
1063 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001064 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1065 // pointer - int
1066 Value *Idx = Ops.RHS;
1067 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001068 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001069 // Zero or sign extend the pointer value based on whether the index is
1070 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001071 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001072 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1073 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1074 else
1075 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1076 }
1077 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001078
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001079 // Handle interface types, which are not represented with a concrete
1080 // type.
1081 if (const ObjCInterfaceType *OIT =
1082 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1083 llvm::Value *InterfaceSize =
1084 llvm::ConstantInt::get(Idx->getType(),
1085 CGF.getContext().getTypeSize(OIT) / 8);
1086 Idx = Builder.CreateMul(Idx, InterfaceSize);
1087 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1088 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1089 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1090 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1091 }
1092
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001093 // Explicitly handle GNU void* and function pointer arithmetic
1094 // extensions. The GNU void* casts amount to no-ops since our
1095 // void* type is i8*, but this is future proof.
1096 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1097 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1098 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1099 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1100 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1101 }
1102
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001103 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001104 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001105 // pointer - pointer
1106 Value *LHS = Ops.LHS;
1107 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001108
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001109 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001110
Chris Lattner6d2e3492009-02-11 07:21:43 +00001111 // Handle GCC extension for pointer arithmetic on void* and function pointer
1112 // types.
1113 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001114 ElementSize = 1;
1115 } else {
1116 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1117 }
1118
1119 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1120 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1121 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1122 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1123
Chris Lattner6d2e3492009-02-11 07:21:43 +00001124 // Optimize out the shift for element size of 1.
1125 if (ElementSize == 1)
1126 return BytesBetween;
1127
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001128 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1129 // remainder. As such, we handle common power-of-two cases here to generate
1130 // better code. See PR2247.
1131 if (llvm::isPowerOf2_64(ElementSize)) {
1132 Value *ShAmt =
1133 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1134 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1135 }
1136
1137 // Otherwise, do a full sdiv.
1138 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1139 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001140 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001141}
1142
1143Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1144 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1145 // RHS to the same size as the LHS.
1146 Value *RHS = Ops.RHS;
1147 if (Ops.LHS->getType() != RHS->getType())
1148 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1149
1150 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1151}
1152
1153Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1154 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1155 // RHS to the same size as the LHS.
1156 Value *RHS = Ops.RHS;
1157 if (Ops.LHS->getType() != RHS->getType())
1158 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1159
Chris Lattner660e31d2007-08-24 21:00:35 +00001160 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001161 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1162 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1163}
1164
1165Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1166 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001167 TestAndClearIgnoreResultAssign();
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001168 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001169 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +00001170 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001171 Value *LHS = Visit(E->getLHS());
1172 Value *RHS = Visit(E->getRHS());
1173
1174 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001175 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001176 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001177 } else if (LHSTy->isSignedIntegerType()) {
1178 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001179 LHS, RHS, "cmp");
1180 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001181 // Unsigned integers and pointers.
1182 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001183 LHS, RHS, "cmp");
1184 }
Nate Begeman1591bc52008-07-25 20:16:05 +00001185 } else if (LHSTy->isVectorType()) {
1186 Value *LHS = Visit(E->getLHS());
1187 Value *RHS = Visit(E->getRHS());
1188
1189 if (LHS->getType()->isFPOrFPVector()) {
1190 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1191 LHS, RHS, "cmp");
1192 } else if (LHSTy->isUnsignedIntegerType()) {
1193 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1194 LHS, RHS, "cmp");
1195 } else {
1196 // Signed integers and pointers.
1197 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1198 LHS, RHS, "cmp");
1199 }
1200 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001201 } else {
1202 // Complex Comparison: can only be an equality comparison.
1203 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1204 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1205
Chris Lattnerc154ac12008-07-26 22:37:01 +00001206 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001207
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001208 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001209 if (CETy->isRealFloatingType()) {
1210 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1211 LHS.first, RHS.first, "cmp.r");
1212 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1213 LHS.second, RHS.second, "cmp.i");
1214 } else {
1215 // Complex comparisons can only be equality comparisons. As such, signed
1216 // and unsigned opcodes are the same.
1217 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1218 LHS.first, RHS.first, "cmp.r");
1219 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1220 LHS.second, RHS.second, "cmp.i");
1221 }
1222
1223 if (E->getOpcode() == BinaryOperator::EQ) {
1224 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1225 } else {
1226 assert(E->getOpcode() == BinaryOperator::NE &&
1227 "Complex comparison other than == or != ?");
1228 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1229 }
1230 }
Nuno Lopes92577002009-01-11 23:22:37 +00001231
1232 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001233}
1234
1235Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001236 bool Ignore = TestAndClearIgnoreResultAssign();
1237
1238 // __block variables need to have the rhs evaluated first, plus this should
1239 // improve codegen just a little.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001240 Value *RHS = Visit(E->getRHS());
Mike Stump68df15c2009-05-21 21:05:15 +00001241 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001242
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001243 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001244 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1245 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001246 // the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001247 if (LHS.isBitfield()) {
1248 if (!LHS.isVolatileQualified()) {
1249 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1250 &RHS);
1251 return RHS;
1252 } else
1253 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1254 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001255 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001256 if (Ignore)
1257 return 0;
1258 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001259}
1260
1261Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001262 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1263 // If we have 1 && X, just emit X without inserting the control flow.
1264 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1265 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001266 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1267 // ZExt result to int.
1268 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1269 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001270
1271 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1272 if (!CGF.ContainsLabel(E->getRHS()))
1273 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001274 }
1275
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001276 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1277 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001278
Chris Lattner7f80bb32008-11-12 08:38:24 +00001279 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1280 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1281
1282 // Any edges into the ContBlock are now from an (indeterminate number of)
1283 // edges from this first condition. All of these values will be false. Start
1284 // setting up the PHI node in the Cont Block for this.
1285 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1286 PN->reserveOperandSpace(2); // Normal case, two inputs.
1287 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1288 PI != PE; ++PI)
1289 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001290
1291 CGF.EmitBlock(RHSBlock);
1292 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1293
1294 // Reaquire the RHS block, as there may be subblocks inserted.
1295 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001296
1297 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1298 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001299 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001300 PN->addIncoming(RHSCond, RHSBlock);
1301
1302 // ZExt result to int.
1303 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1304}
1305
1306Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001307 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1308 // If we have 0 || X, just emit X without inserting the control flow.
1309 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1310 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001311 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1312 // ZExt result to int.
1313 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1314 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001315
Eli Friedmanea137cd2008-12-02 16:02:46 +00001316 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001317 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001318 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001319 }
1320
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001321 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1322 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001323
Chris Lattner7f80bb32008-11-12 08:38:24 +00001324 // Branch on the LHS first. If it is true, go to the success (cont) block.
1325 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1326
1327 // Any edges into the ContBlock are now from an (indeterminate number of)
1328 // edges from this first condition. All of these values will be true. Start
1329 // setting up the PHI node in the Cont Block for this.
1330 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1331 PN->reserveOperandSpace(2); // Normal case, two inputs.
1332 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1333 PI != PE; ++PI)
1334 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1335
1336 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001337 CGF.EmitBlock(RHSBlock);
1338 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1339
1340 // Reaquire the RHS block, as there may be subblocks inserted.
1341 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001342
Chris Lattner7f80bb32008-11-12 08:38:24 +00001343 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1344 // into the phi node for the edge with the value of RHSCond.
1345 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001346 PN->addIncoming(RHSCond, RHSBlock);
1347
1348 // ZExt result to int.
1349 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1350}
1351
1352Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1353 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001354 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001355 return Visit(E->getRHS());
1356}
1357
1358//===----------------------------------------------------------------------===//
1359// Other Operators
1360//===----------------------------------------------------------------------===//
1361
Chris Lattner504a5282008-11-12 08:55:54 +00001362/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1363/// expression is cheap enough and side-effect-free enough to evaluate
1364/// unconditionally instead of conditionally. This is used to convert control
1365/// flow into selects in some cases.
1366static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1367 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1368 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1369
1370 // TODO: Allow anything we can constant fold to an integer or fp constant.
1371 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1372 isa<FloatingLiteral>(E))
1373 return true;
1374
1375 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1376 // X and Y are local variables.
1377 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1378 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1379 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1380 return true;
1381
1382 return false;
1383}
1384
1385
Chris Lattner9fba49a2007-08-24 05:35:26 +00001386Value *ScalarExprEmitter::
1387VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001388 TestAndClearIgnoreResultAssign();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001389 // If the condition constant folds and can be elided, try to avoid emitting
1390 // the condition and the dead arm.
1391 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001392 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001393 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001394 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001395
1396 // If the dead side doesn't have labels we need, and if the Live side isn't
1397 // the gnu missing ?: extension (which we could handle, but don't bother
1398 // to), just emit the Live part.
1399 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1400 Live) // Live part isn't missing.
1401 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001402 }
1403
Chris Lattner504a5282008-11-12 08:55:54 +00001404
1405 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1406 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001407 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001408 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1409 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1410 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1411 llvm::Value *LHS = Visit(E->getLHS());
1412 llvm::Value *RHS = Visit(E->getRHS());
1413 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1414 }
1415
1416
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001417 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1418 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001419 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001420 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001421
Chris Lattner86031712009-02-13 23:35:32 +00001422 // If we don't have the GNU missing condition extension, emit a branch on
1423 // bool the normal way.
1424 if (E->getLHS()) {
1425 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1426 // the branch on bool.
1427 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1428 } else {
1429 // Otherwise, for the ?: extension, evaluate the conditional and then
1430 // convert it to bool the hard way. We do this explicitly because we need
1431 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001432 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001433
1434 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1435 // if there are no extra uses (an optimization). Inhibit this by making an
1436 // extra dead use, because we're going to add a use of CondVal later. We
1437 // don't use the builder for this, because we don't want it to get optimized
1438 // away. This leaves dead code, but the ?: extension isn't common.
1439 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1440 Builder.GetInsertBlock());
1441
Chris Lattner67e22462008-11-12 08:08:13 +00001442 Value *CondBoolVal =
1443 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1444 CGF.getContext().BoolTy);
1445 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001446 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001447
1448 CGF.EmitBlock(LHSBlock);
1449
1450 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001451 Value *LHS;
1452 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001453 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001454 else // Perform promotions, to handle cases like "short ?: int"
1455 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1456
Chris Lattner9fba49a2007-08-24 05:35:26 +00001457 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001458 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001459
1460 CGF.EmitBlock(RHSBlock);
1461
Eli Friedmance8d7032008-05-16 20:38:39 +00001462 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001463 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001464 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001465
1466 CGF.EmitBlock(ContBlock);
1467
Nuno Lopesb62ff242008-06-04 19:15:45 +00001468 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001469 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1470 return 0;
1471 }
1472
Chris Lattner9fba49a2007-08-24 05:35:26 +00001473 // Create a PHI node for the real part.
1474 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1475 PN->reserveOperandSpace(2);
1476 PN->addIncoming(LHS, LHSBlock);
1477 PN->addIncoming(RHS, RHSBlock);
1478 return PN;
1479}
1480
1481Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001482 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001483}
1484
Chris Lattner307da022007-11-30 17:56:23 +00001485Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001486 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001487 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1488
1489 // If EmitVAArg fails, we fall back to the LLVM instruction.
1490 if (!ArgPtr)
1491 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1492
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001493 // FIXME Volatility.
Anders Carlsson285611e2008-11-04 05:30:00 +00001494 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001495}
1496
Mike Stump4eb81dc2009-02-12 18:29:15 +00001497Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001498 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001499}
1500
Chris Lattner9fba49a2007-08-24 05:35:26 +00001501//===----------------------------------------------------------------------===//
1502// Entry Point into this File
1503//===----------------------------------------------------------------------===//
1504
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001505/// EmitScalarExpr - Emit the computation of the specified expression of
1506/// scalar type, ignoring the result.
1507Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001508 assert(E && !hasAggregateLLVMType(E->getType()) &&
1509 "Invalid scalar expression to emit");
1510
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001511 return ScalarExprEmitter(*this, IgnoreResultAssign)
1512 .Visit(const_cast<Expr*>(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001513}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001514
1515/// EmitScalarConversion - Emit a conversion from the specified type to the
1516/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001517Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1518 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001519 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1520 "Invalid scalar expression to emit");
1521 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1522}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001523
1524/// EmitComplexToScalarConversion - Emit a conversion from the specified
1525/// complex type to the specified destination type, where the destination
1526/// type is an LLVM scalar type.
1527Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1528 QualType SrcTy,
1529 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001530 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001531 "Invalid complex -> scalar conversion");
1532 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1533 DstTy);
1534}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001535
1536Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1537 assert(V1->getType() == V2->getType() &&
1538 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001539 unsigned NumElements =
1540 cast<llvm::VectorType>(V1->getType())->getNumElements();
1541
1542 va_list va;
1543 va_start(va, V2);
1544
1545 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001546 for (unsigned i = 0; i < NumElements; i++) {
1547 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001548 assert(n >= 0 && n < (int)NumElements * 2 &&
1549 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001550 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1551 }
1552
1553 const char *Name = va_arg(va, const char *);
1554 va_end(va);
1555
1556 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1557
1558 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1559}
1560
Anders Carlsson68b8be92007-12-15 21:23:30 +00001561llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001562 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001563 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001564 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001565
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001566 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001567 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001568 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001569 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001570 }
1571
1572 return Vec;
1573}