blob: dd881350c63ba56fddc346867ec3b87a3fbdd6ec [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"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000015#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000016#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000018#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000022#include "llvm/Constants.h"
23#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000025#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000026#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000030
Chris Lattner7f02f722007-08-24 05:35:26 +000031using namespace clang;
32using namespace CodeGen;
33using llvm::Value;
34
35//===----------------------------------------------------------------------===//
36// Scalar Expression Emitter
37//===----------------------------------------------------------------------===//
38
39struct BinOpInfo {
40 Value *LHS;
41 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000043 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
44 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000045};
46
47namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000048class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000049 : public StmtVisitor<ScalarExprEmitter, Value*> {
50 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000051 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000052 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000053 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000054public:
55
Mike Stump7f79f9b2009-05-29 15:46:01 +000056 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000057 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000058 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000059 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000060
Chris Lattner7f02f722007-08-24 05:35:26 +000061 //===--------------------------------------------------------------------===//
62 // Utilities
63 //===--------------------------------------------------------------------===//
64
Mike Stump7f79f9b2009-05-29 15:46:01 +000065 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000066 bool I = IgnoreResultAssign;
67 IgnoreResultAssign = false;
68 return I;
69 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
72 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000073 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000074
75 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000076 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000077 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000078
Chris Lattner7f02f722007-08-24 05:35:26 +000079 /// EmitLoadOfLValue - Given an expression with complex type that represents a
80 /// value l-value, this method emits the address of the l-value, then loads
81 /// and returns the result.
82 Value *EmitLoadOfLValue(const Expr *E) {
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +000084 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000085
Chris Lattner9abc84e2007-08-26 16:42:57 +000086 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000087 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000088 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000089
Chris Lattner3707b252007-08-26 06:48:56 +000090 /// EmitScalarConversion - Emit a conversion from the specified type to the
91 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000092 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
93
94 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095 /// complex type to the specified destination type, where the destination type
96 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000097 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
98 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000099
Anders Carlssona40a9f32010-05-22 17:45:10 +0000100 /// EmitNullValue - Emit a value that corresponds to null for the given type.
101 Value *EmitNullValue(QualType Ty);
102
Chris Lattner7f02f722007-08-24 05:35:26 +0000103 //===--------------------------------------------------------------------===//
104 // Visitor Methods
105 //===--------------------------------------------------------------------===//
106
107 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000108 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000109 assert(0 && "Stmt can't have complex result type!");
110 return 0;
111 }
112 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000113
Chris Lattner7f02f722007-08-24 05:35:26 +0000114 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
115
116 // Leaves.
117 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000118 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000119 }
120 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000121 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000122 }
123 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000124 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000125 }
Nate Begemane7579b52007-11-15 05:40:03 +0000126 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000127 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000128 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000129 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000130 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000131 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000132 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000133 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000134 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000135 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000136 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000137 CGF.getContext().typesAreCompatible(
138 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000139 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000140 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +0000141 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000142 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000143 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
144 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000145 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000146
Chris Lattner7f02f722007-08-24 05:35:26 +0000147 // l-values.
148 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000149 Expr::EvalResult Result;
150 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
151 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
Devang Patel25c2c8f2010-08-10 17:53:33 +0000152 llvm::ConstantInt *CI
153 = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
154 CGF.EmitDeclRefExprDbgValue(E, CI);
155 return CI;
Eli Friedman28665272009-11-26 03:22:21 +0000156 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 return EmitLoadOfLValue(E);
158 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000159 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
160 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000161 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000162 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
163 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000164 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000165 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000166 return EmitLoadOfLValue(E);
167 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000168 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000169 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000170 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000171 Value *VisitObjCImplicitSetterGetterRefExpr(
172 ObjCImplicitSetterGetterRefExpr *E) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000173 return EmitLoadOfLValue(E);
174 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000175 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
176 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000177 }
178
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000179 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000180 LValue LV = CGF.EmitObjCIsaExpr(E);
181 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000182 return V;
183 }
184
Chris Lattner7f02f722007-08-24 05:35:26 +0000185 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000186 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000187 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000188 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000189 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
190 return EmitLoadOfLValue(E);
191 }
Devang Patel35634f52007-10-24 17:18:43 +0000192
Nate Begeman0533b302009-10-18 20:10:40 +0000193 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000194
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000195 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000196 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000197 }
Eli Friedmand8889622009-11-27 04:41:50 +0000198 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000199 // Make sure to evaluate VLA bounds now so that we have them for later.
200 if (E->getType()->isVariablyModifiedType())
201 CGF.EmitVLASize(E->getType());
202
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000203 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000204 }
Eli Friedmand8889622009-11-27 04:41:50 +0000205 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000206
207 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000208 if (E->getCallReturnType()->isReferenceType())
209 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000210
Chris Lattner9b655512007-08-31 22:49:20 +0000211 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000212 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000213
Chris Lattner33793202007-08-31 22:09:40 +0000214 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000215
Mike Stumpa99038c2009-02-28 09:07:16 +0000216 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000217
Chris Lattner7f02f722007-08-24 05:35:26 +0000218 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000219 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000220 LValue LV = EmitLValue(E->getSubExpr());
221 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000222 }
223 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000224 LValue LV = EmitLValue(E->getSubExpr());
225 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000226 }
227 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000228 LValue LV = EmitLValue(E->getSubExpr());
229 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000230 }
231 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000232 LValue LV = EmitLValue(E->getSubExpr());
233 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000234 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000235
236 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
237 bool isInc, bool isPre);
238
239
Chris Lattner7f02f722007-08-24 05:35:26 +0000240 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCalld608cdb2010-08-22 10:59:02 +0000241 // If the sub-expression is an instance member reference,
242 // EmitDeclRefLValue will magically emit it with the appropriate
243 // value as the "address".
Chris Lattner7f02f722007-08-24 05:35:26 +0000244 return EmitLValue(E->getSubExpr()).getAddress();
245 }
246 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
247 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000248 // This differs from gcc, though, most likely due to a bug in gcc.
249 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000250 return Visit(E->getSubExpr());
251 }
252 Value *VisitUnaryMinus (const UnaryOperator *E);
253 Value *VisitUnaryNot (const UnaryOperator *E);
254 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000255 Value *VisitUnaryReal (const UnaryOperator *E);
256 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000257 Value *VisitUnaryExtension(const UnaryOperator *E) {
258 return Visit(E->getSubExpr());
259 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000260
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000261 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000262 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
263 return Visit(DAE->getExpr());
264 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000265 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
266 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000267 }
268
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000269 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000270 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000271 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000272 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
273 return CGF.EmitCXXNewExpr(E);
274 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000275 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
276 CGF.EmitCXXDeleteExpr(E);
277 return 0;
278 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000279 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
280 return llvm::ConstantInt::get(Builder.getInt1Ty(),
281 E->EvaluateTrait(CGF.getContext()));
282 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000283
Douglas Gregora71d8192009-09-04 17:36:40 +0000284 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
285 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000286 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000287 // operator (), and the result of such a call has type void. The only
288 // effect is the evaluation of the postfix-expression before the dot or
289 // arrow.
290 CGF.EmitScalarExpr(E->getBase());
291 return 0;
292 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000293
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000294 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000295 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000296 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000297
298 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
299 CGF.EmitCXXThrowExpr(E);
300 return 0;
301 }
302
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000304 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000305 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000306 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
307 case LangOptions::SOB_Undefined:
308 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
309 case LangOptions::SOB_Defined:
310 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
311 case LangOptions::SOB_Trapping:
312 return EmitOverflowCheckedBinOp(Ops);
313 }
314 }
315
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000316 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000317 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
319 }
Mike Stump2add4732009-04-01 20:28:16 +0000320 /// Create a binary op that checks for overflow.
321 /// Currently only supports +, - and *.
322 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000323 Value *EmitDiv(const BinOpInfo &Ops);
324 Value *EmitRem(const BinOpInfo &Ops);
325 Value *EmitAdd(const BinOpInfo &Ops);
326 Value *EmitSub(const BinOpInfo &Ops);
327 Value *EmitShl(const BinOpInfo &Ops);
328 Value *EmitShr(const BinOpInfo &Ops);
329 Value *EmitAnd(const BinOpInfo &Ops) {
330 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
331 }
332 Value *EmitXor(const BinOpInfo &Ops) {
333 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
334 }
335 Value *EmitOr (const BinOpInfo &Ops) {
336 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
337 }
338
Chris Lattner1f1ded92007-08-24 21:00:35 +0000339 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000340 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
341 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000342 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000343
Chris Lattner3ccf7742007-08-26 21:41:21 +0000344 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000345 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
346
347 // Binary operators and binary compound assignment operators.
348#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000349 Value *VisitBin ## OP(const BinaryOperator *E) { \
350 return Emit ## OP(EmitBinOps(E)); \
351 } \
352 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
353 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000354 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000355 HANDLEBINOP(Mul)
356 HANDLEBINOP(Div)
357 HANDLEBINOP(Rem)
358 HANDLEBINOP(Add)
359 HANDLEBINOP(Sub)
360 HANDLEBINOP(Shl)
361 HANDLEBINOP(Shr)
362 HANDLEBINOP(And)
363 HANDLEBINOP(Xor)
364 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000365#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000366
Chris Lattner7f02f722007-08-24 05:35:26 +0000367 // Comparisons.
368 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
369 unsigned SICmpOpc, unsigned FCmpOpc);
370#define VISITCOMP(CODE, UI, SI, FP) \
371 Value *VisitBin##CODE(const BinaryOperator *E) { \
372 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
373 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000374 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
375 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
376 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
377 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
378 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
379 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000380#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000381
Chris Lattner7f02f722007-08-24 05:35:26 +0000382 Value *VisitBinAssign (const BinaryOperator *E);
383
384 Value *VisitBinLAnd (const BinaryOperator *E);
385 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000386 Value *VisitBinComma (const BinaryOperator *E);
387
Eli Friedman25b825d2009-11-18 09:41:26 +0000388 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
389 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
390
Chris Lattner7f02f722007-08-24 05:35:26 +0000391 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000392 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000393 Value *VisitConditionalOperator(const ConditionalOperator *CO);
394 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000395 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000396 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
397 return CGF.EmitObjCStringLiteral(E);
398 }
399};
400} // end anonymous namespace.
401
402//===----------------------------------------------------------------------===//
403// Utilities
404//===----------------------------------------------------------------------===//
405
Chris Lattner9abc84e2007-08-26 16:42:57 +0000406/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000407/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000408Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000409 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000410
Chris Lattner9abc84e2007-08-26 16:42:57 +0000411 if (SrcType->isRealFloatingType()) {
412 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000413 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000414 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
415 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000416
John McCall0bab0cd2010-08-23 01:21:21 +0000417 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
418 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000419
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000420 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000421 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000422
Chris Lattner9abc84e2007-08-26 16:42:57 +0000423 // Because of the type rules of C, we often end up computing a logical value,
424 // then zero extending it to int, then wanting it as a logical value again.
425 // Optimize this common case.
426 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000427 if (ZI->getOperand(0)->getType() ==
428 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000429 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000430 // If there aren't any more uses, zap the instruction to save space.
431 // Note that there can be more uses, for example if this
432 // is the result of an assignment.
433 if (ZI->use_empty())
434 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000435 return Result;
436 }
437 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000438
Chris Lattner9abc84e2007-08-26 16:42:57 +0000439 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000440 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000441 return Builder.CreateICmpNE(Src, Zero, "tobool");
442}
443
Chris Lattner3707b252007-08-26 06:48:56 +0000444/// EmitScalarConversion - Emit a conversion from the specified type to the
445/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000446Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
447 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000448 SrcType = CGF.getContext().getCanonicalType(SrcType);
449 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000450 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000451
Chris Lattnercf289082007-08-26 07:21:11 +0000452 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000453
Chris Lattner3707b252007-08-26 06:48:56 +0000454 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000455 if (DstType->isBooleanType())
456 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000457
Chris Lattner3707b252007-08-26 06:48:56 +0000458 const llvm::Type *DstTy = ConvertType(DstType);
459
460 // Ignore conversions like int -> uint.
461 if (Src->getType() == DstTy)
462 return Src;
463
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000464 // Handle pointer conversions next: pointers can only be converted to/from
465 // other pointers and integers. Check for pointer types in terms of LLVM, as
466 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000467 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000468 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000469 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000470 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000471
Chris Lattner3707b252007-08-26 06:48:56 +0000472 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000473 // First, convert to the correct width so that we control the kind of
474 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000475 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000476 bool InputSigned = SrcType->isSignedIntegerType();
477 llvm::Value* IntResult =
478 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
479 // Then, cast to pointer.
480 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000481 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000482
Daniel Dunbar270cc662008-08-25 09:51:32 +0000483 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000484 // Must be an ptr to int cast.
485 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000486 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000487 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000488
Nate Begeman213541a2008-04-18 23:10:10 +0000489 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000490 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000491 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000492 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000493 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
494
495 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000496 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000497 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000498 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
499
500 // Splat the element across to all elements
501 llvm::SmallVector<llvm::Constant*, 16> Args;
502 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
503 for (unsigned i = 0; i < NumElements; i++)
Chris Lattner77b89b82010-06-27 07:15:29 +0000504 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000505
Owen Anderson4a289322009-07-28 21:22:35 +0000506 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000507 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
508 return Yay;
509 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000510
Chris Lattner3b1ae002008-02-02 04:51:41 +0000511 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000512 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000513 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000514 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000515
Chris Lattner3707b252007-08-26 06:48:56 +0000516 // Finally, we have the arithmetic types: real int/float.
517 if (isa<llvm::IntegerType>(Src->getType())) {
518 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000519 if (isa<llvm::IntegerType>(DstTy))
520 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
521 else if (InputSigned)
522 return Builder.CreateSIToFP(Src, DstTy, "conv");
523 else
524 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000525 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000526
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000527 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000528 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000529 if (DstType->isSignedIntegerType())
530 return Builder.CreateFPToSI(Src, DstTy, "conv");
531 else
532 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000533 }
534
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000535 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000536 if (DstTy->getTypeID() < Src->getType()->getTypeID())
537 return Builder.CreateFPTrunc(Src, DstTy, "conv");
538 else
539 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000540}
541
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000542/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
543/// type to the specified destination type, where the destination type is an
544/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000545Value *ScalarExprEmitter::
546EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
547 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000548 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000549 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000550
Chris Lattnered70f0a2007-08-26 16:52:28 +0000551 // Handle conversions to bool first, they are special: comparisons against 0.
552 if (DstTy->isBooleanType()) {
553 // Complex != 0 -> (Real != 0) | (Imag != 0)
554 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
555 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
556 return Builder.CreateOr(Src.first, Src.second, "tobool");
557 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000558
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000559 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
560 // the imaginary part of the complex value is discarded and the value of the
561 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000562 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000563 return EmitScalarConversion(Src.first, SrcTy, DstTy);
564}
565
Anders Carlssona40a9f32010-05-22 17:45:10 +0000566Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000567 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
568 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
569
570 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000571}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000572
Chris Lattner7f02f722007-08-24 05:35:26 +0000573//===----------------------------------------------------------------------===//
574// Visitor Methods
575//===----------------------------------------------------------------------===//
576
577Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000578 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000579 if (E->getType()->isVoidType())
580 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000581 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000582}
583
Eli Friedmand38617c2008-05-14 19:38:39 +0000584Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000585 // Vector Mask Case
586 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000587 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000588 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
589 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
590 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000591
Nate Begeman37b6a572010-06-08 00:16:34 +0000592 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
593 unsigned LHSElts = LTy->getNumElements();
594
595 if (E->getNumSubExprs() == 3) {
596 Mask = CGF.EmitScalarExpr(E->getExpr(2));
597
598 // Shuffle LHS & RHS into one input vector.
599 llvm::SmallVector<llvm::Constant*, 32> concat;
600 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000601 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
602 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000603 }
604
605 Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size());
606 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
607 LHSElts *= 2;
608 } else {
609 Mask = RHS;
610 }
611
612 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
613 llvm::Constant* EltMask;
614
615 // Treat vec3 like vec4.
616 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
617 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
618 (1 << llvm::Log2_32(LHSElts+2))-1);
619 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
620 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
621 (1 << llvm::Log2_32(LHSElts+1))-1);
622 else
623 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
624 (1 << llvm::Log2_32(LHSElts))-1);
625
626 // Mask off the high bits of each shuffle index.
627 llvm::SmallVector<llvm::Constant *, 32> MaskV;
628 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
629 MaskV.push_back(EltMask);
630
631 Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size());
632 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
633
634 // newv = undef
635 // mask = mask & maskbits
636 // for each elt
637 // n = extract mask i
638 // x = extract val n
639 // newv = insert newv, x, i
640 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
641 MTy->getNumElements());
642 Value* NewV = llvm::UndefValue::get(RTy);
643 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000644 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000645 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000646 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000647
648 // Handle vec3 special since the index will be off by one for the RHS.
649 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
650 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000651 cmpIndx = Builder.CreateICmpUGT(Indx,
652 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000653 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000654 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000655 "shuf_idx_adj");
656 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
657 }
658 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
659 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
660 }
661 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000662 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000663
Eli Friedmand38617c2008-05-14 19:38:39 +0000664 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
665 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000666
667 // Handle vec3 special since the index will be off by one for the RHS.
668 llvm::SmallVector<llvm::Constant*, 32> indices;
669 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
670 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
671 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
672 if (VTy->getNumElements() == 3) {
673 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
674 uint64_t cVal = CI->getZExtValue();
675 if (cVal > 3) {
676 C = llvm::ConstantInt::get(C->getType(), cVal-1);
677 }
678 }
679 }
680 indices.push_back(C);
681 }
682
Owen Anderson4a289322009-07-28 21:22:35 +0000683 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000684 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
685}
Eli Friedman28665272009-11-26 03:22:21 +0000686Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
687 Expr::EvalResult Result;
688 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
689 if (E->isArrow())
690 CGF.EmitScalarExpr(E->getBase());
691 else
692 EmitLValue(E->getBase());
693 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
694 }
695 return EmitLoadOfLValue(E);
696}
Eli Friedmand38617c2008-05-14 19:38:39 +0000697
Chris Lattner7f02f722007-08-24 05:35:26 +0000698Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000699 TestAndClearIgnoreResultAssign();
700
Chris Lattner7f02f722007-08-24 05:35:26 +0000701 // Emit subscript expressions in rvalue context's. For most cases, this just
702 // loads the lvalue formed by the subscript expr. However, we have to be
703 // careful, because the base of a vector subscript is occasionally an rvalue,
704 // so we can't get it as an lvalue.
705 if (!E->getBase()->getType()->isVectorType())
706 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000707
Chris Lattner7f02f722007-08-24 05:35:26 +0000708 // Handle the vector case. The base must be a vector, the index must be an
709 // integer value.
710 Value *Base = Visit(E->getBase());
711 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000712 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000713 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000714 return Builder.CreateExtractElement(Base, Idx, "vecext");
715}
716
Nate Begeman0533b302009-10-18 20:10:40 +0000717static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
718 unsigned Off, const llvm::Type *I32Ty) {
719 int MV = SVI->getMaskValue(Idx);
720 if (MV == -1)
721 return llvm::UndefValue::get(I32Ty);
722 return llvm::ConstantInt::get(I32Ty, Off+MV);
723}
724
725Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
726 bool Ignore = TestAndClearIgnoreResultAssign();
727 (void)Ignore;
728 assert (Ignore == false && "init list ignored");
729 unsigned NumInitElements = E->getNumInits();
730
731 if (E->hadArrayRangeDesignator())
732 CGF.ErrorUnsupported(E, "GNU array range designator extension");
733
734 const llvm::VectorType *VType =
735 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
736
737 // We have a scalar in braces. Just use the first element.
738 if (!VType)
739 return Visit(E->getInit(0));
740
741 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000742
743 // Loop over initializers collecting the Value for each, and remembering
744 // whether the source was swizzle (ExtVectorElementExpr). This will allow
745 // us to fold the shuffle for the swizzle into the shuffle for the vector
746 // initializer, since LLVM optimizers generally do not want to touch
747 // shuffles.
748 unsigned CurIdx = 0;
749 bool VIsUndefShuffle = false;
750 llvm::Value *V = llvm::UndefValue::get(VType);
751 for (unsigned i = 0; i != NumInitElements; ++i) {
752 Expr *IE = E->getInit(i);
753 Value *Init = Visit(IE);
754 llvm::SmallVector<llvm::Constant*, 16> Args;
755
756 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
757
758 // Handle scalar elements. If the scalar initializer is actually one
759 // element of a different vector of the same width, use shuffle instead of
760 // extract+insert.
761 if (!VVT) {
762 if (isa<ExtVectorElementExpr>(IE)) {
763 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
764
765 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
766 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
767 Value *LHS = 0, *RHS = 0;
768 if (CurIdx == 0) {
769 // insert into undef -> shuffle (src, undef)
770 Args.push_back(C);
771 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000772 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000773
774 LHS = EI->getVectorOperand();
775 RHS = V;
776 VIsUndefShuffle = true;
777 } else if (VIsUndefShuffle) {
778 // insert into undefshuffle && size match -> shuffle (v, src)
779 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
780 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000781 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
782 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000783 ResElts + C->getZExtValue()));
784 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000785 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000786
787 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
788 RHS = EI->getVectorOperand();
789 VIsUndefShuffle = false;
790 }
791 if (!Args.empty()) {
792 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
793 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
794 ++CurIdx;
795 continue;
796 }
797 }
798 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000799 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000800 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
801 VIsUndefShuffle = false;
802 ++CurIdx;
803 continue;
804 }
805
806 unsigned InitElts = VVT->getNumElements();
807
808 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
809 // input is the same width as the vector being constructed, generate an
810 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000811 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000812 if (isa<ExtVectorElementExpr>(IE)) {
813 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
814 Value *SVOp = SVI->getOperand(0);
815 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
816
817 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000818 for (unsigned j = 0; j != CurIdx; ++j) {
819 // If the current vector initializer is a shuffle with undef, merge
820 // this shuffle directly into it.
821 if (VIsUndefShuffle) {
822 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000823 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000824 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000825 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000826 }
827 }
828 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000829 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000830 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000831 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000832
833 if (VIsUndefShuffle)
834 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
835
836 Init = SVOp;
837 }
838 }
839
840 // Extend init to result vector length, and then shuffle its contribution
841 // to the vector initializer into V.
842 if (Args.empty()) {
843 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000844 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000845 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000846 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000847 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
848 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000849 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000850
851 Args.clear();
852 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000853 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000854 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000855 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000856 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000857 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000858 }
859
860 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
861 // merging subsequent shuffles into this one.
862 if (CurIdx == 0)
863 std::swap(V, Init);
864 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
865 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
866 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
867 CurIdx += InitElts;
868 }
869
870 // FIXME: evaluate codegen vs. shuffling against constant null vector.
871 // Emit remaining default initializers.
872 const llvm::Type *EltTy = VType->getElementType();
873
874 // Emit remaining default initializers
875 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000876 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000877 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
878 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
879 }
880 return V;
881}
882
Anders Carlssona3697c92009-11-23 17:57:54 +0000883static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
884 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000885
John McCall2de56d12010-08-25 11:45:40 +0000886 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000887 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000888
889 if (isa<CXXThisExpr>(E)) {
890 // We always assume that 'this' is never null.
891 return false;
892 }
893
894 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000895 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000896 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000897 return false;
898 }
899
900 return true;
901}
902
Chris Lattner7f02f722007-08-24 05:35:26 +0000903// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
904// have to handle a more broad range of conversions than explicit casts, as they
905// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +0000906Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
907 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000908 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +0000909 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000910
Mike Stump7f79f9b2009-05-29 15:46:01 +0000911 if (!DestTy->isVoidType())
912 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000913
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000914 // Since almost all cast kinds apply to scalars, this switch doesn't have
915 // a default case, so the compiler will warn on a missing case. The cases
916 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +0000917 switch (Kind) {
John McCall2de56d12010-08-25 11:45:40 +0000918 case CK_Unknown:
Eli Friedmand8889622009-11-27 04:41:50 +0000919 // FIXME: All casts should have a known kind!
Eli Friedmanad35a832009-11-16 21:33:53 +0000920 //assert(0 && "Unknown cast kind!");
Anders Carlssone9776242009-08-24 18:26:39 +0000921 break;
Eli Friedmanad35a832009-11-16 21:33:53 +0000922
John McCall2de56d12010-08-25 11:45:40 +0000923 case CK_LValueBitCast:
924 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +0000925 Value *V = EmitLValue(E).getAddress();
926 V = Builder.CreateBitCast(V,
927 ConvertType(CGF.getContext().getPointerType(DestTy)));
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000928 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
Douglas Gregore39a3892010-07-13 23:17:26 +0000929 }
930
John McCall2de56d12010-08-25 11:45:40 +0000931 case CK_AnyPointerToObjCPointerCast:
932 case CK_AnyPointerToBlockPointerCast:
933 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000934 Value *Src = Visit(const_cast<Expr*>(E));
935 return Builder.CreateBitCast(Src, ConvertType(DestTy));
936 }
John McCall2de56d12010-08-25 11:45:40 +0000937 case CK_NoOp:
938 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000939 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000940
John McCall2de56d12010-08-25 11:45:40 +0000941 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +0000942 const CXXRecordDecl *DerivedClassDecl =
943 DestTy->getCXXRecordDeclForPointerType();
944
Anders Carlssona04efdf2010-04-24 21:23:59 +0000945 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +0000946 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +0000947 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +0000948 }
John McCall2de56d12010-08-25 11:45:40 +0000949 case CK_UncheckedDerivedToBase:
950 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +0000951 const RecordType *DerivedClassTy =
952 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
953 CXXRecordDecl *DerivedClassDecl =
954 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
955
Anders Carlsson34a2d382010-04-24 21:06:20 +0000956 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +0000957 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +0000958 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +0000959 }
John McCall2de56d12010-08-25 11:45:40 +0000960 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000961 Value *V = Visit(const_cast<Expr*>(E));
962 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
963 return CGF.EmitDynamicCast(V, DCE);
964 }
John McCall2de56d12010-08-25 11:45:40 +0000965 case CK_ToUnion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000966 assert(0 && "Should be unreachable!");
967 break;
Eli Friedmand8889622009-11-27 04:41:50 +0000968
John McCall2de56d12010-08-25 11:45:40 +0000969 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +0000970 assert(E->getType()->isArrayType() &&
971 "Array to pointer decay must have array source type!");
972
973 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
974
975 // Note that VLA pointers are always decayed, so we don't need to do
976 // anything here.
977 if (!E->getType()->isVariableArrayType()) {
978 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
979 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
980 ->getElementType()) &&
981 "Expected pointer to array");
982 V = Builder.CreateStructGEP(V, 0, "arraydecay");
983 }
984
985 return V;
986 }
John McCall2de56d12010-08-25 11:45:40 +0000987 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +0000988 return EmitLValue(E).getAddress();
989
John McCall2de56d12010-08-25 11:45:40 +0000990 case CK_NullToMemberPointer: {
John McCalld608cdb2010-08-22 10:59:02 +0000991 // If the subexpression's type is the C++0x nullptr_t, emit the
992 // subexpression, which may have side effects.
993 if (E->getType()->isNullPtrType())
994 (void) Visit(E);
995
John McCall0bab0cd2010-08-23 01:21:21 +0000996 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
997 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
998 }
Anders Carlsson191dfe92009-09-12 04:57:16 +0000999
John McCall2de56d12010-08-25 11:45:40 +00001000 case CK_BaseToDerivedMemberPointer:
1001 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001002 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001003
1004 // Note that the AST doesn't distinguish between checked and
1005 // unchecked member pointer conversions, so we always have to
1006 // implement checked conversions here. This is inefficient when
1007 // actual control flow may be required in order to perform the
1008 // check, which it is for data member pointers (but not member
1009 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001010 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001011 }
John McCall0bab0cd2010-08-23 01:21:21 +00001012
Eli Friedmand8889622009-11-27 04:41:50 +00001013
John McCall2de56d12010-08-25 11:45:40 +00001014 case CK_ConstructorConversion:
Eli Friedmand8889622009-11-27 04:41:50 +00001015 assert(0 && "Should be unreachable!");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001016 break;
1017
John McCall2de56d12010-08-25 11:45:40 +00001018 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001019 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001020
Anders Carlsson82debc72009-10-18 18:12:03 +00001021 // First, convert to the correct width so that we control the kind of
1022 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001023 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001024 bool InputSigned = E->getType()->isSignedIntegerType();
1025 llvm::Value* IntResult =
1026 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001027
Anders Carlsson82debc72009-10-18 18:12:03 +00001028 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001029 }
John McCall2de56d12010-08-25 11:45:40 +00001030 case CK_PointerToIntegral: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001031 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001032
1033 // Handle conversion to bool correctly.
1034 if (DestTy->isBooleanType())
1035 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1036
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001037 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1038 }
John McCall2de56d12010-08-25 11:45:40 +00001039 case CK_ToVoid: {
Douglas Gregor569c3162010-08-07 11:51:51 +00001040 if (E->Classify(CGF.getContext()).isGLValue())
1041 CGF.EmitLValue(E);
1042 else
1043 CGF.EmitAnyExpr(E, 0, false, true);
Eli Friedmanad35a832009-11-16 21:33:53 +00001044 return 0;
1045 }
John McCall2de56d12010-08-25 11:45:40 +00001046 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001047 const llvm::Type *DstTy = ConvertType(DestTy);
1048 Value *Elt = Visit(const_cast<Expr*>(E));
1049
1050 // Insert the element in element zero of an undef vector
1051 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001052 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001053 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1054
1055 // Splat the element across to all elements
1056 llvm::SmallVector<llvm::Constant*, 16> Args;
1057 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1058 for (unsigned i = 0; i < NumElements; i++)
Chris Lattner77b89b82010-06-27 07:15:29 +00001059 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Eli Friedmanad35a832009-11-16 21:33:53 +00001060
1061 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1062 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1063 return Yay;
1064 }
John McCall2de56d12010-08-25 11:45:40 +00001065 case CK_IntegralCast:
1066 case CK_IntegralToFloating:
1067 case CK_FloatingToIntegral:
1068 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001069 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001070
John McCall2de56d12010-08-25 11:45:40 +00001071 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001072 llvm::Value *MemPtr = Visit(E);
1073 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1074 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001075 }
John McCall0bab0cd2010-08-23 01:21:21 +00001076 }
1077
Chris Lattner58a2e942007-08-26 07:26:12 +00001078 // Handle cases where the source is an non-complex type.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001079
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001080 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +00001081 Value *Src = Visit(const_cast<Expr*>(E));
1082
Chris Lattner3707b252007-08-26 06:48:56 +00001083 // Use EmitScalarConversion to perform the conversion.
1084 return EmitScalarConversion(Src, E->getType(), DestTy);
1085 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001086
Chris Lattner9b2dc282008-04-04 16:54:41 +00001087 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001088 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001089 bool IgnoreImag = true;
1090 bool IgnoreImagAssign = true;
1091 bool IgnoreReal = IgnoreResultAssign;
1092 bool IgnoreRealAssign = IgnoreResultAssign;
1093 if (DestTy->isBooleanType())
1094 IgnoreImagAssign = IgnoreImag = false;
1095 else if (DestTy->isVoidType()) {
1096 IgnoreReal = IgnoreImag = false;
1097 IgnoreRealAssign = IgnoreImagAssign = true;
1098 }
1099 CodeGenFunction::ComplexPairTy V
1100 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
1101 IgnoreImagAssign);
1102 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001103 }
Chris Lattner10b00cf2007-08-26 07:16:41 +00001104
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001105 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
1106 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001107 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001108 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001109}
1110
Chris Lattner33793202007-08-31 22:09:40 +00001111Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +00001112 return CGF.EmitCompoundStmt(*E->getSubStmt(),
1113 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001114}
1115
Mike Stumpa99038c2009-02-28 09:07:16 +00001116Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001117 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1118 if (E->getType().isObjCGCWeak())
1119 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +00001120 return Builder.CreateLoad(V, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +00001121}
Chris Lattner33793202007-08-31 22:09:40 +00001122
Chris Lattner7f02f722007-08-24 05:35:26 +00001123//===----------------------------------------------------------------------===//
1124// Unary Operators
1125//===----------------------------------------------------------------------===//
1126
Chris Lattner8c11a652010-06-26 22:09:34 +00001127llvm::Value *ScalarExprEmitter::
1128EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1129 bool isInc, bool isPre) {
1130
1131 QualType ValTy = E->getSubExpr()->getType();
1132 llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy);
1133
1134 int AmountVal = isInc ? 1 : -1;
1135
1136 if (ValTy->isPointerType() &&
1137 ValTy->getAs<PointerType>()->isVariableArrayType()) {
1138 // The amount of the addition/subtraction needs to account for the VLA size
1139 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1140 }
1141
1142 llvm::Value *NextVal;
1143 if (const llvm::PointerType *PT =
1144 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +00001145 llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal);
Chris Lattner8c11a652010-06-26 22:09:34 +00001146 if (!isa<llvm::FunctionType>(PT->getElementType())) {
1147 QualType PTEE = ValTy->getPointeeType();
1148 if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) {
1149 // Handle interface types, which are not represented with a concrete
1150 // type.
1151 int size = CGF.getContext().getTypeSize(OIT) / 8;
1152 if (!isInc)
1153 size = -size;
1154 Inc = llvm::ConstantInt::get(Inc->getType(), size);
1155 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1156 InVal = Builder.CreateBitCast(InVal, i8Ty);
1157 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1158 llvm::Value *lhs = LV.getAddress();
1159 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001160 LV = CGF.MakeAddrLValue(lhs, ValTy);
Chris Lattner8c11a652010-06-26 22:09:34 +00001161 } else
1162 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1163 } else {
1164 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1165 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1166 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1167 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1168 }
1169 } else if (InVal->getType()->isIntegerTy(1) && isInc) {
1170 // Bool++ is an interesting case, due to promotion rules, we get:
1171 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1172 // Bool = ((int)Bool+1) != 0
1173 // An interesting aspect of this is that increment is always true.
1174 // Decrement does not have this property.
1175 NextVal = llvm::ConstantInt::getTrue(VMContext);
1176 } else if (isa<llvm::IntegerType>(InVal->getType())) {
1177 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1178
Chris Lattner640d3262010-06-26 22:18:28 +00001179 if (!ValTy->isSignedIntegerType())
1180 // Unsigned integer inc is always two's complement.
Chris Lattner8c11a652010-06-26 22:09:34 +00001181 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner640d3262010-06-26 22:18:28 +00001182 else {
1183 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1184 case LangOptions::SOB_Undefined:
1185 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1186 break;
1187 case LangOptions::SOB_Defined:
1188 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1189 break;
1190 case LangOptions::SOB_Trapping:
1191 BinOpInfo BinOp;
1192 BinOp.LHS = InVal;
1193 BinOp.RHS = NextVal;
1194 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001195 BinOp.Opcode = BO_Add;
Chris Lattner640d3262010-06-26 22:18:28 +00001196 BinOp.E = E;
John McCall401be6b2010-08-05 17:39:44 +00001197 NextVal = EmitOverflowCheckedBinOp(BinOp);
1198 break;
Chris Lattner640d3262010-06-26 22:18:28 +00001199 }
1200 }
Chris Lattner8c11a652010-06-26 22:09:34 +00001201 } else {
1202 // Add the inc/dec to the real part.
1203 if (InVal->getType()->isFloatTy())
1204 NextVal =
1205 llvm::ConstantFP::get(VMContext,
1206 llvm::APFloat(static_cast<float>(AmountVal)));
1207 else if (InVal->getType()->isDoubleTy())
1208 NextVal =
1209 llvm::ConstantFP::get(VMContext,
1210 llvm::APFloat(static_cast<double>(AmountVal)));
1211 else {
1212 llvm::APFloat F(static_cast<float>(AmountVal));
1213 bool ignored;
1214 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1215 &ignored);
1216 NextVal = llvm::ConstantFP::get(VMContext, F);
1217 }
1218 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1219 }
1220
1221 // Store the updated result through the lvalue.
1222 if (LV.isBitField())
1223 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal);
1224 else
1225 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1226
1227 // If this is a postinc, return the value read from memory, otherwise use the
1228 // updated value.
1229 return isPre ? NextVal : InVal;
1230}
1231
1232
1233
Chris Lattner7f02f722007-08-24 05:35:26 +00001234Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001235 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001236 // Emit unary minus with EmitSub so we handle overflow cases etc.
1237 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001238 BinOp.RHS = Visit(E->getSubExpr());
1239
1240 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1241 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1242 else
1243 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001244 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001245 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001246 BinOp.E = E;
1247 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001248}
1249
1250Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001251 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001252 Value *Op = Visit(E->getSubExpr());
1253 return Builder.CreateNot(Op, "neg");
1254}
1255
1256Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1257 // Compare operand to zero.
1258 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001259
Chris Lattner7f02f722007-08-24 05:35:26 +00001260 // Invert value.
1261 // TODO: Could dynamically modify easy computations here. For example, if
1262 // the operand is an icmp ne, turn into icmp eq.
1263 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001264
Anders Carlsson9f84d882009-05-19 18:44:53 +00001265 // ZExt result to the expr type.
1266 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001267}
1268
Eli Friedman0027d2b2010-08-05 09:58:49 +00001269Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1270 // Try folding the offsetof to a constant.
1271 Expr::EvalResult EvalResult;
1272 if (E->Evaluate(EvalResult, CGF.getContext()))
1273 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1274
1275 // Loop over the components of the offsetof to compute the value.
1276 unsigned n = E->getNumComponents();
1277 const llvm::Type* ResultType = ConvertType(E->getType());
1278 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1279 QualType CurrentType = E->getTypeSourceInfo()->getType();
1280 for (unsigned i = 0; i != n; ++i) {
1281 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001282 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001283 switch (ON.getKind()) {
1284 case OffsetOfExpr::OffsetOfNode::Array: {
1285 // Compute the index
1286 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1287 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1288 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1289 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1290
1291 // Save the element type
1292 CurrentType =
1293 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1294
1295 // Compute the element size
1296 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1297 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1298
1299 // Multiply out to compute the result
1300 Offset = Builder.CreateMul(Idx, ElemSize);
1301 break;
1302 }
1303
1304 case OffsetOfExpr::OffsetOfNode::Field: {
1305 FieldDecl *MemberDecl = ON.getField();
1306 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1307 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1308
1309 // Compute the index of the field in its parent.
1310 unsigned i = 0;
1311 // FIXME: It would be nice if we didn't have to loop here!
1312 for (RecordDecl::field_iterator Field = RD->field_begin(),
1313 FieldEnd = RD->field_end();
1314 Field != FieldEnd; (void)++Field, ++i) {
1315 if (*Field == MemberDecl)
1316 break;
1317 }
1318 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1319
1320 // Compute the offset to the field
1321 int64_t OffsetInt = RL.getFieldOffset(i) /
1322 CGF.getContext().getCharWidth();
1323 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1324
1325 // Save the element type.
1326 CurrentType = MemberDecl->getType();
1327 break;
1328 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001329
Eli Friedman0027d2b2010-08-05 09:58:49 +00001330 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001331 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001332
Eli Friedman0027d2b2010-08-05 09:58:49 +00001333 case OffsetOfExpr::OffsetOfNode::Base: {
1334 if (ON.getBase()->isVirtual()) {
1335 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1336 continue;
1337 }
1338
1339 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1340 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1341
1342 // Save the element type.
1343 CurrentType = ON.getBase()->getType();
1344
1345 // Compute the offset to the base.
1346 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1347 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1348 int64_t OffsetInt = RL.getBaseClassOffset(BaseRD) /
1349 CGF.getContext().getCharWidth();
1350 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1351 break;
1352 }
1353 }
1354 Result = Builder.CreateAdd(Result, Offset);
1355 }
1356 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001357}
1358
Sebastian Redl05189992008-11-11 17:56:53 +00001359/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1360/// argument of the sizeof expression as an integer.
1361Value *
1362ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001363 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001364 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001365 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001366 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1367 if (E->isArgumentType()) {
1368 // sizeof(type) - make sure to emit the VLA size.
1369 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001370 } else {
1371 // C99 6.5.3.4p2: If the argument is an expression of type
1372 // VLA, it is evaluated.
1373 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001374 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001375
Anders Carlsson96f21472009-02-05 19:43:10 +00001376 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001377 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001378 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001379
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001380 // If this isn't sizeof(vla), the result must be constant; use the constant
1381 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001382 Expr::EvalResult Result;
1383 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001384 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001385}
1386
Chris Lattner46f93d02007-08-24 21:20:17 +00001387Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1388 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001389 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001390 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +00001391 return Visit(Op);
1392}
1393Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1394 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001395 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001396 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001397
Mike Stump7f79f9b2009-05-29 15:46:01 +00001398 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1399 // effects are evaluated, but not the actual value.
1400 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1401 CGF.EmitLValue(Op);
1402 else
1403 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001404 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001405}
1406
Chris Lattner7f02f722007-08-24 05:35:26 +00001407//===----------------------------------------------------------------------===//
1408// Binary Operators
1409//===----------------------------------------------------------------------===//
1410
1411BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001412 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001413 BinOpInfo Result;
1414 Result.LHS = Visit(E->getLHS());
1415 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001416 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001417 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001418 Result.E = E;
1419 return Result;
1420}
1421
Douglas Gregor6a03e342010-04-23 04:16:32 +00001422LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1423 const CompoundAssignOperator *E,
1424 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001425 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001426 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001427 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001428
Eli Friedmanab3a8522009-03-28 01:22:36 +00001429 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001430 // This needs to go through the complex expression emitter, but it's a tad
1431 // complicated to do that... I'm leaving it out for now. (Note that we do
1432 // actually need the imaginary part of the RHS for multiplication and
1433 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001434 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001435 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001436 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001437 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001438
Mike Stumpcc0442f2009-05-22 19:07:20 +00001439 // Emit the RHS first. __block variables need to have the rhs evaluated
1440 // first, plus this should improve codegen a little.
1441 OpInfo.RHS = Visit(E->getRHS());
1442 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001443 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001444 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001445 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001446 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001447 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001448 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1449 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001450
Chris Lattner1f1ded92007-08-24 21:00:35 +00001451 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001452 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001453
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001454 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001455 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001456
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001457 // Store the result value into the LHS lvalue. Bit-fields are handled
1458 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1459 // 'An assignment expression has the value of the left operand after the
1460 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001461 if (LHSLV.isBitField())
1462 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1463 &Result);
1464 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001465 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001466
Douglas Gregor6a03e342010-04-23 04:16:32 +00001467 return LHSLV;
1468}
1469
1470Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1471 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1472 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001473 Value *RHS;
1474 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1475
1476 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001477 if (Ignore)
1478 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001479
1480 // Objective-C property assignment never reloads the value following a store.
1481 if (LHS.isPropertyRef() || LHS.isKVCRef())
1482 return RHS;
1483
1484 // If the lvalue is non-volatile, return the computed value of the assignment.
1485 if (!LHS.isVolatileQualified())
1486 return RHS;
1487
1488 // Otherwise, reload the value.
1489 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001490}
1491
1492
Chris Lattner7f02f722007-08-24 05:35:26 +00001493Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001494 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001495 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001496 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001497 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1498 else
1499 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1500}
1501
1502Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1503 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +00001504 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001505 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1506 else
1507 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1508}
1509
Mike Stump2add4732009-04-01 20:28:16 +00001510Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1511 unsigned IID;
1512 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001513
Chris Lattner9a207232010-06-26 21:48:21 +00001514 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001515 case BO_Add:
1516 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001517 OpID = 1;
1518 IID = llvm::Intrinsic::sadd_with_overflow;
1519 break;
John McCall2de56d12010-08-25 11:45:40 +00001520 case BO_Sub:
1521 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001522 OpID = 2;
1523 IID = llvm::Intrinsic::ssub_with_overflow;
1524 break;
John McCall2de56d12010-08-25 11:45:40 +00001525 case BO_Mul:
1526 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001527 OpID = 3;
1528 IID = llvm::Intrinsic::smul_with_overflow;
1529 break;
1530 default:
1531 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001532 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001533 }
Mike Stump035cf892009-04-02 18:15:54 +00001534 OpID <<= 1;
1535 OpID |= 1;
1536
Mike Stump2add4732009-04-01 20:28:16 +00001537 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1538
1539 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1540
1541 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1542 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1543 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1544
1545 // Branch in case of overflow.
Chris Lattner93a00352010-08-07 00:20:46 +00001546 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1547 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001548
1549 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1550
Chris Lattner93a00352010-08-07 00:20:46 +00001551 // Handle overflow with llvm.trap.
1552 // TODO: it would be better to generate one of these blocks per function.
Mike Stump2add4732009-04-01 20:28:16 +00001553 Builder.SetInsertPoint(overflowBB);
Chris Lattner93a00352010-08-07 00:20:46 +00001554 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
1555 Builder.CreateCall(Trap);
1556 Builder.CreateUnreachable();
1557
1558 // Continue on.
Mike Stump2add4732009-04-01 20:28:16 +00001559 Builder.SetInsertPoint(continueBB);
Chris Lattner93a00352010-08-07 00:20:46 +00001560 return result;
Mike Stump2add4732009-04-01 20:28:16 +00001561}
Chris Lattner7f02f722007-08-24 05:35:26 +00001562
1563Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001564 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001565 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001566 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1567 case LangOptions::SOB_Undefined:
1568 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1569 case LangOptions::SOB_Defined:
1570 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1571 case LangOptions::SOB_Trapping:
1572 return EmitOverflowCheckedBinOp(Ops);
1573 }
1574 }
1575
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001576 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001577 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001578
Chris Lattner7f02f722007-08-24 05:35:26 +00001579 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001580 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001581
Chris Lattner7f215c12010-06-26 21:52:32 +00001582 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001583 // use this path.
1584 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1585
Steve Naroff14108da2009-07-10 23:34:53 +00001586 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001587 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001588 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001589 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001590 }
Chris Lattner9a207232010-06-26 21:48:21 +00001591
Chris Lattner8f925282008-01-03 06:36:51 +00001592 Value *Ptr, *Idx;
1593 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001594 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001595 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001596 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001597 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001598 Ptr = Ops.LHS;
1599 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001600 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001601 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001602 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1603 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001604 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001605 Ptr = Ops.RHS;
1606 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001607 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001608 }
1609
1610 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001611 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001612 // Zero or sign extend the pointer value based on whether the index is
1613 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001614 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001615 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001616 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1617 else
1618 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1619 }
Steve Naroff14108da2009-07-10 23:34:53 +00001620 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001621 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001622 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001623 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001624 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001625 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001626 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001627 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001628 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1629 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1630 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001631 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001632
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001633 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1634 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1635 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001636 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001637 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001638 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001639 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001640 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001641 }
1642
Dan Gohman664f8932009-08-12 00:33:55 +00001643 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001644}
1645
1646Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001647 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001648 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001649 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1650 case LangOptions::SOB_Undefined:
1651 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1652 case LangOptions::SOB_Defined:
1653 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1654 case LangOptions::SOB_Trapping:
1655 return EmitOverflowCheckedBinOp(Ops);
1656 }
1657 }
1658
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001659 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001660 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001661
Chris Lattner7f02f722007-08-24 05:35:26 +00001662 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001663 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001664
Chris Lattner9a207232010-06-26 21:48:21 +00001665 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1666 // use this path.
1667 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1668
1669 if (BinOp->getLHS()->getType()->isPointerType() &&
1670 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001671 // The amount of the addition needs to account for the VLA size for
1672 // ptr-int
1673 // The amount of the division needs to account for the VLA size for
1674 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001675 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001676 }
1677
Chris Lattner9a207232010-06-26 21:48:21 +00001678 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001679 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001680 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1681 // pointer - int
1682 Value *Idx = Ops.RHS;
1683 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001684 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001685 // Zero or sign extend the pointer value based on whether the index is
1686 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001687 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001688 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001689 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1690 else
1691 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1692 }
1693 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001694
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001695 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001696 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001697 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001698 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001699 CGF.getContext().
1700 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001701 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001702 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001703 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1704 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1705 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001706 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001707
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001708 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001709 // extensions. The GNU void* casts amount to no-ops since our void* type is
1710 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001711 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001712 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001713 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1714 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1715 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001716 }
1717
Dan Gohman664f8932009-08-12 00:33:55 +00001718 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001719 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001720 // pointer - pointer
1721 Value *LHS = Ops.LHS;
1722 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001723
Ken Dyck199c3d62010-01-11 17:06:35 +00001724 CharUnits ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001725
Chris Lattnere5ed1512009-02-11 07:21:43 +00001726 // Handle GCC extension for pointer arithmetic on void* and function pointer
1727 // types.
1728 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001729 ElementSize = CharUnits::One();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001730 } else {
Ken Dyck199c3d62010-01-11 17:06:35 +00001731 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001732 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001733
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001734 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1735 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1736 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1737 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001738
Chris Lattnere5ed1512009-02-11 07:21:43 +00001739 // Optimize out the shift for element size of 1.
Ken Dyck199c3d62010-01-11 17:06:35 +00001740 if (ElementSize.isOne())
Chris Lattnere5ed1512009-02-11 07:21:43 +00001741 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001742
1743 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001744 // pointer difference in C is only defined in the case where both operands
1745 // are pointing to elements of an array.
Ken Dyck199c3d62010-01-11 17:06:35 +00001746 Value *BytesPerElt =
1747 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
Dan Gohmandf110942009-08-11 22:40:09 +00001748 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001749 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001750}
1751
1752Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1753 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1754 // RHS to the same size as the LHS.
1755 Value *RHS = Ops.RHS;
1756 if (Ops.LHS->getType() != RHS->getType())
1757 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001758
Mike Stumpbe07f602009-12-14 21:58:14 +00001759 if (CGF.CatchUndefined
1760 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1761 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1762 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1763 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1764 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00001765 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00001766 CGF.EmitBlock(Cont);
1767 }
1768
Chris Lattner7f02f722007-08-24 05:35:26 +00001769 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1770}
1771
1772Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1773 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1774 // RHS to the same size as the LHS.
1775 Value *RHS = Ops.RHS;
1776 if (Ops.LHS->getType() != RHS->getType())
1777 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001778
Mike Stumpbe07f602009-12-14 21:58:14 +00001779 if (CGF.CatchUndefined
1780 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1781 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1782 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1783 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1784 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00001785 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00001786 CGF.EmitBlock(Cont);
1787 }
1788
Douglas Gregorf6094622010-07-23 15:58:24 +00001789 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001790 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1791 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1792}
1793
1794Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1795 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001796 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001797 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001798 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00001799 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00001800 assert(E->getOpcode() == BO_EQ ||
1801 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00001802 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
1803 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00001804 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00001805 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00001806 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001807 Value *LHS = Visit(E->getLHS());
1808 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001809
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001810 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001811 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001812 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00001813 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001814 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001815 LHS, RHS, "cmp");
1816 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001817 // Unsigned integers and pointers.
1818 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001819 LHS, RHS, "cmp");
1820 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001821
1822 // If this is a vector comparison, sign extend the result to the appropriate
1823 // vector integer type and return it (don't convert to bool).
1824 if (LHSTy->isVectorType())
1825 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001826
Chris Lattner7f02f722007-08-24 05:35:26 +00001827 } else {
1828 // Complex Comparison: can only be an equality comparison.
1829 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1830 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001831
John McCall183700f2009-09-21 23:43:11 +00001832 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001833
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001834 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001835 if (CETy->isRealFloatingType()) {
1836 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1837 LHS.first, RHS.first, "cmp.r");
1838 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1839 LHS.second, RHS.second, "cmp.i");
1840 } else {
1841 // Complex comparisons can only be equality comparisons. As such, signed
1842 // and unsigned opcodes are the same.
1843 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1844 LHS.first, RHS.first, "cmp.r");
1845 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1846 LHS.second, RHS.second, "cmp.i");
1847 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001848
John McCall2de56d12010-08-25 11:45:40 +00001849 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001850 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1851 } else {
John McCall2de56d12010-08-25 11:45:40 +00001852 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00001853 "Complex comparison other than == or != ?");
1854 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1855 }
1856 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001857
1858 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001859}
1860
1861Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001862 bool Ignore = TestAndClearIgnoreResultAssign();
1863
1864 // __block variables need to have the rhs evaluated first, plus this should
1865 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001866 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00001867 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001868
Daniel Dunbared3849b2008-11-19 09:36:46 +00001869 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001870 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1871 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001872 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001873 if (LHS.isBitField())
1874 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1875 &RHS);
1876 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001877 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001878
1879 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001880 if (Ignore)
1881 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001882
1883 // Objective-C property assignment never reloads the value following a store.
1884 if (LHS.isPropertyRef() || LHS.isKVCRef())
1885 return RHS;
1886
1887 // If the lvalue is non-volatile, return the computed value of the assignment.
1888 if (!LHS.isVolatileQualified())
1889 return RHS;
1890
1891 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001892 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001893}
1894
1895Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001896 const llvm::Type *ResTy = ConvertType(E->getType());
1897
Chris Lattner20eb09d2008-11-12 08:26:50 +00001898 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1899 // If we have 1 && X, just emit X without inserting the control flow.
1900 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1901 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001902 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001903 // ZExt result to int or bool.
1904 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001905 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001906
Chris Lattner7804bcb2009-10-17 04:24:20 +00001907 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001908 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001909 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001910 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001911
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001912 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1913 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001914
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001915 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1916 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1917
1918 // Any edges into the ContBlock are now from an (indeterminate number of)
1919 // edges from this first condition. All of these values will be false. Start
1920 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001921 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1922 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001923 PN->reserveOperandSpace(2); // Normal case, two inputs.
1924 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1925 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001926 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001927
Anders Carlsson72119a82010-02-04 17:18:07 +00001928 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001929 CGF.EmitBlock(RHSBlock);
1930 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson72119a82010-02-04 17:18:07 +00001931 CGF.EndConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001932
Chris Lattner7f02f722007-08-24 05:35:26 +00001933 // Reaquire the RHS block, as there may be subblocks inserted.
1934 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001935
1936 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1937 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001938 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001939 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001940
Chris Lattner7f02f722007-08-24 05:35:26 +00001941 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001942 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001943}
1944
1945Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001946 const llvm::Type *ResTy = ConvertType(E->getType());
1947
Chris Lattner20eb09d2008-11-12 08:26:50 +00001948 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1949 // If we have 0 || X, just emit X without inserting the control flow.
1950 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1951 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001952 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001953 // ZExt result to int or bool.
1954 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001955 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001956
Chris Lattner7804bcb2009-10-17 04:24:20 +00001957 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001958 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001959 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001960 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001961
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001962 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1963 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001964
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001965 // Branch on the LHS first. If it is true, go to the success (cont) block.
1966 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1967
1968 // Any edges into the ContBlock are now from an (indeterminate number of)
1969 // edges from this first condition. All of these values will be true. Start
1970 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001971 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1972 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001973 PN->reserveOperandSpace(2); // Normal case, two inputs.
1974 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1975 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001976 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001977
Anders Carlsson72119a82010-02-04 17:18:07 +00001978 CGF.BeginConditionalBranch();
Anders Carlsson33da07d2009-06-04 02:53:13 +00001979
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001980 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001981 CGF.EmitBlock(RHSBlock);
1982 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001983
Anders Carlsson72119a82010-02-04 17:18:07 +00001984 CGF.EndConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001985
Chris Lattner7f02f722007-08-24 05:35:26 +00001986 // Reaquire the RHS block, as there may be subblocks inserted.
1987 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001988
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001989 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1990 // into the phi node for the edge with the value of RHSCond.
1991 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001992 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001993
Chris Lattner7f02f722007-08-24 05:35:26 +00001994 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001995 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001996}
1997
1998Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1999 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002000 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002001 return Visit(E->getRHS());
2002}
2003
2004//===----------------------------------------------------------------------===//
2005// Other Operators
2006//===----------------------------------------------------------------------===//
2007
Chris Lattner9802a512008-11-12 08:55:54 +00002008/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2009/// expression is cheap enough and side-effect-free enough to evaluate
2010/// unconditionally instead of conditionally. This is used to convert control
2011/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002012static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2013 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00002014 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002015 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002016
Chris Lattner9802a512008-11-12 08:55:54 +00002017 // TODO: Allow anything we can constant fold to an integer or fp constant.
2018 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2019 isa<FloatingLiteral>(E))
2020 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002021
Chris Lattner9802a512008-11-12 08:55:54 +00002022 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2023 // X and Y are local variables.
2024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2025 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002026 if (VD->hasLocalStorage() && !(CGF.getContext()
2027 .getCanonicalType(VD->getType())
2028 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002029 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002030
Chris Lattner9802a512008-11-12 08:55:54 +00002031 return false;
2032}
2033
2034
Chris Lattner7f02f722007-08-24 05:35:26 +00002035Value *ScalarExprEmitter::
2036VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002037 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00002038 // If the condition constant folds and can be elided, try to avoid emitting
2039 // the condition and the dead arm.
2040 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00002041 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00002042 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00002043 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002044
Chris Lattner31a09842008-11-12 08:04:58 +00002045 // If the dead side doesn't have labels we need, and if the Live side isn't
2046 // the gnu missing ?: extension (which we could handle, but don't bother
2047 // to), just emit the Live part.
2048 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
2049 Live) // Live part isn't missing.
2050 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002051 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002052
2053
Chris Lattner9802a512008-11-12 08:55:54 +00002054 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2055 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002056 // safe to evaluate the LHS and RHS unconditionally.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002057 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2058 CGF) &&
2059 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
Chris Lattner9802a512008-11-12 08:55:54 +00002060 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2061 llvm::Value *LHS = Visit(E->getLHS());
2062 llvm::Value *RHS = Visit(E->getRHS());
2063 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2064 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002065
Douglas Gregor5d743fa2010-08-23 14:50:27 +00002066 if (!E->getLHS() && CGF.getContext().getLangOptions().CPlusPlus) {
2067 // Does not support GNU missing condition extension in C++ yet (see #7726)
2068 CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
2069 return llvm::UndefValue::get(ConvertType(E->getType()));
2070 }
2071
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002072 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2073 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002074 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00002075 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00002076
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002077 // If we don't have the GNU missing condition extension, emit a branch on bool
2078 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00002079 if (E->getLHS()) {
2080 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2081 // the branch on bool.
2082 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2083 } else {
2084 // Otherwise, for the ?: extension, evaluate the conditional and then
2085 // convert it to bool the hard way. We do this explicitly because we need
2086 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00002087 CondVal = CGF.EmitScalarExpr(E->getCond());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002088
Chris Lattner12d152f2009-02-13 23:35:32 +00002089 // In some cases, EmitScalarConversion will delete the "CondVal" expression
2090 // if there are no extra uses (an optimization). Inhibit this by making an
2091 // extra dead use, because we're going to add a use of CondVal later. We
2092 // don't use the builder for this, because we don't want it to get optimized
2093 // away. This leaves dead code, but the ?: extension isn't common.
2094 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2095 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002096
Chris Lattner035cf422008-11-12 08:08:13 +00002097 Value *CondBoolVal =
2098 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2099 CGF.getContext().BoolTy);
2100 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00002101 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002102
Anders Carlsson72119a82010-02-04 17:18:07 +00002103 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002104 CGF.EmitBlock(LHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002105
Chris Lattner7f02f722007-08-24 05:35:26 +00002106 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00002107 Value *LHS;
2108 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00002109 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00002110 else // Perform promotions, to handle cases like "short ?: int"
2111 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002112
Anders Carlsson72119a82010-02-04 17:18:07 +00002113 CGF.EndConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002114 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00002115 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002116
Anders Carlsson72119a82010-02-04 17:18:07 +00002117 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002118 CGF.EmitBlock(RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002119
Eli Friedman856226c2008-05-16 20:38:39 +00002120 Value *RHS = Visit(E->getRHS());
Anders Carlsson72119a82010-02-04 17:18:07 +00002121 CGF.EndConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002122 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00002123 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002124
Chris Lattner7f02f722007-08-24 05:35:26 +00002125 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002126
Eli Friedman48daf592009-12-07 20:25:53 +00002127 // If the LHS or RHS is a throw expression, it will be legitimately null.
2128 if (!LHS)
2129 return RHS;
2130 if (!RHS)
2131 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002132
Chris Lattner7f02f722007-08-24 05:35:26 +00002133 // Create a PHI node for the real part.
2134 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2135 PN->reserveOperandSpace(2);
2136 PN->addIncoming(LHS, LHSBlock);
2137 PN->addIncoming(RHS, RHSBlock);
2138 return PN;
2139}
2140
2141Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002142 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002143}
2144
Chris Lattner2202bce2007-11-30 17:56:23 +00002145Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002146 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002147 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2148
2149 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002150 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002151 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2152
Mike Stump7f79f9b2009-05-29 15:46:01 +00002153 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002154 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002155}
2156
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002157Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00002158 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002159}
2160
Chris Lattner7f02f722007-08-24 05:35:26 +00002161//===----------------------------------------------------------------------===//
2162// Entry Point into this File
2163//===----------------------------------------------------------------------===//
2164
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002165/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2166/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002167Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002168 assert(E && !hasAggregateLLVMType(E->getType()) &&
2169 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002170
Mike Stump7f79f9b2009-05-29 15:46:01 +00002171 return ScalarExprEmitter(*this, IgnoreResultAssign)
2172 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00002173}
Chris Lattner3707b252007-08-26 06:48:56 +00002174
2175/// EmitScalarConversion - Emit a conversion from the specified type to the
2176/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002177Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2178 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002179 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2180 "Invalid scalar expression to emit");
2181 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2182}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002183
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002184/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2185/// type to the specified destination type, where the destination type is an
2186/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002187Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2188 QualType SrcTy,
2189 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002190 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002191 "Invalid complex -> scalar conversion");
2192 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2193 DstTy);
2194}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002195
Chris Lattner8c11a652010-06-26 22:09:34 +00002196
2197llvm::Value *CodeGenFunction::
2198EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2199 bool isInc, bool isPre) {
2200 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2201}
2202
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002203LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2204 llvm::Value *V;
2205 // object->isa or (*object).isa
2206 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002207 // build Class* type
2208 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002209
2210 Expr *BaseExpr = E->getBase();
2211 if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) {
2212 V = CreateTempAlloca(ClassPtrTy, "resval");
2213 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2214 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002215 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2216 MakeAddrLValue(V, E->getType()), E->getType());
2217 } else {
2218 if (E->isArrow())
2219 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2220 else
2221 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002222 }
2223
2224 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002225 ClassPtrTy = ClassPtrTy->getPointerTo();
2226 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002227 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002228}
2229
Douglas Gregor6a03e342010-04-23 04:16:32 +00002230
2231LValue CodeGenFunction::EmitCompoundAssignOperatorLValue(
2232 const CompoundAssignOperator *E) {
2233 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002234 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002235 switch (E->getOpcode()) {
2236#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002237 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002238 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002239 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002240 COMPOUND_OP(Mul);
2241 COMPOUND_OP(Div);
2242 COMPOUND_OP(Rem);
2243 COMPOUND_OP(Add);
2244 COMPOUND_OP(Sub);
2245 COMPOUND_OP(Shl);
2246 COMPOUND_OP(Shr);
2247 COMPOUND_OP(And);
2248 COMPOUND_OP(Xor);
2249 COMPOUND_OP(Or);
2250#undef COMPOUND_OP
2251
John McCall2de56d12010-08-25 11:45:40 +00002252 case BO_PtrMemD:
2253 case BO_PtrMemI:
2254 case BO_Mul:
2255 case BO_Div:
2256 case BO_Rem:
2257 case BO_Add:
2258 case BO_Sub:
2259 case BO_Shl:
2260 case BO_Shr:
2261 case BO_LT:
2262 case BO_GT:
2263 case BO_LE:
2264 case BO_GE:
2265 case BO_EQ:
2266 case BO_NE:
2267 case BO_And:
2268 case BO_Xor:
2269 case BO_Or:
2270 case BO_LAnd:
2271 case BO_LOr:
2272 case BO_Assign:
2273 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002274 assert(false && "Not valid compound assignment operators");
2275 break;
2276 }
2277
2278 llvm_unreachable("Unhandled compound assignment operator");
2279}