blob: 0316116631ad8ca48acd3c4a5525fe0a8eefd5da [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000022#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000023#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000024#include "llvm/Module.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000026#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000028#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000029
Chris Lattner7f02f722007-08-24 05:35:26 +000030using namespace clang;
31using namespace CodeGen;
32using llvm::Value;
33
34//===----------------------------------------------------------------------===//
35// Scalar Expression Emitter
36//===----------------------------------------------------------------------===//
37
38struct BinOpInfo {
39 Value *LHS;
40 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000041 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000042 const BinaryOperator *E;
43};
44
45namespace {
46class VISIBILITY_HIDDEN ScalarExprEmitter
47 : public StmtVisitor<ScalarExprEmitter, Value*> {
48 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000049 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000050 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000051 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000052public:
53
Mike Stump7f79f9b2009-05-29 15:46:01 +000054 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Owen Andersona1cf15f2009-07-14 23:10:40 +000055 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
56 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000057 }
Chris Lattner7f02f722007-08-24 05:35:26 +000058
59 //===--------------------------------------------------------------------===//
60 // Utilities
61 //===--------------------------------------------------------------------===//
62
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000064 bool I = IgnoreResultAssign;
65 IgnoreResultAssign = false;
66 return I;
67 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000068
Chris Lattner7f02f722007-08-24 05:35:26 +000069 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
70 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
71
72 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000073 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000074 }
75
76 /// EmitLoadOfLValue - Given an expression with complex type that represents a
77 /// value l-value, this method emits the address of the l-value, then loads
78 /// and returns the result.
79 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +000080 return EmitLoadOfLValue(EmitLValue(E), E->getType());
81 }
82
Chris Lattner9abc84e2007-08-26 16:42:57 +000083 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000084 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000085 Value *EmitConversionToBool(Value *Src, QualType DstTy);
86
Chris Lattner3707b252007-08-26 06:48:56 +000087 /// EmitScalarConversion - Emit a conversion from the specified type to the
88 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000089 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
90
91 /// EmitComplexToScalarConversion - Emit a conversion from the specified
92 /// complex type to the specified destination type, where the destination
93 /// type is an LLVM scalar type.
94 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
95 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000096
Chris Lattner7f02f722007-08-24 05:35:26 +000097 //===--------------------------------------------------------------------===//
98 // Visitor Methods
99 //===--------------------------------------------------------------------===//
100
101 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000102 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000103 assert(0 && "Stmt can't have complex result type!");
104 return 0;
105 }
106 Value *VisitExpr(Expr *S);
107 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
108
109 // Leaves.
110 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000111 return VMContext.getConstantInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000112 }
113 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000114 return VMContext.getConstantFP(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000115 }
116 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000117 return VMContext.getConstantInt(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000118 }
Nate Begemane7579b52007-11-15 05:40:03 +0000119 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000120 return VMContext.getConstantInt(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000121 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000122 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000123 return VMContext.getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000124 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000125 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000126 return VMContext.getNullValue(ConvertType(E->getType()));
Anders Carlsson3f704562008-12-21 22:39:40 +0000127 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000128 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000129 return VMContext.getConstantInt(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000130 CGF.getContext().typesAreCompatible(
131 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000132 }
Sebastian Redl05189992008-11-11 17:56:53 +0000133 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000134 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar54d19092008-08-16 01:41:47 +0000135 llvm::Value *V =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000136 VMContext.getConstantInt(llvm::Type::Int32Ty,
Daniel Dunbar54d19092008-08-16 01:41:47 +0000137 CGF.GetIDForAddrOfLabel(E->getLabel()));
138
139 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000140 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000141
142 // l-values.
143 Value *VisitDeclRefExpr(DeclRefExpr *E) {
144 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
Owen Andersona1cf15f2009-07-14 23:10:40 +0000145 return VMContext.getConstantInt(EC->getInitVal());
Chris Lattner7f02f722007-08-24 05:35:26 +0000146 return EmitLoadOfLValue(E);
147 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000148 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
149 return CGF.EmitObjCSelectorExpr(E);
150 }
151 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
152 return CGF.EmitObjCProtocolExpr(E);
153 }
154 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
155 return EmitLoadOfLValue(E);
156 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000157 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000158 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000159 }
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000160 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
161 return EmitLoadOfLValue(E);
162 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000163 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
164 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000165 }
166
Chris Lattner7f02f722007-08-24 05:35:26 +0000167 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000168 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000169 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000170 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000171 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
172 return EmitLoadOfLValue(E);
173 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000174 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000175 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
176 return EmitLValue(E).getAddress();
177 }
178
Chris Lattnerd9f69102008-08-10 01:53:14 +0000179 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000180
181 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000182 bool Ignore = TestAndClearIgnoreResultAssign();
183 (void)Ignore;
184 assert (Ignore == false && "init list ignored");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000185 unsigned NumInitElements = E->getNumInits();
186
Douglas Gregora9c87802009-01-29 19:42:23 +0000187 if (E->hadArrayRangeDesignator()) {
188 CGF.ErrorUnsupported(E, "GNU array range designator extension");
189 }
190
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000191 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000192 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
193
194 // We have a scalar in braces. Just use the first element.
195 if (!VType)
196 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000197
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000198 unsigned NumVectorElements = VType->getNumElements();
199 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000200
201 // Emit individual vector element stores.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000202 llvm::Value *V = VMContext.getUndef(VType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000203
Anders Carlsson222d2c82007-12-18 02:45:33 +0000204 // Emit initializers
205 unsigned i;
206 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000207 Value *NewV = Visit(E->getInit(i));
Owen Andersona1cf15f2009-07-14 23:10:40 +0000208 Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, i);
Devang Patela83cc332007-10-24 18:05:48 +0000209 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000210 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000211
212 // Emit remaining default initializers
213 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000214 Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, i);
215 llvm::Value *NewV = VMContext.getNullValue(ElementType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000216 V = Builder.CreateInsertElement(V, NewV, Idx);
217 }
218
Devang Patela83cc332007-10-24 18:05:48 +0000219 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000220 }
Chris Lattner04421082008-04-08 04:40:51 +0000221
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000222 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000223 return VMContext.getNullValue(ConvertType(E->getType()));
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000224 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000225 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000226 Value *VisitCastExpr(const CastExpr *E) {
227 // Make sure to evaluate VLA bounds now so that we have them for later.
228 if (E->getType()->isVariablyModifiedType())
229 CGF.EmitVLASize(E->getType());
230
Chris Lattner7f02f722007-08-24 05:35:26 +0000231 return EmitCastExpr(E->getSubExpr(), E->getType());
232 }
233 Value *EmitCastExpr(const Expr *E, QualType T);
234
235 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000236 if (E->getCallReturnType()->isReferenceType())
237 return EmitLoadOfLValue(E);
238
Chris Lattner9b655512007-08-31 22:49:20 +0000239 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000240 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000241
Chris Lattner33793202007-08-31 22:09:40 +0000242 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000243
Mike Stumpa99038c2009-02-28 09:07:16 +0000244 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattner33793202007-08-31 22:09:40 +0000245
Chris Lattner7f02f722007-08-24 05:35:26 +0000246 // Unary Operators.
247 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
248 Value *VisitUnaryPostDec(const UnaryOperator *E) {
249 return VisitPrePostIncDec(E, false, false);
250 }
251 Value *VisitUnaryPostInc(const UnaryOperator *E) {
252 return VisitPrePostIncDec(E, true, false);
253 }
254 Value *VisitUnaryPreDec(const UnaryOperator *E) {
255 return VisitPrePostIncDec(E, false, true);
256 }
257 Value *VisitUnaryPreInc(const UnaryOperator *E) {
258 return VisitPrePostIncDec(E, true, true);
259 }
260 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
261 return EmitLValue(E->getSubExpr()).getAddress();
262 }
263 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
264 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000265 // This differs from gcc, though, most likely due to a bug in gcc.
266 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000267 return Visit(E->getSubExpr());
268 }
269 Value *VisitUnaryMinus (const UnaryOperator *E);
270 Value *VisitUnaryNot (const UnaryOperator *E);
271 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000272 Value *VisitUnaryReal (const UnaryOperator *E);
273 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000274 Value *VisitUnaryExtension(const UnaryOperator *E) {
275 return Visit(E->getSubExpr());
276 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000277 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000278
279 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000280 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
281 return Visit(DAE->getExpr());
282 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000283 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
284 return CGF.LoadCXXThis();
285 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000286
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000287 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000288 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000289 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000290 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
291 return CGF.EmitCXXNewExpr(E);
292 }
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000293
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stump035cf892009-04-02 18:15:54 +0000296 if (CGF.getContext().getLangOptions().OverflowChecking
297 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000298 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000299 if (Ops.LHS->getType()->isFPOrFPVector())
300 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000301 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
302 }
Mike Stump2add4732009-04-01 20:28:16 +0000303 /// Create a binary op that checks for overflow.
304 /// Currently only supports +, - and *.
305 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 Value *EmitDiv(const BinOpInfo &Ops);
307 Value *EmitRem(const BinOpInfo &Ops);
308 Value *EmitAdd(const BinOpInfo &Ops);
309 Value *EmitSub(const BinOpInfo &Ops);
310 Value *EmitShl(const BinOpInfo &Ops);
311 Value *EmitShr(const BinOpInfo &Ops);
312 Value *EmitAnd(const BinOpInfo &Ops) {
313 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
314 }
315 Value *EmitXor(const BinOpInfo &Ops) {
316 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
317 }
318 Value *EmitOr (const BinOpInfo &Ops) {
319 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
320 }
321
Chris Lattner1f1ded92007-08-24 21:00:35 +0000322 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000323 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000324 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
325
326 // Binary operators and binary compound assignment operators.
327#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000328 Value *VisitBin ## OP(const BinaryOperator *E) { \
329 return Emit ## OP(EmitBinOps(E)); \
330 } \
331 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
332 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000333 }
334 HANDLEBINOP(Mul);
335 HANDLEBINOP(Div);
336 HANDLEBINOP(Rem);
337 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000338 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000339 HANDLEBINOP(Shl);
340 HANDLEBINOP(Shr);
341 HANDLEBINOP(And);
342 HANDLEBINOP(Xor);
343 HANDLEBINOP(Or);
344#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000345
Chris Lattner7f02f722007-08-24 05:35:26 +0000346 // Comparisons.
347 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
348 unsigned SICmpOpc, unsigned FCmpOpc);
349#define VISITCOMP(CODE, UI, SI, FP) \
350 Value *VisitBin##CODE(const BinaryOperator *E) { \
351 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
352 llvm::FCmpInst::FP); }
353 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
354 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
355 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
356 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
357 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
358 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
359#undef VISITCOMP
360
361 Value *VisitBinAssign (const BinaryOperator *E);
362
363 Value *VisitBinLAnd (const BinaryOperator *E);
364 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000365 Value *VisitBinComma (const BinaryOperator *E);
366
367 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000368 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000369 Value *VisitConditionalOperator(const ConditionalOperator *CO);
370 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000371 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000372 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
373 return CGF.EmitObjCStringLiteral(E);
374 }
375};
376} // end anonymous namespace.
377
378//===----------------------------------------------------------------------===//
379// Utilities
380//===----------------------------------------------------------------------===//
381
Chris Lattner9abc84e2007-08-26 16:42:57 +0000382/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000383/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000384Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
385 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
386
387 if (SrcType->isRealFloatingType()) {
388 // Compare against 0.0 for fp scalars.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000389 llvm::Value *Zero = VMContext.getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000390 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
391 }
392
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000393 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000394 "Unknown scalar type to convert");
395
396 // Because of the type rules of C, we often end up computing a logical value,
397 // then zero extending it to int, then wanting it as a logical value again.
398 // Optimize this common case.
399 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
400 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
401 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000402 // If there aren't any more uses, zap the instruction to save space.
403 // Note that there can be more uses, for example if this
404 // is the result of an assignment.
405 if (ZI->use_empty())
406 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000407 return Result;
408 }
409 }
410
411 // Compare against an integer or pointer null.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000412 llvm::Value *Zero = VMContext.getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000413 return Builder.CreateICmpNE(Src, Zero, "tobool");
414}
415
Chris Lattner3707b252007-08-26 06:48:56 +0000416/// EmitScalarConversion - Emit a conversion from the specified type to the
417/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000418Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
419 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000420 SrcType = CGF.getContext().getCanonicalType(SrcType);
421 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000422 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000423
424 if (DstType->isVoidType()) return 0;
Chris Lattner3707b252007-08-26 06:48:56 +0000425
426 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000427 if (DstType->isBooleanType())
428 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000429
430 const llvm::Type *DstTy = ConvertType(DstType);
431
432 // Ignore conversions like int -> uint.
433 if (Src->getType() == DstTy)
434 return Src;
435
Daniel Dunbar270cc662008-08-25 09:51:32 +0000436 // Handle pointer conversions next: pointers can only be converted
437 // to/from other pointers and integers. Check for pointer types in
438 // terms of LLVM, as some native types (like Obj-C id) may map to a
439 // pointer type.
440 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000441 // The source value may be an integer, or a pointer.
442 if (isa<llvm::PointerType>(Src->getType()))
443 return Builder.CreateBitCast(Src, DstTy, "conv");
444 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000445 // First, convert to the correct width so that we control the kind of
446 // extension.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000447 const llvm::Type *MiddleTy = VMContext.getIntegerType(CGF.LLVMPointerWidth);
Eli Friedman25615422009-03-04 04:02:35 +0000448 bool InputSigned = SrcType->isSignedIntegerType();
449 llvm::Value* IntResult =
450 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
451 // Then, cast to pointer.
452 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000453 }
454
Daniel Dunbar270cc662008-08-25 09:51:32 +0000455 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000456 // Must be an ptr to int cast.
457 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000458 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000459 }
460
Nate Begeman213541a2008-04-18 23:10:10 +0000461 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000462 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
463 // Cast the scalar to element type
464 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
465 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
466
467 // Insert the element in element zero of an undef vector
Owen Andersona1cf15f2009-07-14 23:10:40 +0000468 llvm::Value *UnV = VMContext.getUndef(DstTy);
469 llvm::Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000470 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
471
472 // Splat the element across to all elements
473 llvm::SmallVector<llvm::Constant*, 16> Args;
474 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
475 for (unsigned i = 0; i < NumElements; i++)
Owen Andersona1cf15f2009-07-14 23:10:40 +0000476 Args.push_back(VMContext.getConstantInt(llvm::Type::Int32Ty, 0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000477
Owen Andersona1cf15f2009-07-14 23:10:40 +0000478 llvm::Constant *Mask = VMContext.getConstantVector(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000479 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
480 return Yay;
481 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000482
Chris Lattner3b1ae002008-02-02 04:51:41 +0000483 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000484 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000485 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000486 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000487
Chris Lattner3707b252007-08-26 06:48:56 +0000488 // Finally, we have the arithmetic types: real int/float.
489 if (isa<llvm::IntegerType>(Src->getType())) {
490 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000491 if (isa<llvm::IntegerType>(DstTy))
492 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
493 else if (InputSigned)
494 return Builder.CreateSIToFP(Src, DstTy, "conv");
495 else
496 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000497 }
498
499 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
500 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000501 if (DstType->isSignedIntegerType())
502 return Builder.CreateFPToSI(Src, DstTy, "conv");
503 else
504 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000505 }
506
507 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000508 if (DstTy->getTypeID() < Src->getType()->getTypeID())
509 return Builder.CreateFPTrunc(Src, DstTy, "conv");
510 else
511 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000512}
513
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000514/// EmitComplexToScalarConversion - Emit a conversion from the specified
515/// complex type to the specified destination type, where the destination
516/// type is an LLVM scalar type.
517Value *ScalarExprEmitter::
518EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
519 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000520 // Get the source element type.
Chris Lattner96196622008-07-26 22:37:01 +0000521 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnered70f0a2007-08-26 16:52:28 +0000522
523 // Handle conversions to bool first, they are special: comparisons against 0.
524 if (DstTy->isBooleanType()) {
525 // Complex != 0 -> (Real != 0) | (Imag != 0)
526 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
527 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
528 return Builder.CreateOr(Src.first, Src.second, "tobool");
529 }
530
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000531 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
532 // the imaginary part of the complex value is discarded and the value of the
533 // real part is converted according to the conversion rules for the
534 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000535 return EmitScalarConversion(Src.first, SrcTy, DstTy);
536}
537
538
Chris Lattner7f02f722007-08-24 05:35:26 +0000539//===----------------------------------------------------------------------===//
540// Visitor Methods
541//===----------------------------------------------------------------------===//
542
543Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000544 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000545 if (E->getType()->isVoidType())
546 return 0;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000547 return VMContext.getUndef(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000548}
549
Eli Friedmand38617c2008-05-14 19:38:39 +0000550Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
551 llvm::SmallVector<llvm::Constant*, 32> indices;
552 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
553 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
554 }
555 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
556 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Andersona1cf15f2009-07-14 23:10:40 +0000557 Value* SV = VMContext.getConstantVector(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000558 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
559}
560
Chris Lattner7f02f722007-08-24 05:35:26 +0000561Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000562 TestAndClearIgnoreResultAssign();
563
Chris Lattner7f02f722007-08-24 05:35:26 +0000564 // Emit subscript expressions in rvalue context's. For most cases, this just
565 // loads the lvalue formed by the subscript expr. However, we have to be
566 // careful, because the base of a vector subscript is occasionally an rvalue,
567 // so we can't get it as an lvalue.
568 if (!E->getBase()->getType()->isVectorType())
569 return EmitLoadOfLValue(E);
570
571 // Handle the vector case. The base must be a vector, the index must be an
572 // integer value.
573 Value *Base = Visit(E->getBase());
574 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000575 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedman515ff5a2009-03-28 03:27:06 +0000576 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
577 "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000578 return Builder.CreateExtractElement(Base, Idx, "vecext");
579}
580
581/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
582/// also handle things like function to pointer-to-function decay, and array to
583/// pointer decay.
584Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
585 const Expr *Op = E->getSubExpr();
586
587 // If this is due to array->pointer conversion, emit the array expression as
588 // an l-value.
589 if (Op->getType()->isArrayType()) {
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000590 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000591
Eli Friedmandaa24a22009-03-28 02:45:41 +0000592 // Note that VLA pointers are always decayed, so we don't need to do
593 // anything here.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000594 if (!Op->getType()->isVariableArrayType()) {
595 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
596 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
597 ->getElementType()) &&
598 "Expected pointer to array");
599 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar662174c82008-08-29 17:28:43 +0000600 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000601
602 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerf31627f2008-07-23 06:31:27 +0000603 // types as well (e.g. void*) and can be implicitly converted to integer.
604 const llvm::Type *DestTy = ConvertType(E->getType());
605 if (V->getType() != DestTy) {
606 if (isa<llvm::PointerType>(DestTy))
607 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
608 else {
609 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
610 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
611 }
612 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000613 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000614 }
Eli Friedmandaa24a22009-03-28 02:45:41 +0000615
Chris Lattner7f02f722007-08-24 05:35:26 +0000616 return EmitCastExpr(Op, E->getType());
617}
618
619
620// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
621// have to handle a more broad range of conversions than explicit casts, as they
622// handle things like function to ptr-to-function decay etc.
623Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000624 if (!DestTy->isVoidType())
625 TestAndClearIgnoreResultAssign();
626
Chris Lattner58a2e942007-08-26 07:26:12 +0000627 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000628
629 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000630 Value *Src = Visit(const_cast<Expr*>(E));
631
Chris Lattner3707b252007-08-26 06:48:56 +0000632 // Use EmitScalarConversion to perform the conversion.
633 return EmitScalarConversion(Src, E->getType(), DestTy);
634 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000635
Chris Lattner9b2dc282008-04-04 16:54:41 +0000636 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000637 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000638 bool IgnoreImag = true;
639 bool IgnoreImagAssign = true;
640 bool IgnoreReal = IgnoreResultAssign;
641 bool IgnoreRealAssign = IgnoreResultAssign;
642 if (DestTy->isBooleanType())
643 IgnoreImagAssign = IgnoreImag = false;
644 else if (DestTy->isVoidType()) {
645 IgnoreReal = IgnoreImag = false;
646 IgnoreRealAssign = IgnoreImagAssign = true;
647 }
648 CodeGenFunction::ComplexPairTy V
649 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
650 IgnoreImagAssign);
651 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000652 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000653
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000654 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
655 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000656 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000657 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000658}
659
Chris Lattner33793202007-08-31 22:09:40 +0000660Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000661 return CGF.EmitCompoundStmt(*E->getSubStmt(),
662 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000663}
664
Mike Stumpa99038c2009-02-28 09:07:16 +0000665Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
666 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +0000667}
Chris Lattner33793202007-08-31 22:09:40 +0000668
Chris Lattner7f02f722007-08-24 05:35:26 +0000669//===----------------------------------------------------------------------===//
670// Unary Operators
671//===----------------------------------------------------------------------===//
672
673Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000674 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000675 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000676 QualType ValTy = E->getSubExpr()->getType();
677 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000678
679 int AmountVal = isInc ? 1 : -1;
Eli Friedmandaa24a22009-03-28 02:45:41 +0000680
681 if (ValTy->isPointerType() &&
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000682 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000683 // The amount of the addition/subtraction needs to account for the VLA size
684 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
685 }
686
Chris Lattner7f02f722007-08-24 05:35:26 +0000687 Value *NextVal;
Chris Lattner8cc9d082009-03-18 04:25:13 +0000688 if (const llvm::PointerType *PT =
689 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000690 llvm::Constant *Inc =
691 VMContext.getConstantInt(llvm::Type::Int32Ty, AmountVal);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000692 if (!isa<llvm::FunctionType>(PT->getElementType())) {
693 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
694 } else {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000695 const llvm::Type *i8Ty =
696 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000697 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
698 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
699 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
700 }
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +0000701 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
702 // Bool++ is an interesting case, due to promotion rules, we get:
703 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
704 // Bool = ((int)Bool+1) != 0
705 // An interesting aspect of this is that increment is always true.
706 // Decrement does not have this property.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000707 NextVal = VMContext.getConstantIntTrue();
Chris Lattner87415d22009-06-17 06:36:24 +0000708 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000709 NextVal = VMContext.getConstantInt(InVal->getType(), AmountVal);
Chris Lattner87415d22009-06-17 06:36:24 +0000710 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000711 } else {
712 // Add the inc/dec to the real part.
Chris Lattner87415d22009-06-17 06:36:24 +0000713 if (InVal->getType() == llvm::Type::FloatTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000714 NextVal =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000715 VMContext.getConstantFP(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000716 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000717 NextVal =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000718 VMContext.getConstantFP(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000719 else {
720 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000721 bool ignored;
722 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
723 &ignored);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000724 NextVal = VMContext.getConstantFP(F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000725 }
Chris Lattner87415d22009-06-17 06:36:24 +0000726 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000727 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000728
729 // Store the updated result through the lvalue.
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000730 if (LV.isBitfield())
731 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
732 &NextVal);
733 else
734 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner7f02f722007-08-24 05:35:26 +0000735
736 // If this is a postinc, return the value read from memory, otherwise use the
737 // updated value.
738 return isPre ? NextVal : InVal;
739}
740
741
742Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000743 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000744 Value *Op = Visit(E->getSubExpr());
Chris Lattner87415d22009-06-17 06:36:24 +0000745 if (Op->getType()->isFPOrFPVector())
746 return Builder.CreateFNeg(Op, "neg");
Chris Lattner7f02f722007-08-24 05:35:26 +0000747 return Builder.CreateNeg(Op, "neg");
748}
749
750Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000751 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000752 Value *Op = Visit(E->getSubExpr());
753 return Builder.CreateNot(Op, "neg");
754}
755
756Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
757 // Compare operand to zero.
758 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
759
760 // Invert value.
761 // TODO: Could dynamically modify easy computations here. For example, if
762 // the operand is an icmp ne, turn into icmp eq.
763 BoolVal = Builder.CreateNot(BoolVal, "lnot");
764
Anders Carlsson9f84d882009-05-19 18:44:53 +0000765 // ZExt result to the expr type.
766 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +0000767}
768
Sebastian Redl05189992008-11-11 17:56:53 +0000769/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
770/// argument of the sizeof expression as an integer.
771Value *
772ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +0000773 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000774 if (E->isSizeOf()) {
775 if (const VariableArrayType *VAT =
776 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
777 if (E->isArgumentType()) {
778 // sizeof(type) - make sure to emit the VLA size.
779 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +0000780 } else {
781 // C99 6.5.3.4p2: If the argument is an expression of type
782 // VLA, it is evaluated.
783 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000784 }
Anders Carlsson6cd586d2009-01-30 16:41:04 +0000785
Anders Carlsson96f21472009-02-05 19:43:10 +0000786 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000787 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000788 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000789
790 // If this isn't sizeof(vla), the result must be constant; use the
791 // constant folding logic so we don't have to duplicate it here.
792 Expr::EvalResult Result;
793 E->Evaluate(Result, CGF.getContext());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000794 return VMContext.getConstantInt(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +0000795}
796
Chris Lattner46f93d02007-08-24 21:20:17 +0000797Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
798 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000799 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000800 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +0000801 return Visit(Op);
802}
803Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
804 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000805 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000806 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000807
Mike Stump7f79f9b2009-05-29 15:46:01 +0000808 // __imag on a scalar returns zero. Emit the subexpr to ensure side
809 // effects are evaluated, but not the actual value.
810 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
811 CGF.EmitLValue(Op);
812 else
813 CGF.EmitScalarExpr(Op, true);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000814 return VMContext.getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000815}
816
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000817Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
818{
Eli Friedman35183ac2009-02-27 06:44:11 +0000819 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +0000820 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +0000821 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000822}
Chris Lattner46f93d02007-08-24 21:20:17 +0000823
Chris Lattner7f02f722007-08-24 05:35:26 +0000824//===----------------------------------------------------------------------===//
825// Binary Operators
826//===----------------------------------------------------------------------===//
827
828BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000829 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000830 BinOpInfo Result;
831 Result.LHS = Visit(E->getLHS());
832 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000833 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000834 Result.E = E;
835 return Result;
836}
837
Chris Lattner3ccf7742007-08-26 21:41:21 +0000838Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000839 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000840 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000841 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
842
843 BinOpInfo OpInfo;
844
Eli Friedmanab3a8522009-03-28 01:22:36 +0000845 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000846 // This needs to go through the complex expression emitter, but
Eli Friedmanab3a8522009-03-28 01:22:36 +0000847 // it's a tad complicated to do that... I'm leaving it out for now.
848 // (Note that we do actually need the imaginary part of the RHS for
849 // multiplication and division.)
850 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Andersona1cf15f2009-07-14 23:10:40 +0000851 return VMContext.getUndef(CGF.ConvertType(E->getType()));
Eli Friedmanab3a8522009-03-28 01:22:36 +0000852 }
853
Mike Stumpcc0442f2009-05-22 19:07:20 +0000854 // Emit the RHS first. __block variables need to have the rhs evaluated
855 // first, plus this should improve codegen a little.
856 OpInfo.RHS = Visit(E->getRHS());
857 OpInfo.Ty = E->getComputationResultType();
858 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +0000859 // Load/convert the LHS.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000860 LValue LHSLV = EmitLValue(E->getLHS());
861 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000862 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
863 E->getComputationLHSType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000864
865 // Expand the binary operator.
866 Value *Result = (this->*Func)(OpInfo);
867
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000868 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +0000869 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
870
Daniel Dunbared3849b2008-11-19 09:36:46 +0000871 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar371d16f2008-11-19 11:54:05 +0000872 // handled specially because the result is altered by the store,
873 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
874 // the left operand after the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000875 if (LHSLV.isBitfield()) {
876 if (!LHSLV.isVolatileQualified()) {
877 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
878 &Result);
879 return Result;
880 } else
881 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
882 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +0000883 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stump7f79f9b2009-05-29 15:46:01 +0000884 if (Ignore)
885 return 0;
886 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000887}
888
889
Chris Lattner7f02f722007-08-24 05:35:26 +0000890Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000891 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000892 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000893 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000894 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
895 else
896 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
897}
898
899Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
900 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000901 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000902 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
903 else
904 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
905}
906
Mike Stump2add4732009-04-01 20:28:16 +0000907Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
908 unsigned IID;
909 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000910
Mike Stump035cf892009-04-02 18:15:54 +0000911 switch (Ops.E->getOpcode()) {
912 case BinaryOperator::Add:
913 case BinaryOperator::AddAssign:
914 OpID = 1;
915 IID = llvm::Intrinsic::sadd_with_overflow;
916 break;
917 case BinaryOperator::Sub:
918 case BinaryOperator::SubAssign:
919 OpID = 2;
920 IID = llvm::Intrinsic::ssub_with_overflow;
921 break;
922 case BinaryOperator::Mul:
923 case BinaryOperator::MulAssign:
924 OpID = 3;
925 IID = llvm::Intrinsic::smul_with_overflow;
926 break;
927 default:
928 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +0000929 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +0000930 }
Mike Stump035cf892009-04-02 18:15:54 +0000931 OpID <<= 1;
932 OpID |= 1;
933
Mike Stump2add4732009-04-01 20:28:16 +0000934 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
935
936 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
937
938 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
939 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
940 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
941
942 // Branch in case of overflow.
943 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
944 llvm::BasicBlock *overflowBB =
945 CGF.createBasicBlock("overflow", CGF.CurFn);
946 llvm::BasicBlock *continueBB =
947 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
948
949 Builder.CreateCondBr(overflow, overflowBB, continueBB);
950
951 // Handle overflow
952
953 Builder.SetInsertPoint(overflowBB);
954
955 // Handler is:
956 // long long *__overflow_handler)(long long a, long long b, char op,
957 // char width)
958 std::vector<const llvm::Type*> handerArgTypes;
959 handerArgTypes.push_back(llvm::Type::Int64Ty);
960 handerArgTypes.push_back(llvm::Type::Int64Ty);
961 handerArgTypes.push_back(llvm::Type::Int8Ty);
962 handerArgTypes.push_back(llvm::Type::Int8Ty);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000963 llvm::FunctionType *handlerTy = VMContext.getFunctionType(llvm::Type::Int64Ty,
Mike Stump2add4732009-04-01 20:28:16 +0000964 handerArgTypes, false);
965 llvm::Value *handlerFunction =
966 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Andersona1cf15f2009-07-14 23:10:40 +0000967 VMContext.getPointerTypeUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +0000968 handlerFunction = Builder.CreateLoad(handlerFunction);
969
970 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
971 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
972 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000973 VMContext.getConstantInt(llvm::Type::Int8Ty, OpID),
974 VMContext.getConstantInt(llvm::Type::Int8Ty,
Mike Stump2add4732009-04-01 20:28:16 +0000975 cast<llvm::IntegerType>(opTy)->getBitWidth()));
976
977 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
978
979 Builder.CreateBr(continueBB);
980
981 // Set up the continuation
982 Builder.SetInsertPoint(continueBB);
983 // Get the correct result
984 llvm::PHINode *phi = Builder.CreatePHI(opTy);
985 phi->reserveOperandSpace(2);
986 phi->addIncoming(result, initialBB);
987 phi->addIncoming(handlerResult, overflowBB);
988
989 return phi;
990}
Chris Lattner7f02f722007-08-24 05:35:26 +0000991
992Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000993 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner87415d22009-06-17 06:36:24 +0000994 if (CGF.getContext().getLangOptions().OverflowChecking &&
995 Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000996 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000997
998 if (Ops.LHS->getType()->isFPOrFPVector())
999 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1000
Chris Lattner7f02f722007-08-24 05:35:26 +00001001 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001002 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001003
Steve Naroff14108da2009-07-10 23:34:53 +00001004 if (Ops.Ty->isPointerType() &&
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001005 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001006 // The amount of the addition needs to account for the VLA size
1007 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1008 }
Chris Lattner8f925282008-01-03 06:36:51 +00001009 Value *Ptr, *Idx;
1010 Expr *IdxExp;
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001011 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001012 const ObjCObjectPointerType *OPT =
1013 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1014 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001015 Ptr = Ops.LHS;
1016 Idx = Ops.RHS;
1017 IdxExp = Ops.E->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001018 } else { // int + pointer
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001019 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001020 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1021 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001022 Ptr = Ops.RHS;
1023 Idx = Ops.LHS;
1024 IdxExp = Ops.E->getLHS();
1025 }
1026
1027 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001028 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001029 // Zero or sign extend the pointer value based on whether the index is
1030 // signed or not.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001031 const llvm::Type *IdxType = VMContext.getIntegerType(CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +00001032 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001033 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1034 else
1035 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1036 }
Steve Naroff14108da2009-07-10 23:34:53 +00001037 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbar2a866252009-04-25 05:08:32 +00001038 // Handle interface types, which are not represented with a concrete
1039 // type.
1040 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1041 llvm::Value *InterfaceSize =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001042 VMContext.getConstantInt(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001043 CGF.getContext().getTypeSize(OIT) / 8);
1044 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001045 const llvm::Type *i8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001046 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1047 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1048 return Builder.CreateBitCast(Res, Ptr->getType());
1049 }
1050
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001051 // Explicitly handle GNU void* and function pointer arithmetic
1052 // extensions. The GNU void* casts amount to no-ops since our void*
1053 // type is i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001054 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001055 const llvm::Type *i8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001056 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001057 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001058 return Builder.CreateBitCast(Res, Ptr->getType());
1059 }
Chris Lattner8f925282008-01-03 06:36:51 +00001060
1061 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001062}
1063
1064Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001065 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stump035cf892009-04-02 18:15:54 +00001066 if (CGF.getContext().getLangOptions().OverflowChecking
1067 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001068 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001069
1070 if (Ops.LHS->getType()->isFPOrFPVector())
1071 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner7f02f722007-08-24 05:35:26 +00001072 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001073 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001074
Steve Naroff14108da2009-07-10 23:34:53 +00001075 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001076 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001077 // The amount of the addition needs to account for the VLA size for
1078 // ptr-int
1079 // The amount of the division needs to account for the VLA size for
1080 // ptr-ptr.
1081 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1082 }
1083
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001084 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001085 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001086 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1087 // pointer - int
1088 Value *Idx = Ops.RHS;
1089 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001090 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001091 // Zero or sign extend the pointer value based on whether the index is
1092 // signed or not.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001093 const llvm::Type *IdxType =
1094 VMContext.getIntegerType(CGF.LLVMPointerWidth);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001095 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1096 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1097 else
1098 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1099 }
1100 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001101
Daniel Dunbar2a866252009-04-25 05:08:32 +00001102 // Handle interface types, which are not represented with a concrete
1103 // type.
1104 if (const ObjCInterfaceType *OIT =
1105 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1106 llvm::Value *InterfaceSize =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001107 VMContext.getConstantInt(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001108 CGF.getContext().getTypeSize(OIT) / 8);
1109 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001110 const llvm::Type *i8Ty =
1111 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001112 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1113 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1114 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1115 }
1116
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001117 // Explicitly handle GNU void* and function pointer arithmetic
1118 // extensions. The GNU void* casts amount to no-ops since our
1119 // void* type is i8*, but this is future proof.
1120 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001121 const llvm::Type *i8Ty =
1122 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001123 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1124 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1125 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1126 }
1127
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001128 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001129 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001130 // pointer - pointer
1131 Value *LHS = Ops.LHS;
1132 Value *RHS = Ops.RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +00001133
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001134 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001135
Chris Lattnere5ed1512009-02-11 07:21:43 +00001136 // Handle GCC extension for pointer arithmetic on void* and function pointer
1137 // types.
1138 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001139 ElementSize = 1;
1140 } else {
1141 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1142 }
1143
1144 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1145 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1146 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1147 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1148
Chris Lattnere5ed1512009-02-11 07:21:43 +00001149 // Optimize out the shift for element size of 1.
1150 if (ElementSize == 1)
1151 return BytesBetween;
1152
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001153 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1154 // remainder. As such, we handle common power-of-two cases here to generate
1155 // better code. See PR2247.
1156 if (llvm::isPowerOf2_64(ElementSize)) {
1157 Value *ShAmt =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001158 VMContext.getConstantInt(ResultType, llvm::Log2_64(ElementSize));
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001159 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1160 }
1161
1162 // Otherwise, do a full sdiv.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001163 Value *BytesPerElt = VMContext.getConstantInt(ResultType, ElementSize);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001164 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001165 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001166}
1167
1168Value *ScalarExprEmitter::EmitShl(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
1175 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1176}
1177
1178Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1179 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1180 // RHS to the same size as the LHS.
1181 Value *RHS = Ops.RHS;
1182 if (Ops.LHS->getType() != RHS->getType())
1183 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1184
Chris Lattner1f1ded92007-08-24 21:00:35 +00001185 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001186 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1187 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1188}
1189
1190Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1191 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001192 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001193 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001194 QualType LHSTy = E->getLHS()->getType();
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001195 if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001196 Value *LHS = Visit(E->getLHS());
1197 Value *RHS = Visit(E->getRHS());
1198
1199 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001200 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001201 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001202 } else if (LHSTy->isSignedIntegerType()) {
1203 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001204 LHS, RHS, "cmp");
1205 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001206 // Unsigned integers and pointers.
1207 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001208 LHS, RHS, "cmp");
1209 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001210
1211 // If this is a vector comparison, sign extend the result to the appropriate
1212 // vector integer type and return it (don't convert to bool).
1213 if (LHSTy->isVectorType())
1214 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001215
Chris Lattner7f02f722007-08-24 05:35:26 +00001216 } else {
1217 // Complex Comparison: can only be an equality comparison.
1218 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1219 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1220
Chris Lattner96196622008-07-26 22:37:01 +00001221 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner7f02f722007-08-24 05:35:26 +00001222
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001223 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001224 if (CETy->isRealFloatingType()) {
1225 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1226 LHS.first, RHS.first, "cmp.r");
1227 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1228 LHS.second, RHS.second, "cmp.i");
1229 } else {
1230 // Complex comparisons can only be equality comparisons. As such, signed
1231 // and unsigned opcodes are the same.
1232 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1233 LHS.first, RHS.first, "cmp.r");
1234 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1235 LHS.second, RHS.second, "cmp.i");
1236 }
1237
1238 if (E->getOpcode() == BinaryOperator::EQ) {
1239 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1240 } else {
1241 assert(E->getOpcode() == BinaryOperator::NE &&
1242 "Complex comparison other than == or != ?");
1243 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1244 }
1245 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001246
1247 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001248}
1249
1250Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001251 bool Ignore = TestAndClearIgnoreResultAssign();
1252
1253 // __block variables need to have the rhs evaluated first, plus this should
1254 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001255 Value *RHS = Visit(E->getRHS());
Mike Stump99459b62009-05-21 21:05:15 +00001256 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001257
Daniel Dunbared3849b2008-11-19 09:36:46 +00001258 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001259 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1260 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001261 // the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001262 if (LHS.isBitfield()) {
1263 if (!LHS.isVolatileQualified()) {
1264 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1265 &RHS);
1266 return RHS;
1267 } else
1268 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1269 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001270 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stump7f79f9b2009-05-29 15:46:01 +00001271 if (Ignore)
1272 return 0;
1273 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001274}
1275
1276Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001277 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1278 // If we have 1 && X, just emit X without inserting the control flow.
1279 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1280 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001281 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1282 // ZExt result to int.
1283 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1284 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001285
1286 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1287 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersona1cf15f2009-07-14 23:10:40 +00001288 return VMContext.getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001289 }
1290
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001291 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1292 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001293
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001294 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1295 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1296
1297 // Any edges into the ContBlock are now from an (indeterminate number of)
1298 // edges from this first condition. All of these values will be false. Start
1299 // setting up the PHI node in the Cont Block for this.
1300 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1301 PN->reserveOperandSpace(2); // Normal case, two inputs.
1302 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1303 PI != PE; ++PI)
Owen Andersona1cf15f2009-07-14 23:10:40 +00001304 PN->addIncoming(VMContext.getConstantIntFalse(), *PI);
Chris Lattner7f02f722007-08-24 05:35:26 +00001305
Anders Carlsson33da07d2009-06-04 02:53:13 +00001306 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001307 CGF.EmitBlock(RHSBlock);
1308 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson33da07d2009-06-04 02:53:13 +00001309 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001310
1311 // Reaquire the RHS block, as there may be subblocks inserted.
1312 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001313
1314 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1315 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001316 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001317 PN->addIncoming(RHSCond, RHSBlock);
1318
1319 // ZExt result to int.
1320 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1321}
1322
1323Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001324 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1325 // If we have 0 || X, just emit X without inserting the control flow.
1326 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1327 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001328 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1329 // ZExt result to int.
1330 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1331 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001332
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001333 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001334 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersona1cf15f2009-07-14 23:10:40 +00001335 return VMContext.getConstantInt(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001336 }
1337
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001338 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1339 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner7f02f722007-08-24 05:35:26 +00001340
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001341 // Branch on the LHS first. If it is true, go to the success (cont) block.
1342 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1343
1344 // Any edges into the ContBlock are now from an (indeterminate number of)
1345 // edges from this first condition. All of these values will be true. Start
1346 // setting up the PHI node in the Cont Block for this.
1347 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1348 PN->reserveOperandSpace(2); // Normal case, two inputs.
1349 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1350 PI != PE; ++PI)
Owen Andersona1cf15f2009-07-14 23:10:40 +00001351 PN->addIncoming(VMContext.getConstantIntTrue(), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001352
Anders Carlsson33da07d2009-06-04 02:53:13 +00001353 CGF.PushConditionalTempDestruction();
1354
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001355 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001356 CGF.EmitBlock(RHSBlock);
1357 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1358
Anders Carlsson33da07d2009-06-04 02:53:13 +00001359 CGF.PopConditionalTempDestruction();
1360
Chris Lattner7f02f722007-08-24 05:35:26 +00001361 // Reaquire the RHS block, as there may be subblocks inserted.
1362 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00001363
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001364 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1365 // into the phi node for the edge with the value of RHSCond.
1366 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001367 PN->addIncoming(RHSCond, RHSBlock);
1368
1369 // ZExt result to int.
1370 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1371}
1372
1373Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1374 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001375 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001376 return Visit(E->getRHS());
1377}
1378
1379//===----------------------------------------------------------------------===//
1380// Other Operators
1381//===----------------------------------------------------------------------===//
1382
Chris Lattner9802a512008-11-12 08:55:54 +00001383/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1384/// expression is cheap enough and side-effect-free enough to evaluate
1385/// unconditionally instead of conditionally. This is used to convert control
1386/// flow into selects in some cases.
1387static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1388 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1389 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1390
1391 // TODO: Allow anything we can constant fold to an integer or fp constant.
1392 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1393 isa<FloatingLiteral>(E))
1394 return true;
1395
1396 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1397 // X and Y are local variables.
1398 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1399 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1400 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1401 return true;
1402
1403 return false;
1404}
1405
1406
Chris Lattner7f02f722007-08-24 05:35:26 +00001407Value *ScalarExprEmitter::
1408VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001409 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00001410 // If the condition constant folds and can be elided, try to avoid emitting
1411 // the condition and the dead arm.
1412 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001413 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001414 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001415 std::swap(Live, Dead);
Chris Lattner31a09842008-11-12 08:04:58 +00001416
1417 // If the dead side doesn't have labels we need, and if the Live side isn't
1418 // the gnu missing ?: extension (which we could handle, but don't bother
1419 // to), just emit the Live part.
1420 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1421 Live) // Live part isn't missing.
1422 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001423 }
1424
Chris Lattner9802a512008-11-12 08:55:54 +00001425
1426 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1427 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001428 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001429 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1430 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1431 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1432 llvm::Value *LHS = Visit(E->getLHS());
1433 llvm::Value *RHS = Visit(E->getRHS());
1434 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1435 }
1436
1437
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001438 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1439 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001440 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001441 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001442
Chris Lattner12d152f2009-02-13 23:35:32 +00001443 // If we don't have the GNU missing condition extension, emit a branch on
1444 // bool the normal way.
1445 if (E->getLHS()) {
1446 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1447 // the branch on bool.
1448 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1449 } else {
1450 // Otherwise, for the ?: extension, evaluate the conditional and then
1451 // convert it to bool the hard way. We do this explicitly because we need
1452 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001453 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00001454
1455 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1456 // if there are no extra uses (an optimization). Inhibit this by making an
1457 // extra dead use, because we're going to add a use of CondVal later. We
1458 // don't use the builder for this, because we don't want it to get optimized
1459 // away. This leaves dead code, but the ?: extension isn't common.
1460 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1461 Builder.GetInsertBlock());
1462
Chris Lattner035cf422008-11-12 08:08:13 +00001463 Value *CondBoolVal =
1464 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1465 CGF.getContext().BoolTy);
1466 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001467 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001468
1469 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001470 CGF.EmitBlock(LHSBlock);
1471
1472 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001473 Value *LHS;
1474 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001475 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001476 else // Perform promotions, to handle cases like "short ?: int"
1477 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1478
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001479 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001480 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001481 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001482
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001483 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001484 CGF.EmitBlock(RHSBlock);
1485
Eli Friedman856226c2008-05-16 20:38:39 +00001486 Value *RHS = Visit(E->getRHS());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001487 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001488 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001489 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001490
1491 CGF.EmitBlock(ContBlock);
1492
Nuno Lopes108f55d2008-06-04 19:15:45 +00001493 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001494 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1495 return 0;
1496 }
1497
Chris Lattner7f02f722007-08-24 05:35:26 +00001498 // Create a PHI node for the real part.
1499 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1500 PN->reserveOperandSpace(2);
1501 PN->addIncoming(LHS, LHSBlock);
1502 PN->addIncoming(RHS, RHSBlock);
1503 return PN;
1504}
1505
1506Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001507 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001508}
1509
Chris Lattner2202bce2007-11-30 17:56:23 +00001510Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001511 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001512 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1513
1514 // If EmitVAArg fails, we fall back to the LLVM instruction.
1515 if (!ArgPtr)
1516 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1517
Mike Stump7f79f9b2009-05-29 15:46:01 +00001518 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001519 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001520}
1521
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001522Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001523 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001524}
1525
Chris Lattner7f02f722007-08-24 05:35:26 +00001526//===----------------------------------------------------------------------===//
1527// Entry Point into this File
1528//===----------------------------------------------------------------------===//
1529
Mike Stump7f79f9b2009-05-29 15:46:01 +00001530/// EmitScalarExpr - Emit the computation of the specified expression of
1531/// scalar type, ignoring the result.
1532Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001533 assert(E && !hasAggregateLLVMType(E->getType()) &&
1534 "Invalid scalar expression to emit");
1535
Mike Stump7f79f9b2009-05-29 15:46:01 +00001536 return ScalarExprEmitter(*this, IgnoreResultAssign)
1537 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00001538}
Chris Lattner3707b252007-08-26 06:48:56 +00001539
1540/// EmitScalarConversion - Emit a conversion from the specified type to the
1541/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001542Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1543 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001544 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1545 "Invalid scalar expression to emit");
1546 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1547}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001548
1549/// EmitComplexToScalarConversion - Emit a conversion from the specified
1550/// complex type to the specified destination type, where the destination
1551/// type is an LLVM scalar type.
1552Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1553 QualType SrcTy,
1554 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001555 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001556 "Invalid complex -> scalar conversion");
1557 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1558 DstTy);
1559}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001560
1561Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1562 assert(V1->getType() == V2->getType() &&
1563 "Vector operands must be of the same type");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001564 unsigned NumElements =
1565 cast<llvm::VectorType>(V1->getType())->getNumElements();
1566
1567 va_list va;
1568 va_start(va, V2);
1569
1570 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001571 for (unsigned i = 0; i < NumElements; i++) {
1572 int n = va_arg(va, int);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001573 assert(n >= 0 && n < (int)NumElements * 2 &&
1574 "Vector shuffle index out of bounds!");
Owen Andersona1cf15f2009-07-14 23:10:40 +00001575 Args.push_back(VMContext.getConstantInt(llvm::Type::Int32Ty, n));
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001576 }
1577
1578 const char *Name = va_arg(va, const char *);
1579 va_end(va);
1580
Owen Andersona1cf15f2009-07-14 23:10:40 +00001581 llvm::Constant *Mask = VMContext.getConstantVector(&Args[0], NumElements);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001582
1583 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1584}
1585
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001586llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001587 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001588 llvm::Value *Vec
Owen Andersona1cf15f2009-07-14 23:10:40 +00001589 = VMContext.getUndef(VMContext.getVectorType(Vals[0]->getType(), NumVals));
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001590
Chris Lattner345f7202008-07-26 20:15:14 +00001591 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001592 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Andersona1cf15f2009-07-14 23:10:40 +00001593 llvm::Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001594 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001595 }
1596
1597 return Vec;
1598}