blob: 4e16f66ba422f6f7f6daadd398836ef6b9aaf4e8 [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"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000016#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000017#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000019#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000021#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000023#include "llvm/Constants.h"
24#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000025#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000026#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000027#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000028#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000029#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000030#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000031
Chris Lattner7f02f722007-08-24 05:35:26 +000032using namespace clang;
33using namespace CodeGen;
34using llvm::Value;
35
36//===----------------------------------------------------------------------===//
37// Scalar Expression Emitter
38//===----------------------------------------------------------------------===//
39
40struct BinOpInfo {
41 Value *LHS;
42 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000043 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000044 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
45 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000046};
47
48namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000049class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000050 : public StmtVisitor<ScalarExprEmitter, Value*> {
51 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000052 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000053 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000054 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000055public:
56
Mike Stump7f79f9b2009-05-29 15:46:01 +000057 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000058 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000059 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000060 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000061
Chris Lattner7f02f722007-08-24 05:35:26 +000062 //===--------------------------------------------------------------------===//
63 // Utilities
64 //===--------------------------------------------------------------------===//
65
Mike Stump7f79f9b2009-05-29 15:46:01 +000066 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000067 bool I = IgnoreResultAssign;
68 IgnoreResultAssign = false;
69 return I;
70 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000071
Chris Lattner7f02f722007-08-24 05:35:26 +000072 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
73 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000074 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000075
76 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000077 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000078 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000079
Chris Lattner7f02f722007-08-24 05:35:26 +000080 /// EmitLoadOfLValue - Given an expression with complex type that represents a
81 /// value l-value, this method emits the address of the l-value, then loads
82 /// and returns the result.
83 Value *EmitLoadOfLValue(const Expr *E) {
Mike Stumpb14e62d2009-12-16 02:57:00 +000084 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +000085 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000086
Chris Lattner9abc84e2007-08-26 16:42:57 +000087 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000088 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000089 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000090
Chris Lattner3707b252007-08-26 06:48:56 +000091 /// EmitScalarConversion - Emit a conversion from the specified type to the
92 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000093 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
94
95 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +000096 /// complex type to the specified destination type, where the destination type
97 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000098 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
99 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000100
Anders Carlssona40a9f32010-05-22 17:45:10 +0000101 /// EmitNullValue - Emit a value that corresponds to null for the given type.
102 Value *EmitNullValue(QualType Ty);
103
Chris Lattner7f02f722007-08-24 05:35:26 +0000104 //===--------------------------------------------------------------------===//
105 // Visitor Methods
106 //===--------------------------------------------------------------------===//
107
108 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000109 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000110 assert(0 && "Stmt can't have complex result type!");
111 return 0;
112 }
113 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000114
Chris Lattner7f02f722007-08-24 05:35:26 +0000115 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
116
117 // Leaves.
118 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000119 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000120 }
121 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000122 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000123 }
124 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000125 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000126 }
Nate Begemane7579b52007-11-15 05:40:03 +0000127 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000128 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000129 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000130 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000131 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000132 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000133 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000134 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000135 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000136 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000137 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000138 CGF.getContext().typesAreCompatible(
139 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000140 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000141 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +0000142 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000143 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000144 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
145 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000146 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000147
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 // l-values.
149 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000150 Expr::EvalResult Result;
151 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
152 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
Devang Patel25c2c8f2010-08-10 17:53:33 +0000153 llvm::ConstantInt *CI
154 = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
155 CGF.EmitDeclRefExprDbgValue(E, CI);
156 return CI;
Eli Friedman28665272009-11-26 03:22:21 +0000157 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000158 return EmitLoadOfLValue(E);
159 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000160 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
161 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000162 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000163 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
164 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000165 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000166 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000167 return EmitLoadOfLValue(E);
168 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000169 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000170 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000171 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000172 Value *VisitObjCImplicitSetterGetterRefExpr(
173 ObjCImplicitSetterGetterRefExpr *E) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000174 return EmitLoadOfLValue(E);
175 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000176 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
177 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000178 }
179
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000180 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000181 LValue LV = CGF.EmitObjCIsaExpr(E);
182 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000183 return V;
184 }
185
Chris Lattner7f02f722007-08-24 05:35:26 +0000186 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000187 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000188 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000189 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000190 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
191 return EmitLoadOfLValue(E);
192 }
Devang Patel35634f52007-10-24 17:18:43 +0000193
Nate Begeman0533b302009-10-18 20:10:40 +0000194 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000195
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000196 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000197 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000198 }
Eli Friedmand8889622009-11-27 04:41:50 +0000199 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000200 // Make sure to evaluate VLA bounds now so that we have them for later.
201 if (E->getType()->isVariablyModifiedType())
202 CGF.EmitVLASize(E->getType());
203
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000204 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000205 }
Eli Friedmand8889622009-11-27 04:41:50 +0000206 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000207
208 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000209 if (E->getCallReturnType()->isReferenceType())
210 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000211
Chris Lattner9b655512007-08-31 22:49:20 +0000212 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000213 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000214
Chris Lattner33793202007-08-31 22:09:40 +0000215 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000216
Mike Stumpa99038c2009-02-28 09:07:16 +0000217 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000218
Chris Lattner7f02f722007-08-24 05:35:26 +0000219 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000220 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000221 LValue LV = EmitLValue(E->getSubExpr());
222 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000223 }
224 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000225 LValue LV = EmitLValue(E->getSubExpr());
226 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000227 }
228 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000229 LValue LV = EmitLValue(E->getSubExpr());
230 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000231 }
232 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000233 LValue LV = EmitLValue(E->getSubExpr());
234 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000235 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000236
237 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
238 bool isInc, bool isPre);
239
240
Chris Lattner7f02f722007-08-24 05:35:26 +0000241 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCalld608cdb2010-08-22 10:59:02 +0000242 // If the sub-expression is an instance member reference,
243 // EmitDeclRefLValue will magically emit it with the appropriate
244 // value as the "address".
Chris Lattner7f02f722007-08-24 05:35:26 +0000245 return EmitLValue(E->getSubExpr()).getAddress();
246 }
247 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
248 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000249 // This differs from gcc, though, most likely due to a bug in gcc.
250 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000251 return Visit(E->getSubExpr());
252 }
253 Value *VisitUnaryMinus (const UnaryOperator *E);
254 Value *VisitUnaryNot (const UnaryOperator *E);
255 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000256 Value *VisitUnaryReal (const UnaryOperator *E);
257 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000258 Value *VisitUnaryExtension(const UnaryOperator *E) {
259 return Visit(E->getSubExpr());
260 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000261
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000262 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000263 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
264 return Visit(DAE->getExpr());
265 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000266 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
267 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000268 }
269
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000270 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000271 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000272 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000273 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
274 return CGF.EmitCXXNewExpr(E);
275 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000276 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
277 CGF.EmitCXXDeleteExpr(E);
278 return 0;
279 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000280 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
281 return llvm::ConstantInt::get(Builder.getInt1Ty(),
282 E->EvaluateTrait(CGF.getContext()));
283 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000284
Douglas Gregora71d8192009-09-04 17:36:40 +0000285 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
286 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000287 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000288 // operator (), and the result of such a call has type void. The only
289 // effect is the evaluation of the postfix-expression before the dot or
290 // arrow.
291 CGF.EmitScalarExpr(E->getBase());
292 return 0;
293 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000294
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000295 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000296 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000297 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000298
299 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
300 CGF.EmitCXXThrowExpr(E);
301 return 0;
302 }
303
Chris Lattner7f02f722007-08-24 05:35:26 +0000304 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000305 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000306 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000307 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
308 case LangOptions::SOB_Undefined:
309 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
310 case LangOptions::SOB_Defined:
311 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
312 case LangOptions::SOB_Trapping:
313 return EmitOverflowCheckedBinOp(Ops);
314 }
315 }
316
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000317 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000318 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000319 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
320 }
Mike Stump2add4732009-04-01 20:28:16 +0000321 /// Create a binary op that checks for overflow.
322 /// Currently only supports +, - and *.
323 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000324 Value *EmitDiv(const BinOpInfo &Ops);
325 Value *EmitRem(const BinOpInfo &Ops);
326 Value *EmitAdd(const BinOpInfo &Ops);
327 Value *EmitSub(const BinOpInfo &Ops);
328 Value *EmitShl(const BinOpInfo &Ops);
329 Value *EmitShr(const BinOpInfo &Ops);
330 Value *EmitAnd(const BinOpInfo &Ops) {
331 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
332 }
333 Value *EmitXor(const BinOpInfo &Ops) {
334 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
335 }
336 Value *EmitOr (const BinOpInfo &Ops) {
337 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
338 }
339
Chris Lattner1f1ded92007-08-24 21:00:35 +0000340 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000341 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
342 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000343 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000344
Chris Lattner3ccf7742007-08-26 21:41:21 +0000345 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000346 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
347
348 // Binary operators and binary compound assignment operators.
349#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000350 Value *VisitBin ## OP(const BinaryOperator *E) { \
351 return Emit ## OP(EmitBinOps(E)); \
352 } \
353 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
354 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000355 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000356 HANDLEBINOP(Mul)
357 HANDLEBINOP(Div)
358 HANDLEBINOP(Rem)
359 HANDLEBINOP(Add)
360 HANDLEBINOP(Sub)
361 HANDLEBINOP(Shl)
362 HANDLEBINOP(Shr)
363 HANDLEBINOP(And)
364 HANDLEBINOP(Xor)
365 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000366#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000367
Chris Lattner7f02f722007-08-24 05:35:26 +0000368 // Comparisons.
369 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
370 unsigned SICmpOpc, unsigned FCmpOpc);
371#define VISITCOMP(CODE, UI, SI, FP) \
372 Value *VisitBin##CODE(const BinaryOperator *E) { \
373 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
374 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000375 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
376 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
377 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
378 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
379 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
380 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000381#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000382
Chris Lattner7f02f722007-08-24 05:35:26 +0000383 Value *VisitBinAssign (const BinaryOperator *E);
384
385 Value *VisitBinLAnd (const BinaryOperator *E);
386 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000387 Value *VisitBinComma (const BinaryOperator *E);
388
Eli Friedman25b825d2009-11-18 09:41:26 +0000389 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
390 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
391
Chris Lattner7f02f722007-08-24 05:35:26 +0000392 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000393 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000394 Value *VisitConditionalOperator(const ConditionalOperator *CO);
395 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000396 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000397 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
398 return CGF.EmitObjCStringLiteral(E);
399 }
400};
401} // end anonymous namespace.
402
403//===----------------------------------------------------------------------===//
404// Utilities
405//===----------------------------------------------------------------------===//
406
Chris Lattner9abc84e2007-08-26 16:42:57 +0000407/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000408/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000409Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000410 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000411
Chris Lattner9abc84e2007-08-26 16:42:57 +0000412 if (SrcType->isRealFloatingType()) {
413 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000414 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000415 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
416 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000417
John McCall0bab0cd2010-08-23 01:21:21 +0000418 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
419 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000420
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000421 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000422 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000423
Chris Lattner9abc84e2007-08-26 16:42:57 +0000424 // Because of the type rules of C, we often end up computing a logical value,
425 // then zero extending it to int, then wanting it as a logical value again.
426 // Optimize this common case.
427 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000428 if (ZI->getOperand(0)->getType() ==
429 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000430 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000431 // If there aren't any more uses, zap the instruction to save space.
432 // Note that there can be more uses, for example if this
433 // is the result of an assignment.
434 if (ZI->use_empty())
435 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000436 return Result;
437 }
438 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000439
Chris Lattner9abc84e2007-08-26 16:42:57 +0000440 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000441 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000442 return Builder.CreateICmpNE(Src, Zero, "tobool");
443}
444
Chris Lattner3707b252007-08-26 06:48:56 +0000445/// EmitScalarConversion - Emit a conversion from the specified type to the
446/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000447Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
448 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000449 SrcType = CGF.getContext().getCanonicalType(SrcType);
450 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000451 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000452
Chris Lattnercf289082007-08-26 07:21:11 +0000453 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000454
Chris Lattner3707b252007-08-26 06:48:56 +0000455 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000456 if (DstType->isBooleanType())
457 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000458
Chris Lattner3707b252007-08-26 06:48:56 +0000459 const llvm::Type *DstTy = ConvertType(DstType);
460
461 // Ignore conversions like int -> uint.
462 if (Src->getType() == DstTy)
463 return Src;
464
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000465 // Handle pointer conversions next: pointers can only be converted to/from
466 // other pointers and integers. Check for pointer types in terms of LLVM, as
467 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000468 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000469 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000470 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000471 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000472
Chris Lattner3707b252007-08-26 06:48:56 +0000473 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000474 // First, convert to the correct width so that we control the kind of
475 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000476 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000477 bool InputSigned = SrcType->isSignedIntegerType();
478 llvm::Value* IntResult =
479 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
480 // Then, cast to pointer.
481 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000482 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000483
Daniel Dunbar270cc662008-08-25 09:51:32 +0000484 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000485 // Must be an ptr to int cast.
486 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000487 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000488 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000489
Nate Begeman213541a2008-04-18 23:10:10 +0000490 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000491 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000492 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000493 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000494 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
495
496 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000497 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000498 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000499 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
500
501 // Splat the element across to all elements
502 llvm::SmallVector<llvm::Constant*, 16> Args;
503 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
504 for (unsigned i = 0; i < NumElements; i++)
Chris Lattner77b89b82010-06-27 07:15:29 +0000505 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +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");
Mike Stumpdb52dcd2009-09-09 13:00:44 +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 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000528 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000529 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
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000536 assert(DstTy->isFloatingPointTy() && "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
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000543/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
544/// type to the specified destination type, where the destination type is an
545/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000546Value *ScalarExprEmitter::
547EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
548 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000549 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000550 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000551
Chris Lattnered70f0a2007-08-26 16:52:28 +0000552 // 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 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000559
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
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000563 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000564 return EmitScalarConversion(Src.first, SrcTy, DstTy);
565}
566
Anders Carlssona40a9f32010-05-22 17:45:10 +0000567Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000568 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
569 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
570
571 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000572}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000573
Chris Lattner7f02f722007-08-24 05:35:26 +0000574//===----------------------------------------------------------------------===//
575// Visitor Methods
576//===----------------------------------------------------------------------===//
577
578Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000579 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000580 if (E->getType()->isVoidType())
581 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000582 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000583}
584
Eli Friedmand38617c2008-05-14 19:38:39 +0000585Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000586 // Vector Mask Case
587 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000588 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000589 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
590 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
591 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000592
Nate Begeman37b6a572010-06-08 00:16:34 +0000593 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
594 unsigned LHSElts = LTy->getNumElements();
595
596 if (E->getNumSubExprs() == 3) {
597 Mask = CGF.EmitScalarExpr(E->getExpr(2));
598
599 // Shuffle LHS & RHS into one input vector.
600 llvm::SmallVector<llvm::Constant*, 32> concat;
601 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000602 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
603 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000604 }
605
606 Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size());
607 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
608 LHSElts *= 2;
609 } else {
610 Mask = RHS;
611 }
612
613 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
614 llvm::Constant* EltMask;
615
616 // Treat vec3 like vec4.
617 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
618 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
619 (1 << llvm::Log2_32(LHSElts+2))-1);
620 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
621 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
622 (1 << llvm::Log2_32(LHSElts+1))-1);
623 else
624 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
625 (1 << llvm::Log2_32(LHSElts))-1);
626
627 // Mask off the high bits of each shuffle index.
628 llvm::SmallVector<llvm::Constant *, 32> MaskV;
629 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
630 MaskV.push_back(EltMask);
631
632 Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size());
633 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
634
635 // newv = undef
636 // mask = mask & maskbits
637 // for each elt
638 // n = extract mask i
639 // x = extract val n
640 // newv = insert newv, x, i
641 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
642 MTy->getNumElements());
643 Value* NewV = llvm::UndefValue::get(RTy);
644 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000645 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000646 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000647 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000648
649 // Handle vec3 special since the index will be off by one for the RHS.
650 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
651 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000652 cmpIndx = Builder.CreateICmpUGT(Indx,
653 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000654 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000655 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000656 "shuf_idx_adj");
657 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
658 }
659 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
660 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
661 }
662 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000663 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000664
Eli Friedmand38617c2008-05-14 19:38:39 +0000665 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
666 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000667
668 // Handle vec3 special since the index will be off by one for the RHS.
669 llvm::SmallVector<llvm::Constant*, 32> indices;
670 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
671 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
672 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
673 if (VTy->getNumElements() == 3) {
674 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
675 uint64_t cVal = CI->getZExtValue();
676 if (cVal > 3) {
677 C = llvm::ConstantInt::get(C->getType(), cVal-1);
678 }
679 }
680 }
681 indices.push_back(C);
682 }
683
Owen Anderson4a289322009-07-28 21:22:35 +0000684 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000685 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
686}
Eli Friedman28665272009-11-26 03:22:21 +0000687Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
688 Expr::EvalResult Result;
689 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
690 if (E->isArrow())
691 CGF.EmitScalarExpr(E->getBase());
692 else
693 EmitLValue(E->getBase());
694 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
695 }
696 return EmitLoadOfLValue(E);
697}
Eli Friedmand38617c2008-05-14 19:38:39 +0000698
Chris Lattner7f02f722007-08-24 05:35:26 +0000699Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000700 TestAndClearIgnoreResultAssign();
701
Chris Lattner7f02f722007-08-24 05:35:26 +0000702 // Emit subscript expressions in rvalue context's. For most cases, this just
703 // loads the lvalue formed by the subscript expr. However, we have to be
704 // careful, because the base of a vector subscript is occasionally an rvalue,
705 // so we can't get it as an lvalue.
706 if (!E->getBase()->getType()->isVectorType())
707 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000708
Chris Lattner7f02f722007-08-24 05:35:26 +0000709 // Handle the vector case. The base must be a vector, the index must be an
710 // integer value.
711 Value *Base = Visit(E->getBase());
712 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000713 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000714 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000715 return Builder.CreateExtractElement(Base, Idx, "vecext");
716}
717
Nate Begeman0533b302009-10-18 20:10:40 +0000718static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
719 unsigned Off, const llvm::Type *I32Ty) {
720 int MV = SVI->getMaskValue(Idx);
721 if (MV == -1)
722 return llvm::UndefValue::get(I32Ty);
723 return llvm::ConstantInt::get(I32Ty, Off+MV);
724}
725
726Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
727 bool Ignore = TestAndClearIgnoreResultAssign();
728 (void)Ignore;
729 assert (Ignore == false && "init list ignored");
730 unsigned NumInitElements = E->getNumInits();
731
732 if (E->hadArrayRangeDesignator())
733 CGF.ErrorUnsupported(E, "GNU array range designator extension");
734
735 const llvm::VectorType *VType =
736 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
737
738 // We have a scalar in braces. Just use the first element.
739 if (!VType)
740 return Visit(E->getInit(0));
741
742 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000743
744 // Loop over initializers collecting the Value for each, and remembering
745 // whether the source was swizzle (ExtVectorElementExpr). This will allow
746 // us to fold the shuffle for the swizzle into the shuffle for the vector
747 // initializer, since LLVM optimizers generally do not want to touch
748 // shuffles.
749 unsigned CurIdx = 0;
750 bool VIsUndefShuffle = false;
751 llvm::Value *V = llvm::UndefValue::get(VType);
752 for (unsigned i = 0; i != NumInitElements; ++i) {
753 Expr *IE = E->getInit(i);
754 Value *Init = Visit(IE);
755 llvm::SmallVector<llvm::Constant*, 16> Args;
756
757 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
758
759 // Handle scalar elements. If the scalar initializer is actually one
760 // element of a different vector of the same width, use shuffle instead of
761 // extract+insert.
762 if (!VVT) {
763 if (isa<ExtVectorElementExpr>(IE)) {
764 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
765
766 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
767 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
768 Value *LHS = 0, *RHS = 0;
769 if (CurIdx == 0) {
770 // insert into undef -> shuffle (src, undef)
771 Args.push_back(C);
772 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000773 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000774
775 LHS = EI->getVectorOperand();
776 RHS = V;
777 VIsUndefShuffle = true;
778 } else if (VIsUndefShuffle) {
779 // insert into undefshuffle && size match -> shuffle (v, src)
780 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
781 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000782 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
783 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000784 ResElts + C->getZExtValue()));
785 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000786 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000787
788 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
789 RHS = EI->getVectorOperand();
790 VIsUndefShuffle = false;
791 }
792 if (!Args.empty()) {
793 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
794 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
795 ++CurIdx;
796 continue;
797 }
798 }
799 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000800 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000801 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
802 VIsUndefShuffle = false;
803 ++CurIdx;
804 continue;
805 }
806
807 unsigned InitElts = VVT->getNumElements();
808
809 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
810 // input is the same width as the vector being constructed, generate an
811 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000812 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000813 if (isa<ExtVectorElementExpr>(IE)) {
814 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
815 Value *SVOp = SVI->getOperand(0);
816 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
817
818 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000819 for (unsigned j = 0; j != CurIdx; ++j) {
820 // If the current vector initializer is a shuffle with undef, merge
821 // this shuffle directly into it.
822 if (VIsUndefShuffle) {
823 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000824 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000825 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000826 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000827 }
828 }
829 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000830 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000831 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000832 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000833
834 if (VIsUndefShuffle)
835 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
836
837 Init = SVOp;
838 }
839 }
840
841 // Extend init to result vector length, and then shuffle its contribution
842 // to the vector initializer into V.
843 if (Args.empty()) {
844 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000845 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000846 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000847 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000848 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
849 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000850 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000851
852 Args.clear();
853 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000854 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000855 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000856 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000857 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000858 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000859 }
860
861 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
862 // merging subsequent shuffles into this one.
863 if (CurIdx == 0)
864 std::swap(V, Init);
865 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
866 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
867 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
868 CurIdx += InitElts;
869 }
870
871 // FIXME: evaluate codegen vs. shuffling against constant null vector.
872 // Emit remaining default initializers.
873 const llvm::Type *EltTy = VType->getElementType();
874
875 // Emit remaining default initializers
876 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000877 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000878 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
879 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
880 }
881 return V;
882}
883
Anders Carlssona3697c92009-11-23 17:57:54 +0000884static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
885 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000886
John McCall2de56d12010-08-25 11:45:40 +0000887 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000888 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000889
890 if (isa<CXXThisExpr>(E)) {
891 // We always assume that 'this' is never null.
892 return false;
893 }
894
895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000896 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000897 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000898 return false;
899 }
900
901 return true;
902}
903
Chris Lattner7f02f722007-08-24 05:35:26 +0000904// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
905// have to handle a more broad range of conversions than explicit casts, as they
906// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +0000907Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
908 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000909 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +0000910 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000911
Mike Stump7f79f9b2009-05-29 15:46:01 +0000912 if (!DestTy->isVoidType())
913 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000914
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000915 // Since almost all cast kinds apply to scalars, this switch doesn't have
916 // a default case, so the compiler will warn on a missing case. The cases
917 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +0000918 switch (Kind) {
John McCall2de56d12010-08-25 11:45:40 +0000919 case CK_Unknown:
Eli Friedmand8889622009-11-27 04:41:50 +0000920 // FIXME: All casts should have a known kind!
Eli Friedmanad35a832009-11-16 21:33:53 +0000921 //assert(0 && "Unknown cast kind!");
Anders Carlssone9776242009-08-24 18:26:39 +0000922 break;
Eli Friedmanad35a832009-11-16 21:33:53 +0000923
John McCall2de56d12010-08-25 11:45:40 +0000924 case CK_LValueBitCast:
925 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +0000926 Value *V = EmitLValue(E).getAddress();
927 V = Builder.CreateBitCast(V,
928 ConvertType(CGF.getContext().getPointerType(DestTy)));
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000929 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
Douglas Gregore39a3892010-07-13 23:17:26 +0000930 }
931
John McCall2de56d12010-08-25 11:45:40 +0000932 case CK_AnyPointerToObjCPointerCast:
933 case CK_AnyPointerToBlockPointerCast:
934 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000935 Value *Src = Visit(const_cast<Expr*>(E));
936 return Builder.CreateBitCast(Src, ConvertType(DestTy));
937 }
John McCall2de56d12010-08-25 11:45:40 +0000938 case CK_NoOp:
939 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000940 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000941
John McCall2de56d12010-08-25 11:45:40 +0000942 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +0000943 const CXXRecordDecl *DerivedClassDecl =
944 DestTy->getCXXRecordDeclForPointerType();
945
Anders Carlssona04efdf2010-04-24 21:23:59 +0000946 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +0000947 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +0000948 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +0000949 }
John McCall2de56d12010-08-25 11:45:40 +0000950 case CK_UncheckedDerivedToBase:
951 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +0000952 const RecordType *DerivedClassTy =
953 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
954 CXXRecordDecl *DerivedClassDecl =
955 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
956
Anders Carlsson34a2d382010-04-24 21:06:20 +0000957 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +0000958 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +0000959 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +0000960 }
John McCall2de56d12010-08-25 11:45:40 +0000961 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000962 Value *V = Visit(const_cast<Expr*>(E));
963 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
964 return CGF.EmitDynamicCast(V, DCE);
965 }
John McCall2de56d12010-08-25 11:45:40 +0000966 case CK_ToUnion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000967 assert(0 && "Should be unreachable!");
968 break;
Eli Friedmand8889622009-11-27 04:41:50 +0000969
John McCall2de56d12010-08-25 11:45:40 +0000970 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +0000971 assert(E->getType()->isArrayType() &&
972 "Array to pointer decay must have array source type!");
973
974 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
975
976 // Note that VLA pointers are always decayed, so we don't need to do
977 // anything here.
978 if (!E->getType()->isVariableArrayType()) {
979 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
980 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
981 ->getElementType()) &&
982 "Expected pointer to array");
983 V = Builder.CreateStructGEP(V, 0, "arraydecay");
984 }
985
986 return V;
987 }
John McCall2de56d12010-08-25 11:45:40 +0000988 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +0000989 return EmitLValue(E).getAddress();
990
John McCall2de56d12010-08-25 11:45:40 +0000991 case CK_NullToMemberPointer: {
John McCalld608cdb2010-08-22 10:59:02 +0000992 // If the subexpression's type is the C++0x nullptr_t, emit the
993 // subexpression, which may have side effects.
994 if (E->getType()->isNullPtrType())
995 (void) Visit(E);
996
John McCall0bab0cd2010-08-23 01:21:21 +0000997 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
998 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
999 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001000
John McCall2de56d12010-08-25 11:45:40 +00001001 case CK_BaseToDerivedMemberPointer:
1002 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001003 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001004
1005 // Note that the AST doesn't distinguish between checked and
1006 // unchecked member pointer conversions, so we always have to
1007 // implement checked conversions here. This is inefficient when
1008 // actual control flow may be required in order to perform the
1009 // check, which it is for data member pointers (but not member
1010 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001011 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001012 }
John McCall0bab0cd2010-08-23 01:21:21 +00001013
Eli Friedmand8889622009-11-27 04:41:50 +00001014
John McCall2de56d12010-08-25 11:45:40 +00001015 case CK_ConstructorConversion:
Eli Friedmand8889622009-11-27 04:41:50 +00001016 assert(0 && "Should be unreachable!");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001017 break;
1018
John McCall2de56d12010-08-25 11:45:40 +00001019 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001020 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001021
Anders Carlsson82debc72009-10-18 18:12:03 +00001022 // First, convert to the correct width so that we control the kind of
1023 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001024 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001025 bool InputSigned = E->getType()->isSignedIntegerType();
1026 llvm::Value* IntResult =
1027 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001028
Anders Carlsson82debc72009-10-18 18:12:03 +00001029 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001030 }
John McCall2de56d12010-08-25 11:45:40 +00001031 case CK_PointerToIntegral: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001032 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001033
1034 // Handle conversion to bool correctly.
1035 if (DestTy->isBooleanType())
Daniel Dunbardb505472010-09-03 02:07:00 +00001036 return EmitScalarConversion(Src, E->getType(), DestTy);
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001037
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001038 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1039 }
John McCall2de56d12010-08-25 11:45:40 +00001040 case CK_ToVoid: {
Douglas Gregor569c3162010-08-07 11:51:51 +00001041 if (E->Classify(CGF.getContext()).isGLValue())
1042 CGF.EmitLValue(E);
1043 else
1044 CGF.EmitAnyExpr(E, 0, false, true);
Eli Friedmanad35a832009-11-16 21:33:53 +00001045 return 0;
1046 }
John McCall2de56d12010-08-25 11:45:40 +00001047 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001048 const llvm::Type *DstTy = ConvertType(DestTy);
1049 Value *Elt = Visit(const_cast<Expr*>(E));
1050
1051 // Insert the element in element zero of an undef vector
1052 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001053 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001054 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1055
1056 // Splat the element across to all elements
1057 llvm::SmallVector<llvm::Constant*, 16> Args;
1058 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1059 for (unsigned i = 0; i < NumElements; i++)
Chris Lattner77b89b82010-06-27 07:15:29 +00001060 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Eli Friedmanad35a832009-11-16 21:33:53 +00001061
1062 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1063 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1064 return Yay;
1065 }
John McCall2de56d12010-08-25 11:45:40 +00001066 case CK_IntegralCast:
1067 case CK_IntegralToFloating:
1068 case CK_FloatingToIntegral:
1069 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001070 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001071
John McCall2de56d12010-08-25 11:45:40 +00001072 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001073 llvm::Value *MemPtr = Visit(E);
1074 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1075 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001076 }
John McCall0bab0cd2010-08-23 01:21:21 +00001077 }
1078
Chris Lattner58a2e942007-08-26 07:26:12 +00001079 // Handle cases where the source is an non-complex type.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001080
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001081 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +00001082 Value *Src = Visit(const_cast<Expr*>(E));
1083
Chris Lattner3707b252007-08-26 06:48:56 +00001084 // Use EmitScalarConversion to perform the conversion.
1085 return EmitScalarConversion(Src, E->getType(), DestTy);
1086 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001087
Chris Lattner9b2dc282008-04-04 16:54:41 +00001088 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001089 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001090 bool IgnoreImag = true;
1091 bool IgnoreImagAssign = true;
1092 bool IgnoreReal = IgnoreResultAssign;
1093 bool IgnoreRealAssign = IgnoreResultAssign;
1094 if (DestTy->isBooleanType())
1095 IgnoreImagAssign = IgnoreImag = false;
1096 else if (DestTy->isVoidType()) {
1097 IgnoreReal = IgnoreImag = false;
1098 IgnoreRealAssign = IgnoreImagAssign = true;
1099 }
1100 CodeGenFunction::ComplexPairTy V
1101 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
1102 IgnoreImagAssign);
1103 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001104 }
Chris Lattner10b00cf2007-08-26 07:16:41 +00001105
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001106 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
1107 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001108 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001109 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001110}
1111
Chris Lattner33793202007-08-31 22:09:40 +00001112Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +00001113 return CGF.EmitCompoundStmt(*E->getSubStmt(),
1114 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001115}
1116
Mike Stumpa99038c2009-02-28 09:07:16 +00001117Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001118 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1119 if (E->getType().isObjCGCWeak())
1120 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +00001121 return Builder.CreateLoad(V, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +00001122}
Chris Lattner33793202007-08-31 22:09:40 +00001123
Chris Lattner7f02f722007-08-24 05:35:26 +00001124//===----------------------------------------------------------------------===//
1125// Unary Operators
1126//===----------------------------------------------------------------------===//
1127
Chris Lattner8c11a652010-06-26 22:09:34 +00001128llvm::Value *ScalarExprEmitter::
1129EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1130 bool isInc, bool isPre) {
1131
1132 QualType ValTy = E->getSubExpr()->getType();
1133 llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy);
1134
1135 int AmountVal = isInc ? 1 : -1;
1136
1137 if (ValTy->isPointerType() &&
1138 ValTy->getAs<PointerType>()->isVariableArrayType()) {
1139 // The amount of the addition/subtraction needs to account for the VLA size
1140 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1141 }
1142
1143 llvm::Value *NextVal;
1144 if (const llvm::PointerType *PT =
1145 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +00001146 llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal);
Chris Lattner8c11a652010-06-26 22:09:34 +00001147 if (!isa<llvm::FunctionType>(PT->getElementType())) {
1148 QualType PTEE = ValTy->getPointeeType();
1149 if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) {
1150 // Handle interface types, which are not represented with a concrete
1151 // type.
1152 int size = CGF.getContext().getTypeSize(OIT) / 8;
1153 if (!isInc)
1154 size = -size;
1155 Inc = llvm::ConstantInt::get(Inc->getType(), size);
1156 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1157 InVal = Builder.CreateBitCast(InVal, i8Ty);
1158 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1159 llvm::Value *lhs = LV.getAddress();
1160 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001161 LV = CGF.MakeAddrLValue(lhs, ValTy);
Chris Lattner8c11a652010-06-26 22:09:34 +00001162 } else
1163 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1164 } else {
1165 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1166 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1167 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1168 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1169 }
1170 } else if (InVal->getType()->isIntegerTy(1) && isInc) {
1171 // Bool++ is an interesting case, due to promotion rules, we get:
1172 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1173 // Bool = ((int)Bool+1) != 0
1174 // An interesting aspect of this is that increment is always true.
1175 // Decrement does not have this property.
1176 NextVal = llvm::ConstantInt::getTrue(VMContext);
1177 } else if (isa<llvm::IntegerType>(InVal->getType())) {
1178 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1179
Chris Lattner640d3262010-06-26 22:18:28 +00001180 if (!ValTy->isSignedIntegerType())
1181 // Unsigned integer inc is always two's complement.
Chris Lattner8c11a652010-06-26 22:09:34 +00001182 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner640d3262010-06-26 22:18:28 +00001183 else {
1184 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1185 case LangOptions::SOB_Undefined:
1186 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1187 break;
1188 case LangOptions::SOB_Defined:
1189 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1190 break;
1191 case LangOptions::SOB_Trapping:
1192 BinOpInfo BinOp;
1193 BinOp.LHS = InVal;
1194 BinOp.RHS = NextVal;
1195 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001196 BinOp.Opcode = BO_Add;
Chris Lattner640d3262010-06-26 22:18:28 +00001197 BinOp.E = E;
John McCall401be6b2010-08-05 17:39:44 +00001198 NextVal = EmitOverflowCheckedBinOp(BinOp);
1199 break;
Chris Lattner640d3262010-06-26 22:18:28 +00001200 }
1201 }
Chris Lattner8c11a652010-06-26 22:09:34 +00001202 } else {
1203 // Add the inc/dec to the real part.
1204 if (InVal->getType()->isFloatTy())
1205 NextVal =
1206 llvm::ConstantFP::get(VMContext,
1207 llvm::APFloat(static_cast<float>(AmountVal)));
1208 else if (InVal->getType()->isDoubleTy())
1209 NextVal =
1210 llvm::ConstantFP::get(VMContext,
1211 llvm::APFloat(static_cast<double>(AmountVal)));
1212 else {
1213 llvm::APFloat F(static_cast<float>(AmountVal));
1214 bool ignored;
1215 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1216 &ignored);
1217 NextVal = llvm::ConstantFP::get(VMContext, F);
1218 }
1219 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1220 }
1221
1222 // Store the updated result through the lvalue.
1223 if (LV.isBitField())
1224 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal);
1225 else
1226 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1227
1228 // If this is a postinc, return the value read from memory, otherwise use the
1229 // updated value.
1230 return isPre ? NextVal : InVal;
1231}
1232
1233
1234
Chris Lattner7f02f722007-08-24 05:35:26 +00001235Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001236 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001237 // Emit unary minus with EmitSub so we handle overflow cases etc.
1238 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001239 BinOp.RHS = Visit(E->getSubExpr());
1240
1241 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1242 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1243 else
1244 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001245 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001246 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001247 BinOp.E = E;
1248 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001249}
1250
1251Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001252 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001253 Value *Op = Visit(E->getSubExpr());
1254 return Builder.CreateNot(Op, "neg");
1255}
1256
1257Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1258 // Compare operand to zero.
1259 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001260
Chris Lattner7f02f722007-08-24 05:35:26 +00001261 // Invert value.
1262 // TODO: Could dynamically modify easy computations here. For example, if
1263 // the operand is an icmp ne, turn into icmp eq.
1264 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001265
Anders Carlsson9f84d882009-05-19 18:44:53 +00001266 // ZExt result to the expr type.
1267 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001268}
1269
Eli Friedman0027d2b2010-08-05 09:58:49 +00001270Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1271 // Try folding the offsetof to a constant.
1272 Expr::EvalResult EvalResult;
1273 if (E->Evaluate(EvalResult, CGF.getContext()))
1274 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1275
1276 // Loop over the components of the offsetof to compute the value.
1277 unsigned n = E->getNumComponents();
1278 const llvm::Type* ResultType = ConvertType(E->getType());
1279 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1280 QualType CurrentType = E->getTypeSourceInfo()->getType();
1281 for (unsigned i = 0; i != n; ++i) {
1282 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001283 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001284 switch (ON.getKind()) {
1285 case OffsetOfExpr::OffsetOfNode::Array: {
1286 // Compute the index
1287 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1288 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1289 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1290 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1291
1292 // Save the element type
1293 CurrentType =
1294 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1295
1296 // Compute the element size
1297 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1298 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1299
1300 // Multiply out to compute the result
1301 Offset = Builder.CreateMul(Idx, ElemSize);
1302 break;
1303 }
1304
1305 case OffsetOfExpr::OffsetOfNode::Field: {
1306 FieldDecl *MemberDecl = ON.getField();
1307 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1308 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1309
1310 // Compute the index of the field in its parent.
1311 unsigned i = 0;
1312 // FIXME: It would be nice if we didn't have to loop here!
1313 for (RecordDecl::field_iterator Field = RD->field_begin(),
1314 FieldEnd = RD->field_end();
1315 Field != FieldEnd; (void)++Field, ++i) {
1316 if (*Field == MemberDecl)
1317 break;
1318 }
1319 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1320
1321 // Compute the offset to the field
1322 int64_t OffsetInt = RL.getFieldOffset(i) /
1323 CGF.getContext().getCharWidth();
1324 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1325
1326 // Save the element type.
1327 CurrentType = MemberDecl->getType();
1328 break;
1329 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001330
Eli Friedman0027d2b2010-08-05 09:58:49 +00001331 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001332 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001333
Eli Friedman0027d2b2010-08-05 09:58:49 +00001334 case OffsetOfExpr::OffsetOfNode::Base: {
1335 if (ON.getBase()->isVirtual()) {
1336 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1337 continue;
1338 }
1339
1340 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1341 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1342
1343 // Save the element type.
1344 CurrentType = ON.getBase()->getType();
1345
1346 // Compute the offset to the base.
1347 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1348 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1349 int64_t OffsetInt = RL.getBaseClassOffset(BaseRD) /
1350 CGF.getContext().getCharWidth();
1351 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1352 break;
1353 }
1354 }
1355 Result = Builder.CreateAdd(Result, Offset);
1356 }
1357 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001358}
1359
Sebastian Redl05189992008-11-11 17:56:53 +00001360/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1361/// argument of the sizeof expression as an integer.
1362Value *
1363ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001364 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001365 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001366 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001367 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1368 if (E->isArgumentType()) {
1369 // sizeof(type) - make sure to emit the VLA size.
1370 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001371 } else {
1372 // C99 6.5.3.4p2: If the argument is an expression of type
1373 // VLA, it is evaluated.
1374 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001375 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001376
Anders Carlsson96f21472009-02-05 19:43:10 +00001377 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001378 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001379 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001380
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001381 // If this isn't sizeof(vla), the result must be constant; use the constant
1382 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001383 Expr::EvalResult Result;
1384 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001385 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001386}
1387
Chris Lattner46f93d02007-08-24 21:20:17 +00001388Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1389 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001390 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001391 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +00001392 return Visit(Op);
1393}
1394Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1395 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001396 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001397 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001398
Mike Stump7f79f9b2009-05-29 15:46:01 +00001399 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1400 // effects are evaluated, but not the actual value.
1401 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1402 CGF.EmitLValue(Op);
1403 else
1404 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001405 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001406}
1407
Chris Lattner7f02f722007-08-24 05:35:26 +00001408//===----------------------------------------------------------------------===//
1409// Binary Operators
1410//===----------------------------------------------------------------------===//
1411
1412BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001413 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001414 BinOpInfo Result;
1415 Result.LHS = Visit(E->getLHS());
1416 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001417 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001418 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001419 Result.E = E;
1420 return Result;
1421}
1422
Douglas Gregor6a03e342010-04-23 04:16:32 +00001423LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1424 const CompoundAssignOperator *E,
1425 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001426 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001427 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001428 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001429
Eli Friedmanab3a8522009-03-28 01:22:36 +00001430 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001431 // This needs to go through the complex expression emitter, but it's a tad
1432 // complicated to do that... I'm leaving it out for now. (Note that we do
1433 // actually need the imaginary part of the RHS for multiplication and
1434 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001435 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001436 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001437 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001438 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001439
Mike Stumpcc0442f2009-05-22 19:07:20 +00001440 // Emit the RHS first. __block variables need to have the rhs evaluated
1441 // first, plus this should improve codegen a little.
1442 OpInfo.RHS = Visit(E->getRHS());
1443 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001444 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001445 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001446 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001447 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001448 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001449 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1450 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001451
Chris Lattner1f1ded92007-08-24 21:00:35 +00001452 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001453 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001454
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001455 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001456 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001457
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001458 // Store the result value into the LHS lvalue. Bit-fields are handled
1459 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1460 // 'An assignment expression has the value of the left operand after the
1461 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001462 if (LHSLV.isBitField())
1463 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1464 &Result);
1465 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001466 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001467
Douglas Gregor6a03e342010-04-23 04:16:32 +00001468 return LHSLV;
1469}
1470
1471Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1472 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1473 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001474 Value *RHS;
1475 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1476
1477 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001478 if (Ignore)
1479 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001480
1481 // Objective-C property assignment never reloads the value following a store.
1482 if (LHS.isPropertyRef() || LHS.isKVCRef())
1483 return RHS;
1484
1485 // If the lvalue is non-volatile, return the computed value of the assignment.
1486 if (!LHS.isVolatileQualified())
1487 return RHS;
1488
1489 // Otherwise, reload the value.
1490 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001491}
1492
1493
Chris Lattner7f02f722007-08-24 05:35:26 +00001494Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001495 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001496 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001497 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001498 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1499 else
1500 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1501}
1502
1503Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1504 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +00001505 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001506 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1507 else
1508 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1509}
1510
Mike Stump2add4732009-04-01 20:28:16 +00001511Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1512 unsigned IID;
1513 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001514
Chris Lattner9a207232010-06-26 21:48:21 +00001515 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001516 case BO_Add:
1517 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001518 OpID = 1;
1519 IID = llvm::Intrinsic::sadd_with_overflow;
1520 break;
John McCall2de56d12010-08-25 11:45:40 +00001521 case BO_Sub:
1522 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001523 OpID = 2;
1524 IID = llvm::Intrinsic::ssub_with_overflow;
1525 break;
John McCall2de56d12010-08-25 11:45:40 +00001526 case BO_Mul:
1527 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001528 OpID = 3;
1529 IID = llvm::Intrinsic::smul_with_overflow;
1530 break;
1531 default:
1532 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001533 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001534 }
Mike Stump035cf892009-04-02 18:15:54 +00001535 OpID <<= 1;
1536 OpID |= 1;
1537
Mike Stump2add4732009-04-01 20:28:16 +00001538 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1539
1540 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1541
1542 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1543 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1544 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1545
1546 // Branch in case of overflow.
Chris Lattner93a00352010-08-07 00:20:46 +00001547 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1548 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001549
1550 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1551
Chris Lattner93a00352010-08-07 00:20:46 +00001552 // Handle overflow with llvm.trap.
1553 // TODO: it would be better to generate one of these blocks per function.
Mike Stump2add4732009-04-01 20:28:16 +00001554 Builder.SetInsertPoint(overflowBB);
Chris Lattner93a00352010-08-07 00:20:46 +00001555 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
1556 Builder.CreateCall(Trap);
1557 Builder.CreateUnreachable();
1558
1559 // Continue on.
Mike Stump2add4732009-04-01 20:28:16 +00001560 Builder.SetInsertPoint(continueBB);
Chris Lattner93a00352010-08-07 00:20:46 +00001561 return result;
Mike Stump2add4732009-04-01 20:28:16 +00001562}
Chris Lattner7f02f722007-08-24 05:35:26 +00001563
1564Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001565 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001566 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001567 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1568 case LangOptions::SOB_Undefined:
1569 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1570 case LangOptions::SOB_Defined:
1571 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1572 case LangOptions::SOB_Trapping:
1573 return EmitOverflowCheckedBinOp(Ops);
1574 }
1575 }
1576
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001577 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001578 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001579
Chris Lattner7f02f722007-08-24 05:35:26 +00001580 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001581 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001582
Chris Lattner7f215c12010-06-26 21:52:32 +00001583 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001584 // use this path.
1585 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1586
Steve Naroff14108da2009-07-10 23:34:53 +00001587 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001588 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001589 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001590 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001591 }
Chris Lattner9a207232010-06-26 21:48:21 +00001592
Chris Lattner8f925282008-01-03 06:36:51 +00001593 Value *Ptr, *Idx;
1594 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001595 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001596 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001597 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001598 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001599 Ptr = Ops.LHS;
1600 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001601 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001602 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001603 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1604 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001605 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001606 Ptr = Ops.RHS;
1607 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001608 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001609 }
1610
1611 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001612 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001613 // Zero or sign extend the pointer value based on whether the index is
1614 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001615 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001616 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001617 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1618 else
1619 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1620 }
Steve Naroff14108da2009-07-10 23:34:53 +00001621 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001622 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001623 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001624 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001625 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001626 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001627 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001628 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001629 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1630 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1631 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001632 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001633
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001634 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1635 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1636 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001637 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001638 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001639 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001640 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001641 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001642 }
1643
Dan Gohman664f8932009-08-12 00:33:55 +00001644 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001645}
1646
1647Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001648 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001649 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001650 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1651 case LangOptions::SOB_Undefined:
1652 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1653 case LangOptions::SOB_Defined:
1654 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1655 case LangOptions::SOB_Trapping:
1656 return EmitOverflowCheckedBinOp(Ops);
1657 }
1658 }
1659
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001660 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001661 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001662
Chris Lattner7f02f722007-08-24 05:35:26 +00001663 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001664 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001665
Chris Lattner9a207232010-06-26 21:48:21 +00001666 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1667 // use this path.
1668 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1669
1670 if (BinOp->getLHS()->getType()->isPointerType() &&
1671 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001672 // The amount of the addition needs to account for the VLA size for
1673 // ptr-int
1674 // The amount of the division needs to account for the VLA size for
1675 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001676 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001677 }
1678
Chris Lattner9a207232010-06-26 21:48:21 +00001679 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001680 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001681 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1682 // pointer - int
1683 Value *Idx = Ops.RHS;
1684 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001685 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001686 // Zero or sign extend the pointer value based on whether the index is
1687 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001688 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001689 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001690 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1691 else
1692 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1693 }
1694 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001695
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001696 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001697 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001698 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001699 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001700 CGF.getContext().
1701 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001702 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001703 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001704 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1705 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1706 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001707 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001708
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001709 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001710 // extensions. The GNU void* casts amount to no-ops since our void* type is
1711 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001712 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001713 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001714 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1715 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1716 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001717 }
1718
Dan Gohman664f8932009-08-12 00:33:55 +00001719 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001720 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001721 // pointer - pointer
1722 Value *LHS = Ops.LHS;
1723 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001724
Ken Dyck199c3d62010-01-11 17:06:35 +00001725 CharUnits ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001726
Chris Lattnere5ed1512009-02-11 07:21:43 +00001727 // Handle GCC extension for pointer arithmetic on void* and function pointer
1728 // types.
1729 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001730 ElementSize = CharUnits::One();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001731 } else {
Ken Dyck199c3d62010-01-11 17:06:35 +00001732 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001733 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001734
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001735 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1736 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1737 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1738 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001739
Chris Lattnere5ed1512009-02-11 07:21:43 +00001740 // Optimize out the shift for element size of 1.
Ken Dyck199c3d62010-01-11 17:06:35 +00001741 if (ElementSize.isOne())
Chris Lattnere5ed1512009-02-11 07:21:43 +00001742 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001743
1744 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001745 // pointer difference in C is only defined in the case where both operands
1746 // are pointing to elements of an array.
Ken Dyck199c3d62010-01-11 17:06:35 +00001747 Value *BytesPerElt =
1748 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
Dan Gohmandf110942009-08-11 22:40:09 +00001749 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001750 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001751}
1752
1753Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1754 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1755 // RHS to the same size as the LHS.
1756 Value *RHS = Ops.RHS;
1757 if (Ops.LHS->getType() != RHS->getType())
1758 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001759
Mike Stumpbe07f602009-12-14 21:58:14 +00001760 if (CGF.CatchUndefined
1761 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1762 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1763 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1764 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1765 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00001766 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00001767 CGF.EmitBlock(Cont);
1768 }
1769
Chris Lattner7f02f722007-08-24 05:35:26 +00001770 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1771}
1772
1773Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1774 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1775 // RHS to the same size as the LHS.
1776 Value *RHS = Ops.RHS;
1777 if (Ops.LHS->getType() != RHS->getType())
1778 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001779
Mike Stumpbe07f602009-12-14 21:58:14 +00001780 if (CGF.CatchUndefined
1781 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1782 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1783 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1784 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1785 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00001786 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00001787 CGF.EmitBlock(Cont);
1788 }
1789
Douglas Gregorf6094622010-07-23 15:58:24 +00001790 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001791 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1792 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1793}
1794
1795Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1796 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001797 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001798 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001799 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00001800 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00001801 assert(E->getOpcode() == BO_EQ ||
1802 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00001803 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
1804 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00001805 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00001806 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00001807 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001808 Value *LHS = Visit(E->getLHS());
1809 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001810
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001811 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001812 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001813 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00001814 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001815 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001816 LHS, RHS, "cmp");
1817 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001818 // Unsigned integers and pointers.
1819 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001820 LHS, RHS, "cmp");
1821 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001822
1823 // If this is a vector comparison, sign extend the result to the appropriate
1824 // vector integer type and return it (don't convert to bool).
1825 if (LHSTy->isVectorType())
1826 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001827
Chris Lattner7f02f722007-08-24 05:35:26 +00001828 } else {
1829 // Complex Comparison: can only be an equality comparison.
1830 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1831 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001832
John McCall183700f2009-09-21 23:43:11 +00001833 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001834
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001835 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001836 if (CETy->isRealFloatingType()) {
1837 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1838 LHS.first, RHS.first, "cmp.r");
1839 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1840 LHS.second, RHS.second, "cmp.i");
1841 } else {
1842 // Complex comparisons can only be equality comparisons. As such, signed
1843 // and unsigned opcodes are the same.
1844 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1845 LHS.first, RHS.first, "cmp.r");
1846 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1847 LHS.second, RHS.second, "cmp.i");
1848 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001849
John McCall2de56d12010-08-25 11:45:40 +00001850 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001851 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1852 } else {
John McCall2de56d12010-08-25 11:45:40 +00001853 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00001854 "Complex comparison other than == or != ?");
1855 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1856 }
1857 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001858
1859 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001860}
1861
1862Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001863 bool Ignore = TestAndClearIgnoreResultAssign();
1864
1865 // __block variables need to have the rhs evaluated first, plus this should
1866 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001867 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00001868 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001869
Daniel Dunbared3849b2008-11-19 09:36:46 +00001870 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001871 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1872 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001873 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001874 if (LHS.isBitField())
1875 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1876 &RHS);
1877 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001878 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001879
1880 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001881 if (Ignore)
1882 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001883
1884 // Objective-C property assignment never reloads the value following a store.
1885 if (LHS.isPropertyRef() || LHS.isKVCRef())
1886 return RHS;
1887
1888 // If the lvalue is non-volatile, return the computed value of the assignment.
1889 if (!LHS.isVolatileQualified())
1890 return RHS;
1891
1892 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001893 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001894}
1895
1896Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001897 const llvm::Type *ResTy = ConvertType(E->getType());
1898
Chris Lattner20eb09d2008-11-12 08:26:50 +00001899 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1900 // If we have 1 && X, just emit X without inserting the control flow.
1901 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1902 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001903 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001904 // ZExt result to int or bool.
1905 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001906 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001907
Chris Lattner7804bcb2009-10-17 04:24:20 +00001908 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001909 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001910 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001911 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001912
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001913 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1914 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001915
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001916 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1917 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1918
1919 // Any edges into the ContBlock are now from an (indeterminate number of)
1920 // edges from this first condition. All of these values will be false. Start
1921 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001922 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1923 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001924 PN->reserveOperandSpace(2); // Normal case, two inputs.
1925 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1926 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001927 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001928
Anders Carlsson72119a82010-02-04 17:18:07 +00001929 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001930 CGF.EmitBlock(RHSBlock);
1931 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson72119a82010-02-04 17:18:07 +00001932 CGF.EndConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001933
Chris Lattner7f02f722007-08-24 05:35:26 +00001934 // Reaquire the RHS block, as there may be subblocks inserted.
1935 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001936
1937 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1938 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001939 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001940 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001941
Chris Lattner7f02f722007-08-24 05:35:26 +00001942 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001943 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001944}
1945
1946Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001947 const llvm::Type *ResTy = ConvertType(E->getType());
1948
Chris Lattner20eb09d2008-11-12 08:26:50 +00001949 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1950 // If we have 0 || X, just emit X without inserting the control flow.
1951 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1952 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001953 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001954 // ZExt result to int or bool.
1955 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001956 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001957
Chris Lattner7804bcb2009-10-17 04:24:20 +00001958 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001959 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001960 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001961 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001962
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001963 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1964 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001965
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001966 // Branch on the LHS first. If it is true, go to the success (cont) block.
1967 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1968
1969 // Any edges into the ContBlock are now from an (indeterminate number of)
1970 // edges from this first condition. All of these values will be true. Start
1971 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001972 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1973 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001974 PN->reserveOperandSpace(2); // Normal case, two inputs.
1975 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1976 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001977 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001978
Anders Carlsson72119a82010-02-04 17:18:07 +00001979 CGF.BeginConditionalBranch();
Anders Carlsson33da07d2009-06-04 02:53:13 +00001980
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001981 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001982 CGF.EmitBlock(RHSBlock);
1983 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001984
Anders Carlsson72119a82010-02-04 17:18:07 +00001985 CGF.EndConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001986
Chris Lattner7f02f722007-08-24 05:35:26 +00001987 // Reaquire the RHS block, as there may be subblocks inserted.
1988 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001989
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001990 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1991 // into the phi node for the edge with the value of RHSCond.
1992 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001993 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001994
Chris Lattner7f02f722007-08-24 05:35:26 +00001995 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001996 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001997}
1998
1999Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2000 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002001 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002002 return Visit(E->getRHS());
2003}
2004
2005//===----------------------------------------------------------------------===//
2006// Other Operators
2007//===----------------------------------------------------------------------===//
2008
Chris Lattner9802a512008-11-12 08:55:54 +00002009/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2010/// expression is cheap enough and side-effect-free enough to evaluate
2011/// unconditionally instead of conditionally. This is used to convert control
2012/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002013static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2014 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00002015 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002016 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002017
Chris Lattner9802a512008-11-12 08:55:54 +00002018 // TODO: Allow anything we can constant fold to an integer or fp constant.
2019 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2020 isa<FloatingLiteral>(E))
2021 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002022
Chris Lattner9802a512008-11-12 08:55:54 +00002023 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2024 // X and Y are local variables.
2025 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2026 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002027 if (VD->hasLocalStorage() && !(CGF.getContext()
2028 .getCanonicalType(VD->getType())
2029 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002030 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002031
Chris Lattner9802a512008-11-12 08:55:54 +00002032 return false;
2033}
2034
2035
Chris Lattner7f02f722007-08-24 05:35:26 +00002036Value *ScalarExprEmitter::
2037VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002038 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00002039 // If the condition constant folds and can be elided, try to avoid emitting
2040 // the condition and the dead arm.
2041 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00002042 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00002043 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00002044 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002045
Chris Lattner31a09842008-11-12 08:04:58 +00002046 // If the dead side doesn't have labels we need, and if the Live side isn't
2047 // the gnu missing ?: extension (which we could handle, but don't bother
2048 // to), just emit the Live part.
2049 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
2050 Live) // Live part isn't missing.
2051 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002052 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002053
2054
Chris Lattner9802a512008-11-12 08:55:54 +00002055 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2056 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002057 // safe to evaluate the LHS and RHS unconditionally.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002058 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2059 CGF) &&
2060 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
Chris Lattner9802a512008-11-12 08:55:54 +00002061 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2062 llvm::Value *LHS = Visit(E->getLHS());
2063 llvm::Value *RHS = Visit(E->getRHS());
2064 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2065 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002066
Douglas Gregor5d743fa2010-08-23 14:50:27 +00002067 if (!E->getLHS() && CGF.getContext().getLangOptions().CPlusPlus) {
2068 // Does not support GNU missing condition extension in C++ yet (see #7726)
2069 CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
2070 return llvm::UndefValue::get(ConvertType(E->getType()));
2071 }
2072
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002073 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2074 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002075 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00002076 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00002077
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002078 // If we don't have the GNU missing condition extension, emit a branch on bool
2079 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00002080 if (E->getLHS()) {
2081 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2082 // the branch on bool.
2083 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2084 } else {
2085 // Otherwise, for the ?: extension, evaluate the conditional and then
2086 // convert it to bool the hard way. We do this explicitly because we need
2087 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00002088 CondVal = CGF.EmitScalarExpr(E->getCond());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002089
Chris Lattner12d152f2009-02-13 23:35:32 +00002090 // In some cases, EmitScalarConversion will delete the "CondVal" expression
2091 // if there are no extra uses (an optimization). Inhibit this by making an
2092 // extra dead use, because we're going to add a use of CondVal later. We
2093 // don't use the builder for this, because we don't want it to get optimized
2094 // away. This leaves dead code, but the ?: extension isn't common.
2095 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2096 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002097
Chris Lattner035cf422008-11-12 08:08:13 +00002098 Value *CondBoolVal =
2099 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2100 CGF.getContext().BoolTy);
2101 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00002102 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002103
Anders Carlsson72119a82010-02-04 17:18:07 +00002104 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002105 CGF.EmitBlock(LHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002106
Chris Lattner7f02f722007-08-24 05:35:26 +00002107 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00002108 Value *LHS;
2109 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00002110 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00002111 else // Perform promotions, to handle cases like "short ?: int"
2112 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002113
Anders Carlsson72119a82010-02-04 17:18:07 +00002114 CGF.EndConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002115 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00002116 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002117
Anders Carlsson72119a82010-02-04 17:18:07 +00002118 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002119 CGF.EmitBlock(RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002120
Eli Friedman856226c2008-05-16 20:38:39 +00002121 Value *RHS = Visit(E->getRHS());
Anders Carlsson72119a82010-02-04 17:18:07 +00002122 CGF.EndConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002123 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00002124 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002125
Chris Lattner7f02f722007-08-24 05:35:26 +00002126 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002127
Eli Friedman48daf592009-12-07 20:25:53 +00002128 // If the LHS or RHS is a throw expression, it will be legitimately null.
2129 if (!LHS)
2130 return RHS;
2131 if (!RHS)
2132 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002133
Chris Lattner7f02f722007-08-24 05:35:26 +00002134 // Create a PHI node for the real part.
2135 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2136 PN->reserveOperandSpace(2);
2137 PN->addIncoming(LHS, LHSBlock);
2138 PN->addIncoming(RHS, RHSBlock);
2139 return PN;
2140}
2141
2142Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002143 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002144}
2145
Chris Lattner2202bce2007-11-30 17:56:23 +00002146Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002147 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002148 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2149
2150 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002151 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002152 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2153
Mike Stump7f79f9b2009-05-29 15:46:01 +00002154 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002155 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002156}
2157
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002158Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00002159 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002160}
2161
Chris Lattner7f02f722007-08-24 05:35:26 +00002162//===----------------------------------------------------------------------===//
2163// Entry Point into this File
2164//===----------------------------------------------------------------------===//
2165
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002166/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2167/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002168Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002169 assert(E && !hasAggregateLLVMType(E->getType()) &&
2170 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002171
Mike Stump7f79f9b2009-05-29 15:46:01 +00002172 return ScalarExprEmitter(*this, IgnoreResultAssign)
2173 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00002174}
Chris Lattner3707b252007-08-26 06:48:56 +00002175
2176/// EmitScalarConversion - Emit a conversion from the specified type to the
2177/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002178Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2179 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002180 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2181 "Invalid scalar expression to emit");
2182 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2183}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002184
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002185/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2186/// type to the specified destination type, where the destination type is an
2187/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002188Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2189 QualType SrcTy,
2190 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002191 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002192 "Invalid complex -> scalar conversion");
2193 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2194 DstTy);
2195}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002196
Chris Lattner8c11a652010-06-26 22:09:34 +00002197
2198llvm::Value *CodeGenFunction::
2199EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2200 bool isInc, bool isPre) {
2201 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2202}
2203
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002204LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2205 llvm::Value *V;
2206 // object->isa or (*object).isa
2207 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002208 // build Class* type
2209 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002210
2211 Expr *BaseExpr = E->getBase();
2212 if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) {
2213 V = CreateTempAlloca(ClassPtrTy, "resval");
2214 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2215 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002216 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2217 MakeAddrLValue(V, E->getType()), E->getType());
2218 } else {
2219 if (E->isArrow())
2220 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2221 else
2222 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002223 }
2224
2225 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002226 ClassPtrTy = ClassPtrTy->getPointerTo();
2227 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002228 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002229}
2230
Douglas Gregor6a03e342010-04-23 04:16:32 +00002231
2232LValue CodeGenFunction::EmitCompoundAssignOperatorLValue(
2233 const CompoundAssignOperator *E) {
2234 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002235 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002236 switch (E->getOpcode()) {
2237#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002238 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002239 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002240 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002241 COMPOUND_OP(Mul);
2242 COMPOUND_OP(Div);
2243 COMPOUND_OP(Rem);
2244 COMPOUND_OP(Add);
2245 COMPOUND_OP(Sub);
2246 COMPOUND_OP(Shl);
2247 COMPOUND_OP(Shr);
2248 COMPOUND_OP(And);
2249 COMPOUND_OP(Xor);
2250 COMPOUND_OP(Or);
2251#undef COMPOUND_OP
2252
John McCall2de56d12010-08-25 11:45:40 +00002253 case BO_PtrMemD:
2254 case BO_PtrMemI:
2255 case BO_Mul:
2256 case BO_Div:
2257 case BO_Rem:
2258 case BO_Add:
2259 case BO_Sub:
2260 case BO_Shl:
2261 case BO_Shr:
2262 case BO_LT:
2263 case BO_GT:
2264 case BO_LE:
2265 case BO_GE:
2266 case BO_EQ:
2267 case BO_NE:
2268 case BO_And:
2269 case BO_Xor:
2270 case BO_Or:
2271 case BO_LAnd:
2272 case BO_LOr:
2273 case BO_Assign:
2274 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002275 assert(false && "Not valid compound assignment operators");
2276 break;
2277 }
2278
2279 llvm_unreachable("Unhandled compound assignment operator");
2280}