blob: d94ee5bed218173dc281d4bfb84f78420c7c58b3 [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"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000030
Chris Lattner7f02f722007-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 Lattner1f1ded92007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-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 Dunbar45d196b2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000051 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000052 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000053public:
54
Mike Stump7f79f9b2009-05-29 15:46:01 +000055 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Owen Andersona1cf15f2009-07-14 23:10:40 +000056 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
57 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000058 }
Chris Lattner7f02f722007-08-24 05:35:26 +000059
60 //===--------------------------------------------------------------------===//
61 // Utilities
62 //===--------------------------------------------------------------------===//
63
Mike Stump7f79f9b2009-05-29 15:46:01 +000064 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000065 bool I = IgnoreResultAssign;
66 IgnoreResultAssign = false;
67 return I;
68 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000069
Chris Lattner7f02f722007-08-24 05:35:26 +000070 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
71 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
72
73 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000074 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000075 }
76
77 /// EmitLoadOfLValue - Given an expression with complex type that represents a
78 /// value l-value, this method emits the address of the l-value, then loads
79 /// and returns the result.
80 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +000081 return EmitLoadOfLValue(EmitLValue(E), E->getType());
82 }
83
Chris Lattner9abc84e2007-08-26 16:42:57 +000084 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000085 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000086 Value *EmitConversionToBool(Value *Src, QualType DstTy);
87
Chris Lattner3707b252007-08-26 06:48:56 +000088 /// EmitScalarConversion - Emit a conversion from the specified type to the
89 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000090 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
91
92 /// EmitComplexToScalarConversion - Emit a conversion from the specified
93 /// complex type to the specified destination type, where the destination
94 /// type is an LLVM scalar type.
95 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
96 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000097
Chris Lattner7f02f722007-08-24 05:35:26 +000098 //===--------------------------------------------------------------------===//
99 // Visitor Methods
100 //===--------------------------------------------------------------------===//
101
102 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000103 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000104 assert(0 && "Stmt can't have complex result type!");
105 return 0;
106 }
107 Value *VisitExpr(Expr *S);
108 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
109
110 // Leaves.
111 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000112 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000113 }
114 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000115 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000116 }
117 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000119 }
Nate Begemane7579b52007-11-15 05:40:03 +0000120 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000121 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000122 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000123 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000124 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000125 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000126 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000127 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Anders Carlsson3f704562008-12-21 22:39:40 +0000128 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000129 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000130 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000131 CGF.getContext().typesAreCompatible(
132 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000133 }
Sebastian Redl05189992008-11-11 17:56:53 +0000134 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000135 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar54d19092008-08-16 01:41:47 +0000136 llvm::Value *V =
Owen Anderson0032b272009-08-13 21:57:51 +0000137 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
Daniel Dunbar54d19092008-08-16 01:41:47 +0000138 CGF.GetIDForAddrOfLabel(E->getLabel()));
139
140 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000141 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000142
143 // l-values.
144 Value *VisitDeclRefExpr(DeclRefExpr *E) {
145 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000146 return llvm::ConstantInt::get(VMContext, EC->getInitVal());
Chris Lattner7f02f722007-08-24 05:35:26 +0000147 return EmitLoadOfLValue(E);
148 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000149 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
150 return CGF.EmitObjCSelectorExpr(E);
151 }
152 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
153 return CGF.EmitObjCProtocolExpr(E);
154 }
155 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
156 return EmitLoadOfLValue(E);
157 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000158 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000159 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000160 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000161 Value *VisitObjCImplicitSetterGetterRefExpr(
162 ObjCImplicitSetterGetterRefExpr *E) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000163 return EmitLoadOfLValue(E);
164 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000165 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
166 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000167 }
168
Chris Lattner7f02f722007-08-24 05:35:26 +0000169 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000170 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000171 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000172 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000173 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
174 return EmitLoadOfLValue(E);
175 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000177 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
178 return EmitLValue(E).getAddress();
179 }
180
Chris Lattnerd9f69102008-08-10 01:53:14 +0000181 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000182
183 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000184 bool Ignore = TestAndClearIgnoreResultAssign();
185 (void)Ignore;
186 assert (Ignore == false && "init list ignored");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000187 unsigned NumInitElements = E->getNumInits();
188
Douglas Gregora9c87802009-01-29 19:42:23 +0000189 if (E->hadArrayRangeDesignator()) {
190 CGF.ErrorUnsupported(E, "GNU array range designator extension");
191 }
192
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000193 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000194 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
195
196 // We have a scalar in braces. Just use the first element.
197 if (!VType)
198 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000199
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000200 unsigned NumVectorElements = VType->getNumElements();
201 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000202
203 // Emit individual vector element stores.
Owen Anderson03e20502009-07-30 23:11:26 +0000204 llvm::Value *V = llvm::UndefValue::get(VType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000205
Anders Carlsson222d2c82007-12-18 02:45:33 +0000206 // Emit initializers
207 unsigned i;
208 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000209 Value *NewV = Visit(E->getInit(i));
Owen Anderson0032b272009-08-13 21:57:51 +0000210 Value *Idx =
211 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Devang Patela83cc332007-10-24 18:05:48 +0000212 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000213 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000214
215 // Emit remaining default initializers
216 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Anderson0032b272009-08-13 21:57:51 +0000217 Value *Idx =
218 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000219 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000220 V = Builder.CreateInsertElement(V, NewV, Idx);
221 }
222
Devang Patela83cc332007-10-24 18:05:48 +0000223 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000224 }
Chris Lattner04421082008-04-08 04:40:51 +0000225
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000226 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000227 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000228 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000229 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000230 Value *VisitCastExpr(const CastExpr *E) {
231 // Make sure to evaluate VLA bounds now so that we have them for later.
232 if (E->getType()->isVariablyModifiedType())
233 CGF.EmitVLASize(E->getType());
234
Anders Carlsson4e382f32009-08-24 18:12:39 +0000235 return EmitCastExpr(E->getSubExpr(), E->getType(), E->getCastKind());
Chris Lattner7f02f722007-08-24 05:35:26 +0000236 }
Anders Carlsson4e382f32009-08-24 18:12:39 +0000237 Value *EmitCastExpr(const Expr *E, QualType T, CastExpr::CastKind Kind);
Chris Lattner7f02f722007-08-24 05:35:26 +0000238
239 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000240 if (E->getCallReturnType()->isReferenceType())
241 return EmitLoadOfLValue(E);
242
Chris Lattner9b655512007-08-31 22:49:20 +0000243 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000244 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000245
Chris Lattner33793202007-08-31 22:09:40 +0000246 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000247
Mike Stumpa99038c2009-02-28 09:07:16 +0000248 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattner33793202007-08-31 22:09:40 +0000249
Chris Lattner7f02f722007-08-24 05:35:26 +0000250 // Unary Operators.
251 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
252 Value *VisitUnaryPostDec(const UnaryOperator *E) {
253 return VisitPrePostIncDec(E, false, false);
254 }
255 Value *VisitUnaryPostInc(const UnaryOperator *E) {
256 return VisitPrePostIncDec(E, true, false);
257 }
258 Value *VisitUnaryPreDec(const UnaryOperator *E) {
259 return VisitPrePostIncDec(E, false, true);
260 }
261 Value *VisitUnaryPreInc(const UnaryOperator *E) {
262 return VisitPrePostIncDec(E, true, true);
263 }
264 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
265 return EmitLValue(E->getSubExpr()).getAddress();
266 }
267 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
268 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000269 // This differs from gcc, though, most likely due to a bug in gcc.
270 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000271 return Visit(E->getSubExpr());
272 }
273 Value *VisitUnaryMinus (const UnaryOperator *E);
274 Value *VisitUnaryNot (const UnaryOperator *E);
275 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000276 Value *VisitUnaryReal (const UnaryOperator *E);
277 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000278 Value *VisitUnaryExtension(const UnaryOperator *E) {
279 return Visit(E->getSubExpr());
280 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000281 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000282
283 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000284 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
285 return Visit(DAE->getExpr());
286 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000287 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
288 return CGF.LoadCXXThis();
289 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000290
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000291 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000292 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000293 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000294 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
295 return CGF.EmitCXXNewExpr(E);
296 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000297 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
298 CGF.EmitCXXDeleteExpr(E);
299 return 0;
300 }
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000301
Chris Lattner7f02f722007-08-24 05:35:26 +0000302 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stump035cf892009-04-02 18:15:54 +0000304 if (CGF.getContext().getLangOptions().OverflowChecking
305 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000306 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000307 if (Ops.LHS->getType()->isFPOrFPVector())
308 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000309 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
310 }
Mike Stump2add4732009-04-01 20:28:16 +0000311 /// Create a binary op that checks for overflow.
312 /// Currently only supports +, - and *.
313 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000314 Value *EmitDiv(const BinOpInfo &Ops);
315 Value *EmitRem(const BinOpInfo &Ops);
316 Value *EmitAdd(const BinOpInfo &Ops);
317 Value *EmitSub(const BinOpInfo &Ops);
318 Value *EmitShl(const BinOpInfo &Ops);
319 Value *EmitShr(const BinOpInfo &Ops);
320 Value *EmitAnd(const BinOpInfo &Ops) {
321 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
322 }
323 Value *EmitXor(const BinOpInfo &Ops) {
324 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
325 }
326 Value *EmitOr (const BinOpInfo &Ops) {
327 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
328 }
329
Chris Lattner1f1ded92007-08-24 21:00:35 +0000330 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000331 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000332 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
333
334 // Binary operators and binary compound assignment operators.
335#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000336 Value *VisitBin ## OP(const BinaryOperator *E) { \
337 return Emit ## OP(EmitBinOps(E)); \
338 } \
339 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
340 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000341 }
342 HANDLEBINOP(Mul);
343 HANDLEBINOP(Div);
344 HANDLEBINOP(Rem);
345 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000346 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000347 HANDLEBINOP(Shl);
348 HANDLEBINOP(Shr);
349 HANDLEBINOP(And);
350 HANDLEBINOP(Xor);
351 HANDLEBINOP(Or);
352#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000353
Chris Lattner7f02f722007-08-24 05:35:26 +0000354 // Comparisons.
355 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
356 unsigned SICmpOpc, unsigned FCmpOpc);
357#define VISITCOMP(CODE, UI, SI, FP) \
358 Value *VisitBin##CODE(const BinaryOperator *E) { \
359 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
360 llvm::FCmpInst::FP); }
361 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
362 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
363 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
364 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
365 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
366 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
367#undef VISITCOMP
368
369 Value *VisitBinAssign (const BinaryOperator *E);
370
371 Value *VisitBinLAnd (const BinaryOperator *E);
372 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000373 Value *VisitBinComma (const BinaryOperator *E);
374
375 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000376 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000377 Value *VisitConditionalOperator(const ConditionalOperator *CO);
378 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000379 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000380 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
381 return CGF.EmitObjCStringLiteral(E);
382 }
383};
384} // end anonymous namespace.
385
386//===----------------------------------------------------------------------===//
387// Utilities
388//===----------------------------------------------------------------------===//
389
Chris Lattner9abc84e2007-08-26 16:42:57 +0000390/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000391/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000392Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
393 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
394
395 if (SrcType->isRealFloatingType()) {
396 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000397 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000398 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
399 }
400
Anders Carlsson237957c2009-08-09 18:26:27 +0000401 if (SrcType->isMemberPointerType()) {
402 // FIXME: This is ABI specific.
403
404 // Compare against -1.
405 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
406 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
407 }
408
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000409 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000410 "Unknown scalar type to convert");
411
412 // Because of the type rules of C, we often end up computing a logical value,
413 // then zero extending it to int, then wanting it as a logical value again.
414 // Optimize this common case.
415 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000416 if (ZI->getOperand(0)->getType() ==
417 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000418 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000419 // If there aren't any more uses, zap the instruction to save space.
420 // Note that there can be more uses, for example if this
421 // is the result of an assignment.
422 if (ZI->use_empty())
423 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000424 return Result;
425 }
426 }
427
428 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000429 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000430 return Builder.CreateICmpNE(Src, Zero, "tobool");
431}
432
Chris Lattner3707b252007-08-26 06:48:56 +0000433/// EmitScalarConversion - Emit a conversion from the specified type to the
434/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000435Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
436 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000437 SrcType = CGF.getContext().getCanonicalType(SrcType);
438 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000439 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000440
441 if (DstType->isVoidType()) return 0;
Owen Anderson0032b272009-08-13 21:57:51 +0000442
443 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner3707b252007-08-26 06:48:56 +0000444
445 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000446 if (DstType->isBooleanType())
447 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000448
449 const llvm::Type *DstTy = ConvertType(DstType);
450
451 // Ignore conversions like int -> uint.
452 if (Src->getType() == DstTy)
453 return Src;
454
Daniel Dunbar270cc662008-08-25 09:51:32 +0000455 // Handle pointer conversions next: pointers can only be converted
456 // to/from other pointers and integers. Check for pointer types in
457 // terms of LLVM, as some native types (like Obj-C id) may map to a
458 // pointer type.
459 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000460 // The source value may be an integer, or a pointer.
Fariborz Jahanianfa9f8b42009-07-28 22:00:58 +0000461 if (isa<llvm::PointerType>(Src->getType())) {
462 // Some heavy lifting for derived to base conversion.
Fariborz Jahaniana91d6a62009-07-29 00:44:13 +0000463 if (const CXXRecordDecl *ClassDecl =
464 SrcType->getCXXRecordDeclForPointerType())
465 if (const CXXRecordDecl *BaseClassDecl =
466 DstType->getCXXRecordDeclForPointerType())
467 Src = CGF.AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl);
Chris Lattner3707b252007-08-26 06:48:56 +0000468 return Builder.CreateBitCast(Src, DstTy, "conv");
Fariborz Jahanianfa9f8b42009-07-28 22:00:58 +0000469 }
Chris Lattner3707b252007-08-26 06:48:56 +0000470 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000471 // First, convert to the correct width so that we control the kind of
472 // extension.
Owen Anderson0032b272009-08-13 21:57:51 +0000473 const llvm::Type *MiddleTy =
474 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Eli Friedman25615422009-03-04 04:02:35 +0000475 bool InputSigned = SrcType->isSignedIntegerType();
476 llvm::Value* IntResult =
477 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
478 // Then, cast to pointer.
479 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000480 }
481
Daniel Dunbar270cc662008-08-25 09:51:32 +0000482 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000483 // Must be an ptr to int cast.
484 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000485 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000486 }
487
Nate Begeman213541a2008-04-18 23:10:10 +0000488 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000489 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000490 // Cast the scalar to element type
491 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
492 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
493
494 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000495 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Owen Anderson0032b272009-08-13 21:57:51 +0000496 llvm::Value *Idx =
497 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000498 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
499
500 // Splat the element across to all elements
501 llvm::SmallVector<llvm::Constant*, 16> Args;
502 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
503 for (unsigned i = 0; i < NumElements; i++)
Owen Anderson0032b272009-08-13 21:57:51 +0000504 Args.push_back(llvm::ConstantInt::get(
505 llvm::Type::getInt32Ty(VMContext), 0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000506
Owen Anderson4a289322009-07-28 21:22:35 +0000507 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000508 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
509 return Yay;
510 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000511
Chris Lattner3b1ae002008-02-02 04:51:41 +0000512 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000513 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000514 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000515 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000516
Chris Lattner3707b252007-08-26 06:48:56 +0000517 // Finally, we have the arithmetic types: real int/float.
518 if (isa<llvm::IntegerType>(Src->getType())) {
519 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000520 if (isa<llvm::IntegerType>(DstTy))
521 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
522 else if (InputSigned)
523 return Builder.CreateSIToFP(Src, DstTy, "conv");
524 else
525 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000526 }
527
528 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
529 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000530 if (DstType->isSignedIntegerType())
531 return Builder.CreateFPToSI(Src, DstTy, "conv");
532 else
533 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000534 }
535
536 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000537 if (DstTy->getTypeID() < Src->getType()->getTypeID())
538 return Builder.CreateFPTrunc(Src, DstTy, "conv");
539 else
540 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000541}
542
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000543/// EmitComplexToScalarConversion - Emit a conversion from the specified
544/// complex type to the specified destination type, where the destination
545/// type is an LLVM scalar type.
546Value *ScalarExprEmitter::
547EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
548 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000549 // Get the source element type.
Chris Lattner96196622008-07-26 22:37:01 +0000550 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnered70f0a2007-08-26 16:52:28 +0000551
552 // Handle conversions to bool first, they are special: comparisons against 0.
553 if (DstTy->isBooleanType()) {
554 // Complex != 0 -> (Real != 0) | (Imag != 0)
555 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
556 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
557 return Builder.CreateOr(Src.first, Src.second, "tobool");
558 }
559
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000560 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
561 // the imaginary part of the complex value is discarded and the value of the
562 // real part is converted according to the conversion rules for the
563 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000564 return EmitScalarConversion(Src.first, SrcTy, DstTy);
565}
566
567
Chris Lattner7f02f722007-08-24 05:35:26 +0000568//===----------------------------------------------------------------------===//
569// Visitor Methods
570//===----------------------------------------------------------------------===//
571
572Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000573 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000574 if (E->getType()->isVoidType())
575 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000576 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000577}
578
Eli Friedmand38617c2008-05-14 19:38:39 +0000579Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
580 llvm::SmallVector<llvm::Constant*, 32> indices;
581 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
582 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
583 }
584 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
585 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson4a289322009-07-28 21:22:35 +0000586 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000587 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
588}
589
Chris Lattner7f02f722007-08-24 05:35:26 +0000590Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000591 TestAndClearIgnoreResultAssign();
592
Chris Lattner7f02f722007-08-24 05:35:26 +0000593 // Emit subscript expressions in rvalue context's. For most cases, this just
594 // loads the lvalue formed by the subscript expr. However, we have to be
595 // careful, because the base of a vector subscript is occasionally an rvalue,
596 // so we can't get it as an lvalue.
597 if (!E->getBase()->getType()->isVectorType())
598 return EmitLoadOfLValue(E);
599
600 // Handle the vector case. The base must be a vector, the index must be an
601 // integer value.
602 Value *Base = Visit(E->getBase());
603 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000604 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Owen Anderson0032b272009-08-13 21:57:51 +0000605 Idx = Builder.CreateIntCast(Idx,
606 llvm::Type::getInt32Ty(CGF.getLLVMContext()),
607 IdxSigned,
Eli Friedman515ff5a2009-03-28 03:27:06 +0000608 "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000609 return Builder.CreateExtractElement(Base, Idx, "vecext");
610}
611
612/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
613/// also handle things like function to pointer-to-function decay, and array to
614/// pointer decay.
615Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
616 const Expr *Op = E->getSubExpr();
617
618 // If this is due to array->pointer conversion, emit the array expression as
619 // an l-value.
620 if (Op->getType()->isArrayType()) {
Anders Carlsson112a0a82009-08-07 23:48:20 +0000621 assert(E->getCastKind() == CastExpr::CK_ArrayToPointerDecay);
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000622 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000623
Eli Friedmandaa24a22009-03-28 02:45:41 +0000624 // Note that VLA pointers are always decayed, so we don't need to do
625 // anything here.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000626 if (!Op->getType()->isVariableArrayType()) {
627 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
628 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
629 ->getElementType()) &&
630 "Expected pointer to array");
631 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar662174c82008-08-29 17:28:43 +0000632 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000633
634 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerf31627f2008-07-23 06:31:27 +0000635 // types as well (e.g. void*) and can be implicitly converted to integer.
636 const llvm::Type *DestTy = ConvertType(E->getType());
637 if (V->getType() != DestTy) {
638 if (isa<llvm::PointerType>(DestTy))
639 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
640 else {
641 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
642 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
643 }
644 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000645 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000646 }
Eli Friedmandaa24a22009-03-28 02:45:41 +0000647
Anders Carlsson4e382f32009-08-24 18:12:39 +0000648 return EmitCastExpr(Op, E->getType(), E->getCastKind());
Chris Lattner7f02f722007-08-24 05:35:26 +0000649}
650
651
652// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
653// have to handle a more broad range of conversions than explicit casts, as they
654// handle things like function to ptr-to-function decay etc.
Anders Carlsson4e382f32009-08-24 18:12:39 +0000655Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy,
656 CastExpr::CastKind Kind) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000657 if (!DestTy->isVoidType())
658 TestAndClearIgnoreResultAssign();
659
Chris Lattner58a2e942007-08-26 07:26:12 +0000660 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000661
662 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000663 Value *Src = Visit(const_cast<Expr*>(E));
664
Chris Lattner3707b252007-08-26 06:48:56 +0000665 // Use EmitScalarConversion to perform the conversion.
666 return EmitScalarConversion(Src, E->getType(), DestTy);
667 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000668
Chris Lattner9b2dc282008-04-04 16:54:41 +0000669 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000670 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000671 bool IgnoreImag = true;
672 bool IgnoreImagAssign = true;
673 bool IgnoreReal = IgnoreResultAssign;
674 bool IgnoreRealAssign = IgnoreResultAssign;
675 if (DestTy->isBooleanType())
676 IgnoreImagAssign = IgnoreImag = false;
677 else if (DestTy->isVoidType()) {
678 IgnoreReal = IgnoreImag = false;
679 IgnoreRealAssign = IgnoreImagAssign = true;
680 }
681 CodeGenFunction::ComplexPairTy V
682 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
683 IgnoreImagAssign);
684 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000685 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000686
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000687 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
688 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000689 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000690 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000691}
692
Chris Lattner33793202007-08-31 22:09:40 +0000693Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000694 return CGF.EmitCompoundStmt(*E->getSubStmt(),
695 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000696}
697
Mike Stumpa99038c2009-02-28 09:07:16 +0000698Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
699 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +0000700}
Chris Lattner33793202007-08-31 22:09:40 +0000701
Chris Lattner7f02f722007-08-24 05:35:26 +0000702//===----------------------------------------------------------------------===//
703// Unary Operators
704//===----------------------------------------------------------------------===//
705
706Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000707 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000708 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000709 QualType ValTy = E->getSubExpr()->getType();
710 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Owen Anderson0032b272009-08-13 21:57:51 +0000711
712 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner7f02f722007-08-24 05:35:26 +0000713
714 int AmountVal = isInc ? 1 : -1;
Eli Friedmandaa24a22009-03-28 02:45:41 +0000715
716 if (ValTy->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000717 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000718 // The amount of the addition/subtraction needs to account for the VLA size
719 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
720 }
721
Chris Lattner7f02f722007-08-24 05:35:26 +0000722 Value *NextVal;
Chris Lattner8cc9d082009-03-18 04:25:13 +0000723 if (const llvm::PointerType *PT =
724 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000725 llvm::Constant *Inc =
Owen Anderson0032b272009-08-13 21:57:51 +0000726 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000727 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000728 QualType PTEE = ValTy->getPointeeType();
729 if (const ObjCInterfaceType *OIT =
730 dyn_cast<ObjCInterfaceType>(PTEE)) {
731 // Handle interface types, which are not represented with a concrete type.
732 int size = CGF.getContext().getTypeSize(OIT) / 8;
733 if (!isInc)
734 size = -size;
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000735 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000736 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +0000737 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000738 InVal = Builder.CreateBitCast(InVal, i8Ty);
739 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
740 llvm::Value *lhs = LV.getAddress();
Owen Anderson96e0fc72009-07-29 22:16:19 +0000741 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000742 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
743 CGF.getContext().getObjCGCAttrKind(ValTy));
Mike Stumpb3589f42009-07-30 22:28:39 +0000744 } else
Dan Gohman664f8932009-08-12 00:33:55 +0000745 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
Chris Lattner8cc9d082009-03-18 04:25:13 +0000746 } else {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000747 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +0000748 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Chris Lattner8cc9d082009-03-18 04:25:13 +0000749 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
750 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
751 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
752 }
Owen Anderson0032b272009-08-13 21:57:51 +0000753 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +0000754 // Bool++ is an interesting case, due to promotion rules, we get:
755 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
756 // Bool = ((int)Bool+1) != 0
757 // An interesting aspect of this is that increment is always true.
758 // Decrement does not have this property.
Owen Anderson3b144ba2009-07-31 17:39:36 +0000759 NextVal = llvm::ConstantInt::getTrue(VMContext);
Chris Lattner87415d22009-06-17 06:36:24 +0000760 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000761 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Dan Gohmanbf933a02009-08-12 01:16:29 +0000762
763 // Signed integer overflow is undefined behavior.
764 if (ValTy->isSignedIntegerType())
765 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
766 else
767 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000768 } else {
769 // Add the inc/dec to the real part.
Owen Anderson0032b272009-08-13 21:57:51 +0000770 if (InVal->getType() == llvm::Type::getFloatTy(VMContext))
Devang Patele9b8c0a2007-10-30 20:59:40 +0000771 NextVal =
Owen Andersonbc0a2222009-07-27 21:00:51 +0000772 llvm::ConstantFP::get(VMContext,
773 llvm::APFloat(static_cast<float>(AmountVal)));
Owen Anderson0032b272009-08-13 21:57:51 +0000774 else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext))
Devang Patele9b8c0a2007-10-30 20:59:40 +0000775 NextVal =
Owen Andersonbc0a2222009-07-27 21:00:51 +0000776 llvm::ConstantFP::get(VMContext,
777 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000778 else {
779 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000780 bool ignored;
781 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
782 &ignored);
Owen Andersonbc0a2222009-07-27 21:00:51 +0000783 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000784 }
Chris Lattner87415d22009-06-17 06:36:24 +0000785 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000786 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000787
788 // Store the updated result through the lvalue.
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000789 if (LV.isBitfield())
790 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
791 &NextVal);
792 else
793 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner7f02f722007-08-24 05:35:26 +0000794
795 // If this is a postinc, return the value read from memory, otherwise use the
796 // updated value.
797 return isPre ? NextVal : InVal;
798}
799
800
801Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000802 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000803 Value *Op = Visit(E->getSubExpr());
Chris Lattner87415d22009-06-17 06:36:24 +0000804 if (Op->getType()->isFPOrFPVector())
805 return Builder.CreateFNeg(Op, "neg");
Chris Lattner7f02f722007-08-24 05:35:26 +0000806 return Builder.CreateNeg(Op, "neg");
807}
808
809Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000810 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000811 Value *Op = Visit(E->getSubExpr());
812 return Builder.CreateNot(Op, "neg");
813}
814
815Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
816 // Compare operand to zero.
817 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
818
819 // Invert value.
820 // TODO: Could dynamically modify easy computations here. For example, if
821 // the operand is an icmp ne, turn into icmp eq.
822 BoolVal = Builder.CreateNot(BoolVal, "lnot");
823
Anders Carlsson9f84d882009-05-19 18:44:53 +0000824 // ZExt result to the expr type.
825 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +0000826}
827
Sebastian Redl05189992008-11-11 17:56:53 +0000828/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
829/// argument of the sizeof expression as an integer.
830Value *
831ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +0000832 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000833 if (E->isSizeOf()) {
834 if (const VariableArrayType *VAT =
835 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
836 if (E->isArgumentType()) {
837 // sizeof(type) - make sure to emit the VLA size.
838 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +0000839 } else {
840 // C99 6.5.3.4p2: If the argument is an expression of type
841 // VLA, it is evaluated.
842 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000843 }
Anders Carlsson6cd586d2009-01-30 16:41:04 +0000844
Anders Carlsson96f21472009-02-05 19:43:10 +0000845 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000846 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000847 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000848
849 // If this isn't sizeof(vla), the result must be constant; use the
850 // constant folding logic so we don't have to duplicate it here.
851 Expr::EvalResult Result;
852 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000853 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +0000854}
855
Chris Lattner46f93d02007-08-24 21:20:17 +0000856Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
857 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000858 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000859 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +0000860 return Visit(Op);
861}
862Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
863 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000864 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000865 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000866
Mike Stump7f79f9b2009-05-29 15:46:01 +0000867 // __imag on a scalar returns zero. Emit the subexpr to ensure side
868 // effects are evaluated, but not the actual value.
869 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
870 CGF.EmitLValue(Op);
871 else
872 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000873 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000874}
875
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000876Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
877{
Eli Friedman35183ac2009-02-27 06:44:11 +0000878 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +0000879 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +0000880 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000881}
Chris Lattner46f93d02007-08-24 21:20:17 +0000882
Chris Lattner7f02f722007-08-24 05:35:26 +0000883//===----------------------------------------------------------------------===//
884// Binary Operators
885//===----------------------------------------------------------------------===//
886
887BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000888 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000889 BinOpInfo Result;
890 Result.LHS = Visit(E->getLHS());
891 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000892 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000893 Result.E = E;
894 return Result;
895}
896
Chris Lattner3ccf7742007-08-26 21:41:21 +0000897Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000898 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000899 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000900 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
901
902 BinOpInfo OpInfo;
903
Eli Friedmanab3a8522009-03-28 01:22:36 +0000904 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000905 // This needs to go through the complex expression emitter, but
Eli Friedmanab3a8522009-03-28 01:22:36 +0000906 // it's a tad complicated to do that... I'm leaving it out for now.
907 // (Note that we do actually need the imaginary part of the RHS for
908 // multiplication and division.)
909 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Anderson03e20502009-07-30 23:11:26 +0000910 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Eli Friedmanab3a8522009-03-28 01:22:36 +0000911 }
912
Mike Stumpcc0442f2009-05-22 19:07:20 +0000913 // Emit the RHS first. __block variables need to have the rhs evaluated
914 // first, plus this should improve codegen a little.
915 OpInfo.RHS = Visit(E->getRHS());
916 OpInfo.Ty = E->getComputationResultType();
917 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +0000918 // Load/convert the LHS.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000919 LValue LHSLV = EmitLValue(E->getLHS());
920 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000921 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
922 E->getComputationLHSType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000923
924 // Expand the binary operator.
925 Value *Result = (this->*Func)(OpInfo);
926
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000927 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +0000928 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
929
Daniel Dunbared3849b2008-11-19 09:36:46 +0000930 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar371d16f2008-11-19 11:54:05 +0000931 // handled specially because the result is altered by the store,
932 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
933 // the left operand after the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000934 if (LHSLV.isBitfield()) {
935 if (!LHSLV.isVolatileQualified()) {
936 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
937 &Result);
938 return Result;
939 } else
940 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
941 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +0000942 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stump7f79f9b2009-05-29 15:46:01 +0000943 if (Ignore)
944 return 0;
945 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000946}
947
948
Chris Lattner7f02f722007-08-24 05:35:26 +0000949Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000950 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000951 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000952 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000953 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
954 else
955 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
956}
957
958Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
959 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000960 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000961 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
962 else
963 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
964}
965
Mike Stump2add4732009-04-01 20:28:16 +0000966Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
967 unsigned IID;
968 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000969
Mike Stump035cf892009-04-02 18:15:54 +0000970 switch (Ops.E->getOpcode()) {
971 case BinaryOperator::Add:
972 case BinaryOperator::AddAssign:
973 OpID = 1;
974 IID = llvm::Intrinsic::sadd_with_overflow;
975 break;
976 case BinaryOperator::Sub:
977 case BinaryOperator::SubAssign:
978 OpID = 2;
979 IID = llvm::Intrinsic::ssub_with_overflow;
980 break;
981 case BinaryOperator::Mul:
982 case BinaryOperator::MulAssign:
983 OpID = 3;
984 IID = llvm::Intrinsic::smul_with_overflow;
985 break;
986 default:
987 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +0000988 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +0000989 }
Mike Stump035cf892009-04-02 18:15:54 +0000990 OpID <<= 1;
991 OpID |= 1;
992
Mike Stump2add4732009-04-01 20:28:16 +0000993 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
994
995 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
996
997 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
998 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
999 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1000
1001 // Branch in case of overflow.
1002 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1003 llvm::BasicBlock *overflowBB =
1004 CGF.createBasicBlock("overflow", CGF.CurFn);
1005 llvm::BasicBlock *continueBB =
1006 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1007
1008 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1009
1010 // Handle overflow
1011
1012 Builder.SetInsertPoint(overflowBB);
1013
1014 // Handler is:
1015 // long long *__overflow_handler)(long long a, long long b, char op,
1016 // char width)
1017 std::vector<const llvm::Type*> handerArgTypes;
Owen Anderson0032b272009-08-13 21:57:51 +00001018 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1019 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1020 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1021 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1022 llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1023 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
Mike Stump2add4732009-04-01 20:28:16 +00001024 llvm::Value *handlerFunction =
1025 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson96e0fc72009-07-29 22:16:19 +00001026 llvm::PointerType::getUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +00001027 handlerFunction = Builder.CreateLoad(handlerFunction);
1028
1029 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
Owen Anderson0032b272009-08-13 21:57:51 +00001030 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1031 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1032 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1033 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
Mike Stump2add4732009-04-01 20:28:16 +00001034 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1035
1036 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1037
1038 Builder.CreateBr(continueBB);
1039
1040 // Set up the continuation
1041 Builder.SetInsertPoint(continueBB);
1042 // Get the correct result
1043 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1044 phi->reserveOperandSpace(2);
1045 phi->addIncoming(result, initialBB);
1046 phi->addIncoming(handlerResult, overflowBB);
1047
1048 return phi;
1049}
Chris Lattner7f02f722007-08-24 05:35:26 +00001050
1051Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001052 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner87415d22009-06-17 06:36:24 +00001053 if (CGF.getContext().getLangOptions().OverflowChecking &&
1054 Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001055 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001056
1057 if (Ops.LHS->getType()->isFPOrFPVector())
1058 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001059
1060 // Signed integer overflow is undefined behavior.
1061 if (Ops.Ty->isSignedIntegerType())
1062 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1063
Chris Lattner7f02f722007-08-24 05:35:26 +00001064 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001065 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001066
Steve Naroff14108da2009-07-10 23:34:53 +00001067 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001068 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001069 // The amount of the addition needs to account for the VLA size
1070 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1071 }
Chris Lattner8f925282008-01-03 06:36:51 +00001072 Value *Ptr, *Idx;
1073 Expr *IdxExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001074 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001075 const ObjCObjectPointerType *OPT =
1076 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1077 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001078 Ptr = Ops.LHS;
1079 Idx = Ops.RHS;
1080 IdxExp = Ops.E->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001081 } else { // int + pointer
Ted Kremenek6217b802009-07-29 21:53:49 +00001082 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001083 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1084 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001085 Ptr = Ops.RHS;
1086 Idx = Ops.LHS;
1087 IdxExp = Ops.E->getLHS();
1088 }
1089
1090 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001091 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001092 // Zero or sign extend the pointer value based on whether the index is
1093 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001094 const llvm::Type *IdxType =
1095 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +00001096 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001097 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1098 else
1099 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1100 }
Steve Naroff14108da2009-07-10 23:34:53 +00001101 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
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 = dyn_cast<ObjCInterfaceType>(ElementType)) {
1105 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001106 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001107 CGF.getContext().getTypeSize(OIT) / 8);
1108 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson0032b272009-08-13 21:57:51 +00001109 const llvm::Type *i8Ty =
1110 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar2a866252009-04-25 05:08:32 +00001111 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1112 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1113 return Builder.CreateBitCast(Res, Ptr->getType());
1114 }
1115
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001116 // Explicitly handle GNU void* and function pointer arithmetic
1117 // extensions. The GNU void* casts amount to no-ops since our void*
1118 // type is i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001119 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Anderson0032b272009-08-13 21:57:51 +00001120 const llvm::Type *i8Ty =
1121 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001122 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001123 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001124 return Builder.CreateBitCast(Res, Ptr->getType());
1125 }
Chris Lattner8f925282008-01-03 06:36:51 +00001126
Dan Gohman664f8932009-08-12 00:33:55 +00001127 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001128}
1129
1130Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001131 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stump035cf892009-04-02 18:15:54 +00001132 if (CGF.getContext().getLangOptions().OverflowChecking
1133 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001134 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001135
1136 if (Ops.LHS->getType()->isFPOrFPVector())
1137 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner7f02f722007-08-24 05:35:26 +00001138 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001139 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001140
Steve Naroff14108da2009-07-10 23:34:53 +00001141 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001142 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001143 // The amount of the addition needs to account for the VLA size for
1144 // ptr-int
1145 // The amount of the division needs to account for the VLA size for
1146 // ptr-ptr.
1147 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1148 }
1149
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001150 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001151 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001152 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1153 // pointer - int
1154 Value *Idx = Ops.RHS;
1155 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001156 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001157 // Zero or sign extend the pointer value based on whether the index is
1158 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001159 const llvm::Type *IdxType =
1160 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001161 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1162 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1163 else
1164 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1165 }
1166 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001167
Daniel Dunbar2a866252009-04-25 05:08:32 +00001168 // Handle interface types, which are not represented with a concrete
1169 // type.
1170 if (const ObjCInterfaceType *OIT =
1171 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1172 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001173 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001174 CGF.getContext().getTypeSize(OIT) / 8);
1175 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001176 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +00001177 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar2a866252009-04-25 05:08:32 +00001178 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1179 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1180 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1181 }
1182
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001183 // Explicitly handle GNU void* and function pointer arithmetic
1184 // extensions. The GNU void* casts amount to no-ops since our
1185 // void* type is i8*, but this is future proof.
1186 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001187 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +00001188 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001189 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1190 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1191 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1192 }
1193
Dan Gohman664f8932009-08-12 00:33:55 +00001194 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001195 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001196 // pointer - pointer
1197 Value *LHS = Ops.LHS;
1198 Value *RHS = Ops.RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +00001199
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001200 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001201
Chris Lattnere5ed1512009-02-11 07:21:43 +00001202 // Handle GCC extension for pointer arithmetic on void* and function pointer
1203 // types.
1204 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001205 ElementSize = 1;
1206 } else {
1207 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1208 }
1209
1210 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1211 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1212 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1213 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1214
Chris Lattnere5ed1512009-02-11 07:21:43 +00001215 // Optimize out the shift for element size of 1.
1216 if (ElementSize == 1)
1217 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001218
1219 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1220 // pointer difference in C is only defined in the case where both
1221 // operands are pointing to elements of an array.
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001222 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Dan Gohmandf110942009-08-11 22:40:09 +00001223 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001224 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001225}
1226
1227Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1228 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1229 // RHS to the same size as the LHS.
1230 Value *RHS = Ops.RHS;
1231 if (Ops.LHS->getType() != RHS->getType())
1232 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1233
1234 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1235}
1236
1237Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1238 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1239 // RHS to the same size as the LHS.
1240 Value *RHS = Ops.RHS;
1241 if (Ops.LHS->getType() != RHS->getType())
1242 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1243
Chris Lattner1f1ded92007-08-24 21:00:35 +00001244 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001245 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1246 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1247}
1248
1249Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1250 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001251 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001252 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001253 QualType LHSTy = E->getLHS()->getType();
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001254 if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001255 Value *LHS = Visit(E->getLHS());
1256 Value *RHS = Visit(E->getRHS());
1257
Eli Friedman1360d4a2009-07-22 06:07:16 +00001258 if (LHS->getType()->isFPOrFPVector()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001259 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001260 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001261 } else if (LHSTy->isSignedIntegerType()) {
1262 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001263 LHS, RHS, "cmp");
1264 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001265 // Unsigned integers and pointers.
1266 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001267 LHS, RHS, "cmp");
1268 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001269
1270 // If this is a vector comparison, sign extend the result to the appropriate
1271 // vector integer type and return it (don't convert to bool).
1272 if (LHSTy->isVectorType())
1273 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001274
Chris Lattner7f02f722007-08-24 05:35:26 +00001275 } else {
1276 // Complex Comparison: can only be an equality comparison.
1277 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1278 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1279
Chris Lattner96196622008-07-26 22:37:01 +00001280 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner7f02f722007-08-24 05:35:26 +00001281
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001282 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001283 if (CETy->isRealFloatingType()) {
1284 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1285 LHS.first, RHS.first, "cmp.r");
1286 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1287 LHS.second, RHS.second, "cmp.i");
1288 } else {
1289 // Complex comparisons can only be equality comparisons. As such, signed
1290 // and unsigned opcodes are the same.
1291 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1292 LHS.first, RHS.first, "cmp.r");
1293 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1294 LHS.second, RHS.second, "cmp.i");
1295 }
1296
1297 if (E->getOpcode() == BinaryOperator::EQ) {
1298 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1299 } else {
1300 assert(E->getOpcode() == BinaryOperator::NE &&
1301 "Complex comparison other than == or != ?");
1302 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1303 }
1304 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001305
1306 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001307}
1308
1309Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001310 bool Ignore = TestAndClearIgnoreResultAssign();
1311
1312 // __block variables need to have the rhs evaluated first, plus this should
1313 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001314 Value *RHS = Visit(E->getRHS());
Mike Stump99459b62009-05-21 21:05:15 +00001315 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001316
Daniel Dunbared3849b2008-11-19 09:36:46 +00001317 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001318 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1319 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001320 // the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001321 if (LHS.isBitfield()) {
1322 if (!LHS.isVolatileQualified()) {
1323 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1324 &RHS);
1325 return RHS;
1326 } else
1327 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1328 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001329 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stump7f79f9b2009-05-29 15:46:01 +00001330 if (Ignore)
1331 return 0;
1332 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001333}
1334
1335Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001336 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1337 // If we have 1 && X, just emit X without inserting the control flow.
1338 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1339 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001340 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1341 // ZExt result to int.
1342 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1343 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001344
1345 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1346 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonc9c88b42009-07-31 20:28:54 +00001347 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001348 }
1349
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001350 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1351 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001352
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001353 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1354 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1355
1356 // Any edges into the ContBlock are now from an (indeterminate number of)
1357 // edges from this first condition. All of these values will be false. Start
1358 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001359 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1360 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001361 PN->reserveOperandSpace(2); // Normal case, two inputs.
1362 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1363 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001364 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Chris Lattner7f02f722007-08-24 05:35:26 +00001365
Anders Carlsson33da07d2009-06-04 02:53:13 +00001366 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001367 CGF.EmitBlock(RHSBlock);
1368 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson33da07d2009-06-04 02:53:13 +00001369 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001370
1371 // Reaquire the RHS block, as there may be subblocks inserted.
1372 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001373
1374 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1375 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001376 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001377 PN->addIncoming(RHSCond, RHSBlock);
1378
1379 // ZExt result to int.
1380 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1381}
1382
1383Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001384 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1385 // If we have 0 || X, just emit X without inserting the control flow.
1386 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1387 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001388 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1389 // ZExt result to int.
1390 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1391 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001392
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001393 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001394 if (!CGF.ContainsLabel(E->getRHS()))
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001395 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001396 }
1397
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001398 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1399 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner7f02f722007-08-24 05:35:26 +00001400
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001401 // Branch on the LHS first. If it is true, go to the success (cont) block.
1402 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1403
1404 // Any edges into the ContBlock are now from an (indeterminate number of)
1405 // edges from this first condition. All of these values will be true. Start
1406 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001407 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1408 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001409 PN->reserveOperandSpace(2); // Normal case, two inputs.
1410 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1411 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001412 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001413
Anders Carlsson33da07d2009-06-04 02:53:13 +00001414 CGF.PushConditionalTempDestruction();
1415
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001416 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001417 CGF.EmitBlock(RHSBlock);
1418 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1419
Anders Carlsson33da07d2009-06-04 02:53:13 +00001420 CGF.PopConditionalTempDestruction();
1421
Chris Lattner7f02f722007-08-24 05:35:26 +00001422 // Reaquire the RHS block, as there may be subblocks inserted.
1423 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00001424
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001425 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1426 // into the phi node for the edge with the value of RHSCond.
1427 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001428 PN->addIncoming(RHSCond, RHSBlock);
1429
1430 // ZExt result to int.
1431 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1432}
1433
1434Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1435 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001436 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001437 return Visit(E->getRHS());
1438}
1439
1440//===----------------------------------------------------------------------===//
1441// Other Operators
1442//===----------------------------------------------------------------------===//
1443
Chris Lattner9802a512008-11-12 08:55:54 +00001444/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1445/// expression is cheap enough and side-effect-free enough to evaluate
1446/// unconditionally instead of conditionally. This is used to convert control
1447/// flow into selects in some cases.
1448static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1449 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1450 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1451
1452 // TODO: Allow anything we can constant fold to an integer or fp constant.
1453 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1454 isa<FloatingLiteral>(E))
1455 return true;
1456
1457 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1458 // X and Y are local variables.
1459 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1460 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1461 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1462 return true;
1463
1464 return false;
1465}
1466
1467
Chris Lattner7f02f722007-08-24 05:35:26 +00001468Value *ScalarExprEmitter::
1469VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001470 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00001471 // If the condition constant folds and can be elided, try to avoid emitting
1472 // the condition and the dead arm.
1473 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001474 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001475 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001476 std::swap(Live, Dead);
Chris Lattner31a09842008-11-12 08:04:58 +00001477
1478 // If the dead side doesn't have labels we need, and if the Live side isn't
1479 // the gnu missing ?: extension (which we could handle, but don't bother
1480 // to), just emit the Live part.
1481 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1482 Live) // Live part isn't missing.
1483 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001484 }
1485
Chris Lattner9802a512008-11-12 08:55:54 +00001486
1487 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1488 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001489 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001490 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1491 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1492 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1493 llvm::Value *LHS = Visit(E->getLHS());
1494 llvm::Value *RHS = Visit(E->getRHS());
1495 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1496 }
1497
1498
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001499 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1500 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001501 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001502 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001503
Chris Lattner12d152f2009-02-13 23:35:32 +00001504 // If we don't have the GNU missing condition extension, emit a branch on
1505 // bool the normal way.
1506 if (E->getLHS()) {
1507 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1508 // the branch on bool.
1509 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1510 } else {
1511 // Otherwise, for the ?: extension, evaluate the conditional and then
1512 // convert it to bool the hard way. We do this explicitly because we need
1513 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001514 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00001515
1516 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1517 // if there are no extra uses (an optimization). Inhibit this by making an
1518 // extra dead use, because we're going to add a use of CondVal later. We
1519 // don't use the builder for this, because we don't want it to get optimized
1520 // away. This leaves dead code, but the ?: extension isn't common.
1521 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1522 Builder.GetInsertBlock());
1523
Chris Lattner035cf422008-11-12 08:08:13 +00001524 Value *CondBoolVal =
1525 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1526 CGF.getContext().BoolTy);
1527 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001528 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001529
1530 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001531 CGF.EmitBlock(LHSBlock);
1532
1533 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001534 Value *LHS;
1535 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001536 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001537 else // Perform promotions, to handle cases like "short ?: int"
1538 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1539
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001540 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001541 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001542 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001543
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001544 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001545 CGF.EmitBlock(RHSBlock);
1546
Eli Friedman856226c2008-05-16 20:38:39 +00001547 Value *RHS = Visit(E->getRHS());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001548 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001549 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001550 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001551
1552 CGF.EmitBlock(ContBlock);
1553
Nuno Lopes108f55d2008-06-04 19:15:45 +00001554 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001555 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1556 return 0;
1557 }
1558
Chris Lattner7f02f722007-08-24 05:35:26 +00001559 // Create a PHI node for the real part.
1560 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1561 PN->reserveOperandSpace(2);
1562 PN->addIncoming(LHS, LHSBlock);
1563 PN->addIncoming(RHS, RHSBlock);
1564 return PN;
1565}
1566
1567Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001568 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001569}
1570
Chris Lattner2202bce2007-11-30 17:56:23 +00001571Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001572 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001573 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1574
1575 // If EmitVAArg fails, we fall back to the LLVM instruction.
1576 if (!ArgPtr)
1577 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1578
Mike Stump7f79f9b2009-05-29 15:46:01 +00001579 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001580 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001581}
1582
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001583Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001584 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001585}
1586
Chris Lattner7f02f722007-08-24 05:35:26 +00001587//===----------------------------------------------------------------------===//
1588// Entry Point into this File
1589//===----------------------------------------------------------------------===//
1590
Mike Stump7f79f9b2009-05-29 15:46:01 +00001591/// EmitScalarExpr - Emit the computation of the specified expression of
1592/// scalar type, ignoring the result.
1593Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001594 assert(E && !hasAggregateLLVMType(E->getType()) &&
1595 "Invalid scalar expression to emit");
1596
Mike Stump7f79f9b2009-05-29 15:46:01 +00001597 return ScalarExprEmitter(*this, IgnoreResultAssign)
1598 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00001599}
Chris Lattner3707b252007-08-26 06:48:56 +00001600
1601/// EmitScalarConversion - Emit a conversion from the specified type to the
1602/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001603Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1604 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001605 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1606 "Invalid scalar expression to emit");
1607 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1608}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001609
1610/// EmitComplexToScalarConversion - Emit a conversion from the specified
1611/// complex type to the specified destination type, where the destination
1612/// type is an LLVM scalar type.
1613Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1614 QualType SrcTy,
1615 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001616 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001617 "Invalid complex -> scalar conversion");
1618 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1619 DstTy);
1620}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001621
1622Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1623 assert(V1->getType() == V2->getType() &&
1624 "Vector operands must be of the same type");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001625 unsigned NumElements =
1626 cast<llvm::VectorType>(V1->getType())->getNumElements();
1627
1628 va_list va;
1629 va_start(va, V2);
1630
1631 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001632 for (unsigned i = 0; i < NumElements; i++) {
1633 int n = va_arg(va, int);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001634 assert(n >= 0 && n < (int)NumElements * 2 &&
1635 "Vector shuffle index out of bounds!");
Owen Anderson0032b272009-08-13 21:57:51 +00001636 Args.push_back(llvm::ConstantInt::get(
1637 llvm::Type::getInt32Ty(VMContext), n));
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001638 }
1639
1640 const char *Name = va_arg(va, const char *);
1641 va_end(va);
1642
Owen Anderson4a289322009-07-28 21:22:35 +00001643 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001644
1645 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1646}
1647
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001648llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001649 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001650 llvm::Value *Vec
Owen Anderson03e20502009-07-30 23:11:26 +00001651 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001652
Chris Lattner345f7202008-07-26 20:15:14 +00001653 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001654 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Anderson0032b272009-08-13 21:57:51 +00001655 llvm::Value *Idx = llvm::ConstantInt::get(
1656 llvm::Type::getInt32Ty(VMContext), i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001657 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001658 }
1659
1660 return Vec;
1661}