blob: 99f3f0d32310a34c0b343122fc1f20b3e10677f4 [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
Devang Patel78ba3d42010-10-04 21:46:04 +000014#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Devang Patel78ba3d42010-10-04 21:46:04 +000019#include "CGDebugInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Constants.h"
26#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000028#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000029#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000030#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000031#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000049};
50
John McCall404cd162010-11-13 01:35:44 +000051static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
56}
57
Benjamin Kramer85b45212009-11-28 19:45:26 +000058class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000059 : public StmtVisitor<ScalarExprEmitter, Value*> {
60 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000061 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000062 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000063 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000064public:
65
Mike Stump7f79f9b2009-05-29 15:46:01 +000066 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000067 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000068 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000069 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Utilities
73 //===--------------------------------------------------------------------===//
74
Mike Stump7f79f9b2009-05-29 15:46:01 +000075 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000076 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
78 return I;
79 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000080
Chris Lattner7f02f722007-08-24 05:35:26 +000081 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000084
85 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000086 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000087 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000088
Chris Lattner7f02f722007-08-24 05:35:26 +000089 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
Mike Stumpb14e62d2009-12-16 02:57:00 +000093 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +000094 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095
Chris Lattner9abc84e2007-08-26 16:42:57 +000096 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000097 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000098 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000099
Chris Lattner3707b252007-08-26 06:48:56 +0000100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
103
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000109
Anders Carlssona40a9f32010-05-22 17:45:10 +0000110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
112
John McCalldaa8e4e2010-11-15 09:13:47 +0000113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
118 }
119
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
125 }
126
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
137 if (ZI->use_empty())
138 ZI->eraseFromParent();
139 return Result;
140 }
141 }
142
143 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(V->getType());
144 Value *Zero = llvm::ConstantInt::get(Ty, 0);
145 return Builder.CreateICmpNE(V, Zero, "tobool");
146 }
147
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 //===--------------------------------------------------------------------===//
149 // Visitor Methods
150 //===--------------------------------------------------------------------===//
151
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000152 Value *Visit(Expr *E) {
153 llvm::DenseMap<const Expr *, llvm::Value *>::iterator I =
154 CGF.ConditionalSaveExprs.find(E);
155 if (I != CGF.ConditionalSaveExprs.end())
156 return I->second;
157
158 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
159 }
160
Chris Lattner7f02f722007-08-24 05:35:26 +0000161 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000162 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000163 assert(0 && "Stmt can't have complex result type!");
164 return 0;
165 }
166 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000167
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000168 Value *VisitParenExpr(ParenExpr *PE) {
169 return Visit(PE->getSubExpr());
170 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000171
172 // Leaves.
173 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000174 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000175 }
176 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000177 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000178 }
179 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000180 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000181 }
Nate Begemane7579b52007-11-15 05:40:03 +0000182 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000183 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000184 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000185 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000186 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000187 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000188 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000189 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000190 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000191 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +0000192 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000193 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000194 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
195 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000196 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000197
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000198 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
199 return llvm::ConstantInt::get(ConvertType(E->getType()),
200 E->getPackLength());
201 }
John McCalle996ffd2011-02-16 08:02:54 +0000202
203 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
204 if (E->isGLValue()) return EmitLoadOfLValue(E);
205
206 // Otherwise, assume the mapping is the scalar directly.
207 return CGF.getOpaqueValueMapping(E);
208 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000209
Chris Lattner7f02f722007-08-24 05:35:26 +0000210 // l-values.
211 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000212 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000213 if (!E->Evaluate(Result, CGF.getContext()))
214 return EmitLoadOfLValue(E);
215
216 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
217
218 llvm::Constant *C;
219 if (Result.Val.isInt()) {
220 C = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
221 } else if (Result.Val.isFloat()) {
222 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
223 } else {
224 return EmitLoadOfLValue(E);
Eli Friedman28665272009-11-26 03:22:21 +0000225 }
John McCall189d6ef2010-10-09 01:34:31 +0000226
227 // Make sure we emit a debug reference to the global variable.
228 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
229 if (!CGF.getContext().DeclMustBeEmitted(VD))
230 CGF.EmitDeclRefExprDbgValue(E, C);
231 } else if (isa<EnumConstantDecl>(E->getDecl())) {
232 CGF.EmitDeclRefExprDbgValue(E, C);
233 }
234
235 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000236 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000237 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
238 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000239 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000240 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
241 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000242 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000243 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000244 return EmitLoadOfLValue(E);
245 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000246 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000247 assert(E->getObjectKind() == OK_Ordinary &&
248 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000249 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000250 }
251 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
252 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000253 }
254
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000255 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000256 LValue LV = CGF.EmitObjCIsaExpr(E);
257 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000258 return V;
259 }
260
Chris Lattner7f02f722007-08-24 05:35:26 +0000261 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000262 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000263 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000264 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000265 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
266 return EmitLoadOfLValue(E);
267 }
Devang Patel35634f52007-10-24 17:18:43 +0000268
Nate Begeman0533b302009-10-18 20:10:40 +0000269 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000270
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000271 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000272 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000273 }
Eli Friedmand8889622009-11-27 04:41:50 +0000274 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000275 // Make sure to evaluate VLA bounds now so that we have them for later.
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000276 if (E->getType()->isVariablyModifiedType())
277 CGF.EmitVLASize(E->getType());
Eli Friedmanc62aad82009-04-20 03:54:15 +0000278
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000279 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000280 }
Eli Friedmand8889622009-11-27 04:41:50 +0000281 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000282
283 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000284 if (E->getCallReturnType()->isReferenceType())
285 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000286
Chris Lattner9b655512007-08-31 22:49:20 +0000287 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000288 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000289
Chris Lattner33793202007-08-31 22:09:40 +0000290 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000291
Mike Stumpa99038c2009-02-28 09:07:16 +0000292 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000293
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000296 LValue LV = EmitLValue(E->getSubExpr());
297 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000298 }
299 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000300 LValue LV = EmitLValue(E->getSubExpr());
301 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000302 }
303 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000304 LValue LV = EmitLValue(E->getSubExpr());
305 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 }
307 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000308 LValue LV = EmitLValue(E->getSubExpr());
309 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000310 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000311
Anton Yartsev683564a2011-02-07 02:17:30 +0000312 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
313 llvm::Value *InVal,
314 llvm::Value *NextVal,
315 bool IsInc);
316
Chris Lattner8c11a652010-06-26 22:09:34 +0000317 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
318 bool isInc, bool isPre);
319
320
Chris Lattner7f02f722007-08-24 05:35:26 +0000321 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000322 if (isa<MemberPointerType>(E->getType())) // never sugared
323 return CGF.CGM.getMemberPointerConstant(E);
324
Chris Lattner7f02f722007-08-24 05:35:26 +0000325 return EmitLValue(E->getSubExpr()).getAddress();
326 }
John McCallfd569002010-12-04 12:43:24 +0000327 Value *VisitUnaryDeref(const UnaryOperator *E) {
328 if (E->getType()->isVoidType())
329 return Visit(E->getSubExpr()); // the actual value should be unused
330 return EmitLoadOfLValue(E);
331 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000332 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000333 // This differs from gcc, though, most likely due to a bug in gcc.
334 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000335 return Visit(E->getSubExpr());
336 }
337 Value *VisitUnaryMinus (const UnaryOperator *E);
338 Value *VisitUnaryNot (const UnaryOperator *E);
339 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000340 Value *VisitUnaryReal (const UnaryOperator *E);
341 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000342 Value *VisitUnaryExtension(const UnaryOperator *E) {
343 return Visit(E->getSubExpr());
344 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000345
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000346 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000347 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
348 return Visit(DAE->getExpr());
349 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000350 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
351 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000352 }
353
John McCall4765fa02010-12-06 08:20:24 +0000354 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
355 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000356 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000357 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
358 return CGF.EmitCXXNewExpr(E);
359 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000360 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
361 CGF.EmitCXXDeleteExpr(E);
362 return 0;
363 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000364 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000365 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000366 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000367
Francois Pichet6ad6f282010-12-07 00:08:36 +0000368 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000369 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000370 }
371
Douglas Gregora71d8192009-09-04 17:36:40 +0000372 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
373 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000374 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000375 // operator (), and the result of such a call has type void. The only
376 // effect is the evaluation of the postfix-expression before the dot or
377 // arrow.
378 CGF.EmitScalarExpr(E->getBase());
379 return 0;
380 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000381
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000382 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000383 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000384 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000385
386 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
387 CGF.EmitCXXThrowExpr(E);
388 return 0;
389 }
390
Sebastian Redl98294de2010-09-10 21:04:00 +0000391 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
392 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
393 }
394
Chris Lattner7f02f722007-08-24 05:35:26 +0000395 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000396 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000397 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000398 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
399 case LangOptions::SOB_Undefined:
400 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
401 case LangOptions::SOB_Defined:
402 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
403 case LangOptions::SOB_Trapping:
404 return EmitOverflowCheckedBinOp(Ops);
405 }
406 }
407
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000408 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000409 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000410 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
411 }
Chris Lattner80230302010-09-11 21:47:09 +0000412 bool isTrapvOverflowBehavior() {
413 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
414 == LangOptions::SOB_Trapping;
415 }
Mike Stump2add4732009-04-01 20:28:16 +0000416 /// Create a binary op that checks for overflow.
417 /// Currently only supports +, - and *.
418 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000419 // Emit the overflow BB when -ftrapv option is activated.
420 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
421 Builder.SetInsertPoint(overflowBB);
422 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
423 Builder.CreateCall(Trap);
424 Builder.CreateUnreachable();
425 }
426 // Check for undefined division and modulus behaviors.
427 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
428 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000429 Value *EmitDiv(const BinOpInfo &Ops);
430 Value *EmitRem(const BinOpInfo &Ops);
431 Value *EmitAdd(const BinOpInfo &Ops);
432 Value *EmitSub(const BinOpInfo &Ops);
433 Value *EmitShl(const BinOpInfo &Ops);
434 Value *EmitShr(const BinOpInfo &Ops);
435 Value *EmitAnd(const BinOpInfo &Ops) {
436 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
437 }
438 Value *EmitXor(const BinOpInfo &Ops) {
439 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
440 }
441 Value *EmitOr (const BinOpInfo &Ops) {
442 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
443 }
444
Chris Lattner1f1ded92007-08-24 21:00:35 +0000445 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000446 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
447 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000448 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000449
Chris Lattner3ccf7742007-08-26 21:41:21 +0000450 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000451 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
452
453 // Binary operators and binary compound assignment operators.
454#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000455 Value *VisitBin ## OP(const BinaryOperator *E) { \
456 return Emit ## OP(EmitBinOps(E)); \
457 } \
458 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
459 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000460 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000461 HANDLEBINOP(Mul)
462 HANDLEBINOP(Div)
463 HANDLEBINOP(Rem)
464 HANDLEBINOP(Add)
465 HANDLEBINOP(Sub)
466 HANDLEBINOP(Shl)
467 HANDLEBINOP(Shr)
468 HANDLEBINOP(And)
469 HANDLEBINOP(Xor)
470 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000471#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000472
Chris Lattner7f02f722007-08-24 05:35:26 +0000473 // Comparisons.
474 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
475 unsigned SICmpOpc, unsigned FCmpOpc);
476#define VISITCOMP(CODE, UI, SI, FP) \
477 Value *VisitBin##CODE(const BinaryOperator *E) { \
478 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
479 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000480 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
481 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
482 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
483 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
484 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
485 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000486#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000487
Chris Lattner7f02f722007-08-24 05:35:26 +0000488 Value *VisitBinAssign (const BinaryOperator *E);
489
490 Value *VisitBinLAnd (const BinaryOperator *E);
491 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000492 Value *VisitBinComma (const BinaryOperator *E);
493
Eli Friedman25b825d2009-11-18 09:41:26 +0000494 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
495 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
496
Chris Lattner7f02f722007-08-24 05:35:26 +0000497 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000498 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000499 Value *VisitConditionalOperator(const ConditionalOperator *CO);
500 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000501 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000502 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
503 return CGF.EmitObjCStringLiteral(E);
504 }
505};
506} // end anonymous namespace.
507
508//===----------------------------------------------------------------------===//
509// Utilities
510//===----------------------------------------------------------------------===//
511
Chris Lattner9abc84e2007-08-26 16:42:57 +0000512/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000513/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000514Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000515 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000516
John McCalldaa8e4e2010-11-15 09:13:47 +0000517 if (SrcType->isRealFloatingType())
518 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000519
John McCall0bab0cd2010-08-23 01:21:21 +0000520 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
521 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000522
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000523 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000524 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000525
John McCalldaa8e4e2010-11-15 09:13:47 +0000526 if (isa<llvm::IntegerType>(Src->getType()))
527 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000528
John McCalldaa8e4e2010-11-15 09:13:47 +0000529 assert(isa<llvm::PointerType>(Src->getType()));
530 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000531}
532
Chris Lattner3707b252007-08-26 06:48:56 +0000533/// EmitScalarConversion - Emit a conversion from the specified type to the
534/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000535Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
536 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000537 SrcType = CGF.getContext().getCanonicalType(SrcType);
538 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000539 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000540
Chris Lattnercf289082007-08-26 07:21:11 +0000541 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000542
Chris Lattner3707b252007-08-26 06:48:56 +0000543 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000544 if (DstType->isBooleanType())
545 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000546
Chris Lattner3707b252007-08-26 06:48:56 +0000547 const llvm::Type *DstTy = ConvertType(DstType);
548
549 // Ignore conversions like int -> uint.
550 if (Src->getType() == DstTy)
551 return Src;
552
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000553 // Handle pointer conversions next: pointers can only be converted to/from
554 // other pointers and integers. Check for pointer types in terms of LLVM, as
555 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000556 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000557 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000558 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000559 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000560
Chris Lattner3707b252007-08-26 06:48:56 +0000561 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000562 // First, convert to the correct width so that we control the kind of
563 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000564 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000565 bool InputSigned = SrcType->isSignedIntegerType();
566 llvm::Value* IntResult =
567 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
568 // Then, cast to pointer.
569 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000570 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000571
Daniel Dunbar270cc662008-08-25 09:51:32 +0000572 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000573 // Must be an ptr to int cast.
574 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000575 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000576 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000577
Nate Begeman213541a2008-04-18 23:10:10 +0000578 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000579 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000580 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000581 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000582 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
583
584 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000585 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000586 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000587 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
588
589 // Splat the element across to all elements
590 llvm::SmallVector<llvm::Constant*, 16> Args;
591 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000592 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner77b89b82010-06-27 07:15:29 +0000593 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000594
Chris Lattnerfb018d12011-02-15 00:14:06 +0000595 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000596 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
597 return Yay;
598 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000599
Chris Lattner3b1ae002008-02-02 04:51:41 +0000600 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000601 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000602 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000603 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000604
Chris Lattner3707b252007-08-26 06:48:56 +0000605 // Finally, we have the arithmetic types: real int/float.
606 if (isa<llvm::IntegerType>(Src->getType())) {
607 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000608 if (isa<llvm::IntegerType>(DstTy))
609 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
610 else if (InputSigned)
611 return Builder.CreateSIToFP(Src, DstTy, "conv");
612 else
613 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000614 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000615
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000616 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000617 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000618 if (DstType->isSignedIntegerType())
619 return Builder.CreateFPToSI(Src, DstTy, "conv");
620 else
621 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000622 }
623
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000624 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000625 if (DstTy->getTypeID() < Src->getType()->getTypeID())
626 return Builder.CreateFPTrunc(Src, DstTy, "conv");
627 else
628 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000629}
630
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000631/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
632/// type to the specified destination type, where the destination type is an
633/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000634Value *ScalarExprEmitter::
635EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
636 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000637 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000638 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000639
Chris Lattnered70f0a2007-08-26 16:52:28 +0000640 // Handle conversions to bool first, they are special: comparisons against 0.
641 if (DstTy->isBooleanType()) {
642 // Complex != 0 -> (Real != 0) | (Imag != 0)
643 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
644 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
645 return Builder.CreateOr(Src.first, Src.second, "tobool");
646 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000647
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000648 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
649 // the imaginary part of the complex value is discarded and the value of the
650 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000651 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000652 return EmitScalarConversion(Src.first, SrcTy, DstTy);
653}
654
Anders Carlssona40a9f32010-05-22 17:45:10 +0000655Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000656 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
657 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
658
659 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000660}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000661
Chris Lattner7f02f722007-08-24 05:35:26 +0000662//===----------------------------------------------------------------------===//
663// Visitor Methods
664//===----------------------------------------------------------------------===//
665
666Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000667 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000668 if (E->getType()->isVoidType())
669 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000670 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000671}
672
Eli Friedmand38617c2008-05-14 19:38:39 +0000673Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000674 // Vector Mask Case
675 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000676 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000677 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
678 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
679 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000680
Nate Begeman37b6a572010-06-08 00:16:34 +0000681 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
682 unsigned LHSElts = LTy->getNumElements();
683
684 if (E->getNumSubExprs() == 3) {
685 Mask = CGF.EmitScalarExpr(E->getExpr(2));
686
687 // Shuffle LHS & RHS into one input vector.
688 llvm::SmallVector<llvm::Constant*, 32> concat;
689 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000690 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
691 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000692 }
693
Chris Lattnerfb018d12011-02-15 00:14:06 +0000694 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000695 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
696 LHSElts *= 2;
697 } else {
698 Mask = RHS;
699 }
700
701 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
702 llvm::Constant* EltMask;
703
704 // Treat vec3 like vec4.
705 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
706 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
707 (1 << llvm::Log2_32(LHSElts+2))-1);
708 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
709 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
710 (1 << llvm::Log2_32(LHSElts+1))-1);
711 else
712 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
713 (1 << llvm::Log2_32(LHSElts))-1);
714
715 // Mask off the high bits of each shuffle index.
716 llvm::SmallVector<llvm::Constant *, 32> MaskV;
717 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
718 MaskV.push_back(EltMask);
719
Chris Lattnerfb018d12011-02-15 00:14:06 +0000720 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000721 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
722
723 // newv = undef
724 // mask = mask & maskbits
725 // for each elt
726 // n = extract mask i
727 // x = extract val n
728 // newv = insert newv, x, i
729 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
730 MTy->getNumElements());
731 Value* NewV = llvm::UndefValue::get(RTy);
732 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000733 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000734 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000735 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000736
737 // Handle vec3 special since the index will be off by one for the RHS.
738 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
739 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000740 cmpIndx = Builder.CreateICmpUGT(Indx,
741 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000742 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000743 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000744 "shuf_idx_adj");
745 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
746 }
747 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
748 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
749 }
750 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000751 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000752
Eli Friedmand38617c2008-05-14 19:38:39 +0000753 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
754 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000755
756 // Handle vec3 special since the index will be off by one for the RHS.
757 llvm::SmallVector<llvm::Constant*, 32> indices;
758 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
759 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
760 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
761 if (VTy->getNumElements() == 3) {
762 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
763 uint64_t cVal = CI->getZExtValue();
764 if (cVal > 3) {
765 C = llvm::ConstantInt::get(C->getType(), cVal-1);
766 }
767 }
768 }
769 indices.push_back(C);
770 }
771
Chris Lattnerfb018d12011-02-15 00:14:06 +0000772 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000773 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
774}
Eli Friedman28665272009-11-26 03:22:21 +0000775Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
776 Expr::EvalResult Result;
777 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
778 if (E->isArrow())
779 CGF.EmitScalarExpr(E->getBase());
780 else
781 EmitLValue(E->getBase());
782 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
783 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000784
785 // Emit debug info for aggregate now, if it was delayed to reduce
786 // debug info size.
787 CGDebugInfo *DI = CGF.getDebugInfo();
788 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
789 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
790 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000791 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000792 DI->getOrCreateRecordType(PTy->getPointeeType(),
793 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000794 }
Eli Friedman28665272009-11-26 03:22:21 +0000795 return EmitLoadOfLValue(E);
796}
Eli Friedmand38617c2008-05-14 19:38:39 +0000797
Chris Lattner7f02f722007-08-24 05:35:26 +0000798Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000799 TestAndClearIgnoreResultAssign();
800
Chris Lattner7f02f722007-08-24 05:35:26 +0000801 // Emit subscript expressions in rvalue context's. For most cases, this just
802 // loads the lvalue formed by the subscript expr. However, we have to be
803 // careful, because the base of a vector subscript is occasionally an rvalue,
804 // so we can't get it as an lvalue.
805 if (!E->getBase()->getType()->isVectorType())
806 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000807
Chris Lattner7f02f722007-08-24 05:35:26 +0000808 // Handle the vector case. The base must be a vector, the index must be an
809 // integer value.
810 Value *Base = Visit(E->getBase());
811 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000812 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000813 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000814 return Builder.CreateExtractElement(Base, Idx, "vecext");
815}
816
Nate Begeman0533b302009-10-18 20:10:40 +0000817static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
818 unsigned Off, const llvm::Type *I32Ty) {
819 int MV = SVI->getMaskValue(Idx);
820 if (MV == -1)
821 return llvm::UndefValue::get(I32Ty);
822 return llvm::ConstantInt::get(I32Ty, Off+MV);
823}
824
825Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
826 bool Ignore = TestAndClearIgnoreResultAssign();
827 (void)Ignore;
828 assert (Ignore == false && "init list ignored");
829 unsigned NumInitElements = E->getNumInits();
830
831 if (E->hadArrayRangeDesignator())
832 CGF.ErrorUnsupported(E, "GNU array range designator extension");
833
834 const llvm::VectorType *VType =
835 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
836
837 // We have a scalar in braces. Just use the first element.
838 if (!VType)
839 return Visit(E->getInit(0));
840
841 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000842
843 // Loop over initializers collecting the Value for each, and remembering
844 // whether the source was swizzle (ExtVectorElementExpr). This will allow
845 // us to fold the shuffle for the swizzle into the shuffle for the vector
846 // initializer, since LLVM optimizers generally do not want to touch
847 // shuffles.
848 unsigned CurIdx = 0;
849 bool VIsUndefShuffle = false;
850 llvm::Value *V = llvm::UndefValue::get(VType);
851 for (unsigned i = 0; i != NumInitElements; ++i) {
852 Expr *IE = E->getInit(i);
853 Value *Init = Visit(IE);
854 llvm::SmallVector<llvm::Constant*, 16> Args;
855
856 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
857
858 // Handle scalar elements. If the scalar initializer is actually one
859 // element of a different vector of the same width, use shuffle instead of
860 // extract+insert.
861 if (!VVT) {
862 if (isa<ExtVectorElementExpr>(IE)) {
863 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
864
865 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
866 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
867 Value *LHS = 0, *RHS = 0;
868 if (CurIdx == 0) {
869 // insert into undef -> shuffle (src, undef)
870 Args.push_back(C);
871 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000872 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000873
874 LHS = EI->getVectorOperand();
875 RHS = V;
876 VIsUndefShuffle = true;
877 } else if (VIsUndefShuffle) {
878 // insert into undefshuffle && size match -> shuffle (v, src)
879 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
880 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000881 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
882 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000883 ResElts + C->getZExtValue()));
884 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000885 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000886
887 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
888 RHS = EI->getVectorOperand();
889 VIsUndefShuffle = false;
890 }
891 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000892 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000893 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
894 ++CurIdx;
895 continue;
896 }
897 }
898 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000899 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000900 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
901 VIsUndefShuffle = false;
902 ++CurIdx;
903 continue;
904 }
905
906 unsigned InitElts = VVT->getNumElements();
907
908 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
909 // input is the same width as the vector being constructed, generate an
910 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000911 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000912 if (isa<ExtVectorElementExpr>(IE)) {
913 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
914 Value *SVOp = SVI->getOperand(0);
915 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
916
917 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000918 for (unsigned j = 0; j != CurIdx; ++j) {
919 // If the current vector initializer is a shuffle with undef, merge
920 // this shuffle directly into it.
921 if (VIsUndefShuffle) {
922 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000923 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000924 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000925 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000926 }
927 }
928 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000929 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000930 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000931 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000932
933 if (VIsUndefShuffle)
934 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
935
936 Init = SVOp;
937 }
938 }
939
940 // Extend init to result vector length, and then shuffle its contribution
941 // to the vector initializer into V.
942 if (Args.empty()) {
943 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000944 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000945 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000946 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000947 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000948 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000949 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000950
951 Args.clear();
952 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000953 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000954 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000955 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000956 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000957 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000958 }
959
960 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
961 // merging subsequent shuffles into this one.
962 if (CurIdx == 0)
963 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000964 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000965 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
966 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
967 CurIdx += InitElts;
968 }
969
970 // FIXME: evaluate codegen vs. shuffling against constant null vector.
971 // Emit remaining default initializers.
972 const llvm::Type *EltTy = VType->getElementType();
973
974 // Emit remaining default initializers
975 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000976 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000977 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
978 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
979 }
980 return V;
981}
982
Anders Carlssona3697c92009-11-23 17:57:54 +0000983static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
984 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000985
John McCall2de56d12010-08-25 11:45:40 +0000986 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000987 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000988
989 if (isa<CXXThisExpr>(E)) {
990 // We always assume that 'this' is never null.
991 return false;
992 }
993
994 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000995 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000996 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000997 return false;
998 }
999
1000 return true;
1001}
1002
Chris Lattner7f02f722007-08-24 05:35:26 +00001003// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1004// have to handle a more broad range of conversions than explicit casts, as they
1005// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +00001006Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
1007 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001008 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001009 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001010
Mike Stump7f79f9b2009-05-29 15:46:01 +00001011 if (!DestTy->isVoidType())
1012 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001013
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001014 // Since almost all cast kinds apply to scalars, this switch doesn't have
1015 // a default case, so the compiler will warn on a missing case. The cases
1016 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001017 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001018 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1019
John McCall2de56d12010-08-25 11:45:40 +00001020 case CK_LValueBitCast:
1021 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001022 Value *V = EmitLValue(E).getAddress();
1023 V = Builder.CreateBitCast(V,
1024 ConvertType(CGF.getContext().getPointerType(DestTy)));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001025 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
Douglas Gregore39a3892010-07-13 23:17:26 +00001026 }
1027
John McCall2de56d12010-08-25 11:45:40 +00001028 case CK_AnyPointerToObjCPointerCast:
1029 case CK_AnyPointerToBlockPointerCast:
1030 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001031 Value *Src = Visit(const_cast<Expr*>(E));
1032 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1033 }
John McCall2de56d12010-08-25 11:45:40 +00001034 case CK_NoOp:
1035 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001036 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001037
John McCall2de56d12010-08-25 11:45:40 +00001038 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001039 const CXXRecordDecl *DerivedClassDecl =
1040 DestTy->getCXXRecordDeclForPointerType();
1041
Anders Carlssona04efdf2010-04-24 21:23:59 +00001042 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001043 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001044 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001045 }
John McCall2de56d12010-08-25 11:45:40 +00001046 case CK_UncheckedDerivedToBase:
1047 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001048 const RecordType *DerivedClassTy =
1049 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1050 CXXRecordDecl *DerivedClassDecl =
1051 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1052
Anders Carlsson34a2d382010-04-24 21:06:20 +00001053 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001054 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001055 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001056 }
John McCall2de56d12010-08-25 11:45:40 +00001057 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001058 Value *V = Visit(const_cast<Expr*>(E));
1059 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1060 return CGF.EmitDynamicCast(V, DCE);
1061 }
Eli Friedmand8889622009-11-27 04:41:50 +00001062
John McCall2de56d12010-08-25 11:45:40 +00001063 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001064 assert(E->getType()->isArrayType() &&
1065 "Array to pointer decay must have array source type!");
1066
1067 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1068
1069 // Note that VLA pointers are always decayed, so we don't need to do
1070 // anything here.
1071 if (!E->getType()->isVariableArrayType()) {
1072 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1073 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1074 ->getElementType()) &&
1075 "Expected pointer to array");
1076 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1077 }
1078
1079 return V;
1080 }
John McCall2de56d12010-08-25 11:45:40 +00001081 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001082 return EmitLValue(E).getAddress();
1083
John McCall404cd162010-11-13 01:35:44 +00001084 case CK_NullToPointer:
1085 if (MustVisitNullValue(E))
1086 (void) Visit(E);
1087
1088 return llvm::ConstantPointerNull::get(
1089 cast<llvm::PointerType>(ConvertType(DestTy)));
1090
John McCall2de56d12010-08-25 11:45:40 +00001091 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001092 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001093 (void) Visit(E);
1094
John McCall0bab0cd2010-08-23 01:21:21 +00001095 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1096 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1097 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001098
John McCall2de56d12010-08-25 11:45:40 +00001099 case CK_BaseToDerivedMemberPointer:
1100 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001101 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001102
1103 // Note that the AST doesn't distinguish between checked and
1104 // unchecked member pointer conversions, so we always have to
1105 // implement checked conversions here. This is inefficient when
1106 // actual control flow may be required in order to perform the
1107 // check, which it is for data member pointers (but not member
1108 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001109 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001110 }
John McCall0bab0cd2010-08-23 01:21:21 +00001111
John McCall2bb5d002010-11-13 09:02:35 +00001112 case CK_FloatingRealToComplex:
1113 case CK_FloatingComplexCast:
1114 case CK_IntegralRealToComplex:
1115 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001116 case CK_IntegralComplexToFloatingComplex:
1117 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001118 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001119 case CK_ToUnion:
1120 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001121 break;
John McCallf6a16482010-12-04 03:47:34 +00001122
1123 case CK_GetObjCProperty: {
1124 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001125 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001126 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1127 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType());
1128 return RV.getScalarVal();
1129 }
John McCall0ae287a2010-12-01 04:43:34 +00001130
1131 case CK_LValueToRValue:
1132 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001133 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001134 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001135
John McCall2de56d12010-08-25 11:45:40 +00001136 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001137 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001138
Anders Carlsson82debc72009-10-18 18:12:03 +00001139 // First, convert to the correct width so that we control the kind of
1140 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001141 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001142 bool InputSigned = E->getType()->isSignedIntegerType();
1143 llvm::Value* IntResult =
1144 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001145
Anders Carlsson82debc72009-10-18 18:12:03 +00001146 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001147 }
John McCall2de56d12010-08-25 11:45:40 +00001148 case CK_PointerToIntegral: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001149 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001150
1151 // Handle conversion to bool correctly.
1152 if (DestTy->isBooleanType())
Daniel Dunbardb505472010-09-03 02:07:00 +00001153 return EmitScalarConversion(Src, E->getType(), DestTy);
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001154
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001155 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1156 }
John McCall2de56d12010-08-25 11:45:40 +00001157 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001158 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001159 return 0;
1160 }
John McCall2de56d12010-08-25 11:45:40 +00001161 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001162 const llvm::Type *DstTy = ConvertType(DestTy);
1163 Value *Elt = Visit(const_cast<Expr*>(E));
1164
1165 // Insert the element in element zero of an undef vector
1166 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001167 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001168 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1169
1170 // Splat the element across to all elements
1171 llvm::SmallVector<llvm::Constant*, 16> Args;
1172 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
John McCalldaa8e4e2010-11-15 09:13:47 +00001173 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001174 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001175 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001176
Chris Lattnerfb018d12011-02-15 00:14:06 +00001177 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001178 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1179 return Yay;
1180 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001181
John McCall2de56d12010-08-25 11:45:40 +00001182 case CK_IntegralCast:
1183 case CK_IntegralToFloating:
1184 case CK_FloatingToIntegral:
1185 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001186 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001187
John McCalldaa8e4e2010-11-15 09:13:47 +00001188 case CK_IntegralToBoolean:
1189 return EmitIntToBoolConversion(Visit(E));
1190 case CK_PointerToBoolean:
1191 return EmitPointerToBoolConversion(Visit(E));
1192 case CK_FloatingToBoolean:
1193 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001194 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001195 llvm::Value *MemPtr = Visit(E);
1196 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1197 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001198 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001199
1200 case CK_FloatingComplexToReal:
1201 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001202 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001203
1204 case CK_FloatingComplexToBoolean:
1205 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001206 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001207
1208 // TODO: kill this function off, inline appropriate case here
1209 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1210 }
1211
John McCall0bab0cd2010-08-23 01:21:21 +00001212 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001213
John McCall61ad0e62010-11-16 06:21:14 +00001214 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001215 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001216}
1217
Chris Lattner33793202007-08-31 22:09:40 +00001218Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001219 CodeGenFunction::StmtExprEvaluation eval(CGF);
1220 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1221 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001222}
1223
Mike Stumpa99038c2009-02-28 09:07:16 +00001224Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001225 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1226 if (E->getType().isObjCGCWeak())
1227 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Fariborz Jahanian469a20d2010-09-03 23:07:53 +00001228 return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
Mike Stump4e7a1f72009-02-21 20:00:35 +00001229}
Chris Lattner33793202007-08-31 22:09:40 +00001230
Chris Lattner7f02f722007-08-24 05:35:26 +00001231//===----------------------------------------------------------------------===//
1232// Unary Operators
1233//===----------------------------------------------------------------------===//
1234
Chris Lattner8c11a652010-06-26 22:09:34 +00001235llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001236EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1237 llvm::Value *InVal,
1238 llvm::Value *NextVal, bool IsInc) {
1239 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1240 case LangOptions::SOB_Undefined:
1241 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1242 break;
1243 case LangOptions::SOB_Defined:
1244 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1245 break;
1246 case LangOptions::SOB_Trapping:
1247 BinOpInfo BinOp;
1248 BinOp.LHS = InVal;
1249 BinOp.RHS = NextVal;
1250 BinOp.Ty = E->getType();
1251 BinOp.Opcode = BO_Add;
1252 BinOp.E = E;
1253 return EmitOverflowCheckedBinOp(BinOp);
1254 break;
1255 }
1256 assert(false && "Unknown SignedOverflowBehaviorTy");
1257 return 0;
1258}
1259
John McCall5936e332011-02-15 09:22:45 +00001260llvm::Value *
1261ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1262 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001263
John McCall5936e332011-02-15 09:22:45 +00001264 QualType type = E->getSubExpr()->getType();
1265 llvm::Value *value = EmitLoadOfLValue(LV, type);
1266 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001267
John McCall5936e332011-02-15 09:22:45 +00001268 int amount = (isInc ? 1 : -1);
1269
1270 // Special case of integer increment that we have to check first: bool++.
1271 // Due to promotion rules, we get:
1272 // bool++ -> bool = bool + 1
1273 // -> bool = (int)bool + 1
1274 // -> bool = ((int)bool + 1 != 0)
1275 // An interesting aspect of this is that increment is always true.
1276 // Decrement does not have this property.
1277 if (isInc && type->isBooleanType()) {
1278 value = Builder.getTrue();
1279
1280 // Most common case by far: integer increment.
1281 } else if (type->isIntegerType()) {
1282
1283 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1284
1285 if (type->isSignedIntegerType())
1286 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1287
1288 // Unsigned integer inc is always two's complement.
1289 else
1290 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1291
1292 // Next most common: pointer increment.
1293 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1294 QualType type = ptr->getPointeeType();
1295
1296 // VLA types don't have constant size.
1297 if (type->isVariableArrayType()) {
1298 llvm::Value *vlaSize =
1299 CGF.GetVLASize(CGF.getContext().getAsVariableArrayType(type));
1300 value = CGF.EmitCastToVoidPtr(value);
1301 if (!isInc) vlaSize = Builder.CreateNSWNeg(vlaSize, "vla.negsize");
1302 value = Builder.CreateInBoundsGEP(value, vlaSize, "vla.inc");
1303 value = Builder.CreateBitCast(value, input->getType());
1304
1305 // Arithmetic on function pointers (!) is just +-1.
1306 } else if (type->isFunctionType()) {
1307 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1308
1309 value = CGF.EmitCastToVoidPtr(value);
1310 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1311 value = Builder.CreateBitCast(value, input->getType());
1312
1313 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001314 } else {
John McCall5936e332011-02-15 09:22:45 +00001315 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1316 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1317 }
1318
1319 // Vector increment/decrement.
1320 } else if (type->isVectorType()) {
1321 if (type->hasIntegerRepresentation()) {
1322 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1323
1324 if (type->hasSignedIntegerRepresentation())
1325 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1326 else
1327 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1328 } else {
1329 value = Builder.CreateFAdd(
1330 value,
1331 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001332 isInc ? "inc" : "dec");
1333 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001334
John McCall5936e332011-02-15 09:22:45 +00001335 // Floating point.
1336 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001337 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001338 llvm::Value *amt;
1339 if (value->getType()->isFloatTy())
1340 amt = llvm::ConstantFP::get(VMContext,
1341 llvm::APFloat(static_cast<float>(amount)));
1342 else if (value->getType()->isDoubleTy())
1343 amt = llvm::ConstantFP::get(VMContext,
1344 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001345 else {
John McCall5936e332011-02-15 09:22:45 +00001346 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001347 bool ignored;
1348 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1349 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001350 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001351 }
John McCall5936e332011-02-15 09:22:45 +00001352 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1353
1354 // Objective-C pointer types.
1355 } else {
1356 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1357 value = CGF.EmitCastToVoidPtr(value);
1358
1359 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1360 if (!isInc) size = -size;
1361 llvm::Value *sizeValue =
1362 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1363
1364 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1365 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001366 }
1367
1368 // Store the updated result through the lvalue.
1369 if (LV.isBitField())
John McCall5936e332011-02-15 09:22:45 +00001370 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, type, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001371 else
John McCall5936e332011-02-15 09:22:45 +00001372 CGF.EmitStoreThroughLValue(RValue::get(value), LV, type);
Chris Lattner8c11a652010-06-26 22:09:34 +00001373
1374 // If this is a postinc, return the value read from memory, otherwise use the
1375 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001376 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001377}
1378
1379
1380
Chris Lattner7f02f722007-08-24 05:35:26 +00001381Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001382 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001383 // Emit unary minus with EmitSub so we handle overflow cases etc.
1384 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001385 BinOp.RHS = Visit(E->getSubExpr());
1386
1387 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1388 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1389 else
1390 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001391 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001392 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001393 BinOp.E = E;
1394 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001395}
1396
1397Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001398 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001399 Value *Op = Visit(E->getSubExpr());
1400 return Builder.CreateNot(Op, "neg");
1401}
1402
1403Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1404 // Compare operand to zero.
1405 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001406
Chris Lattner7f02f722007-08-24 05:35:26 +00001407 // Invert value.
1408 // TODO: Could dynamically modify easy computations here. For example, if
1409 // the operand is an icmp ne, turn into icmp eq.
1410 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001411
Anders Carlsson9f84d882009-05-19 18:44:53 +00001412 // ZExt result to the expr type.
1413 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001414}
1415
Eli Friedman0027d2b2010-08-05 09:58:49 +00001416Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1417 // Try folding the offsetof to a constant.
1418 Expr::EvalResult EvalResult;
1419 if (E->Evaluate(EvalResult, CGF.getContext()))
1420 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1421
1422 // Loop over the components of the offsetof to compute the value.
1423 unsigned n = E->getNumComponents();
1424 const llvm::Type* ResultType = ConvertType(E->getType());
1425 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1426 QualType CurrentType = E->getTypeSourceInfo()->getType();
1427 for (unsigned i = 0; i != n; ++i) {
1428 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001429 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001430 switch (ON.getKind()) {
1431 case OffsetOfExpr::OffsetOfNode::Array: {
1432 // Compute the index
1433 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1434 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1435 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1436 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1437
1438 // Save the element type
1439 CurrentType =
1440 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1441
1442 // Compute the element size
1443 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1444 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1445
1446 // Multiply out to compute the result
1447 Offset = Builder.CreateMul(Idx, ElemSize);
1448 break;
1449 }
1450
1451 case OffsetOfExpr::OffsetOfNode::Field: {
1452 FieldDecl *MemberDecl = ON.getField();
1453 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1454 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1455
1456 // Compute the index of the field in its parent.
1457 unsigned i = 0;
1458 // FIXME: It would be nice if we didn't have to loop here!
1459 for (RecordDecl::field_iterator Field = RD->field_begin(),
1460 FieldEnd = RD->field_end();
1461 Field != FieldEnd; (void)++Field, ++i) {
1462 if (*Field == MemberDecl)
1463 break;
1464 }
1465 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1466
1467 // Compute the offset to the field
1468 int64_t OffsetInt = RL.getFieldOffset(i) /
1469 CGF.getContext().getCharWidth();
1470 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1471
1472 // Save the element type.
1473 CurrentType = MemberDecl->getType();
1474 break;
1475 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001476
Eli Friedman0027d2b2010-08-05 09:58:49 +00001477 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001478 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001479
Eli Friedman0027d2b2010-08-05 09:58:49 +00001480 case OffsetOfExpr::OffsetOfNode::Base: {
1481 if (ON.getBase()->isVirtual()) {
1482 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1483 continue;
1484 }
1485
1486 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1487 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1488
1489 // Save the element type.
1490 CurrentType = ON.getBase()->getType();
1491
1492 // Compute the offset to the base.
1493 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1494 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001495 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001496 CGF.getContext().getCharWidth();
1497 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1498 break;
1499 }
1500 }
1501 Result = Builder.CreateAdd(Result, Offset);
1502 }
1503 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001504}
1505
Sebastian Redl05189992008-11-11 17:56:53 +00001506/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1507/// argument of the sizeof expression as an integer.
1508Value *
1509ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001510 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001511 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001512 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001513 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1514 if (E->isArgumentType()) {
1515 // sizeof(type) - make sure to emit the VLA size.
1516 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001517 } else {
1518 // C99 6.5.3.4p2: If the argument is an expression of type
1519 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001520 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001521 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001522
Anders Carlsson96f21472009-02-05 19:43:10 +00001523 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001524 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001525 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001526
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001527 // If this isn't sizeof(vla), the result must be constant; use the constant
1528 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001529 Expr::EvalResult Result;
1530 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001531 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001532}
1533
Chris Lattner46f93d02007-08-24 21:20:17 +00001534Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1535 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001536 if (Op->getType()->isAnyComplexType()) {
1537 // If it's an l-value, load through the appropriate subobject l-value.
1538 // Note that we have to ask E because Op might be an l-value that
1539 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001540 if (E->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001541 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1542 .getScalarVal();
1543
1544 // Otherwise, calculate and project.
1545 return CGF.EmitComplexExpr(Op, false, true).first;
1546 }
1547
Chris Lattner46f93d02007-08-24 21:20:17 +00001548 return Visit(Op);
1549}
John McCallb418d742010-11-16 10:08:07 +00001550
Chris Lattner46f93d02007-08-24 21:20:17 +00001551Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1552 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001553 if (Op->getType()->isAnyComplexType()) {
1554 // If it's an l-value, load through the appropriate subobject l-value.
1555 // Note that we have to ask E because Op might be an l-value that
1556 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001557 if (Op->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001558 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1559 .getScalarVal();
1560
1561 // Otherwise, calculate and project.
1562 return CGF.EmitComplexExpr(Op, true, false).second;
1563 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001564
Mike Stump7f79f9b2009-05-29 15:46:01 +00001565 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1566 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001567 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001568 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001569}
1570
Chris Lattner7f02f722007-08-24 05:35:26 +00001571//===----------------------------------------------------------------------===//
1572// Binary Operators
1573//===----------------------------------------------------------------------===//
1574
1575BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001576 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001577 BinOpInfo Result;
1578 Result.LHS = Visit(E->getLHS());
1579 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001580 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001581 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001582 Result.E = E;
1583 return Result;
1584}
1585
Douglas Gregor6a03e342010-04-23 04:16:32 +00001586LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1587 const CompoundAssignOperator *E,
1588 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001589 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001590 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001591 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001592
Eli Friedmanab3a8522009-03-28 01:22:36 +00001593 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001594 // This needs to go through the complex expression emitter, but it's a tad
1595 // complicated to do that... I'm leaving it out for now. (Note that we do
1596 // actually need the imaginary part of the RHS for multiplication and
1597 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001598 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001599 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001600 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001601 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001602
Mike Stumpcc0442f2009-05-22 19:07:20 +00001603 // Emit the RHS first. __block variables need to have the rhs evaluated
1604 // first, plus this should improve codegen a little.
1605 OpInfo.RHS = Visit(E->getRHS());
1606 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001607 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001608 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001609 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001610 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001611 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001612 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1613 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001614
Chris Lattner1f1ded92007-08-24 21:00:35 +00001615 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001616 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001617
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001618 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001619 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001620
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001621 // Store the result value into the LHS lvalue. Bit-fields are handled
1622 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1623 // 'An assignment expression has the value of the left operand after the
1624 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001625 if (LHSLV.isBitField())
1626 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1627 &Result);
1628 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001629 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001630
Douglas Gregor6a03e342010-04-23 04:16:32 +00001631 return LHSLV;
1632}
1633
1634Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1635 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1636 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001637 Value *RHS;
1638 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1639
1640 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001641 if (Ignore)
1642 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001643
John McCallb418d742010-11-16 10:08:07 +00001644 // The result of an assignment in C is the assigned r-value.
1645 if (!CGF.getContext().getLangOptions().CPlusPlus)
1646 return RHS;
1647
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001648 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001649 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001650 return RHS;
1651
1652 // If the lvalue is non-volatile, return the computed value of the assignment.
1653 if (!LHS.isVolatileQualified())
1654 return RHS;
1655
1656 // Otherwise, reload the value.
1657 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001658}
1659
Chris Lattner80230302010-09-11 21:47:09 +00001660void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1661 const BinOpInfo &Ops,
1662 llvm::Value *Zero, bool isDiv) {
1663 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1664 llvm::BasicBlock *contBB =
1665 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1666
1667 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1668
1669 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1670 llvm::Value *IntMin =
1671 llvm::ConstantInt::get(VMContext,
1672 llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1673 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1674
1675 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1676 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1677 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1678 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1679 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1680 overflowBB, contBB);
1681 } else {
1682 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1683 overflowBB, contBB);
1684 }
1685 EmitOverflowBB(overflowBB);
1686 Builder.SetInsertPoint(contBB);
1687}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001688
Chris Lattner7f02f722007-08-24 05:35:26 +00001689Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001690 if (isTrapvOverflowBehavior()) {
1691 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1692
1693 if (Ops.Ty->isIntegerType())
1694 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1695 else if (Ops.Ty->isRealFloatingType()) {
1696 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1697 CGF.CurFn);
1698 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1699 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1700 overflowBB, DivCont);
1701 EmitOverflowBB(overflowBB);
1702 Builder.SetInsertPoint(DivCont);
1703 }
1704 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001705 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001706 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001707 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001708 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1709 else
1710 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1711}
1712
1713Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1714 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001715 if (isTrapvOverflowBehavior()) {
1716 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1717
1718 if (Ops.Ty->isIntegerType())
1719 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1720 }
1721
Chris Lattner1f1ded92007-08-24 21:00:35 +00001722 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001723 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1724 else
1725 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1726}
1727
Mike Stump2add4732009-04-01 20:28:16 +00001728Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1729 unsigned IID;
1730 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001731
Chris Lattner9a207232010-06-26 21:48:21 +00001732 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001733 case BO_Add:
1734 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001735 OpID = 1;
1736 IID = llvm::Intrinsic::sadd_with_overflow;
1737 break;
John McCall2de56d12010-08-25 11:45:40 +00001738 case BO_Sub:
1739 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001740 OpID = 2;
1741 IID = llvm::Intrinsic::ssub_with_overflow;
1742 break;
John McCall2de56d12010-08-25 11:45:40 +00001743 case BO_Mul:
1744 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001745 OpID = 3;
1746 IID = llvm::Intrinsic::smul_with_overflow;
1747 break;
1748 default:
1749 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001750 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001751 }
Mike Stump035cf892009-04-02 18:15:54 +00001752 OpID <<= 1;
1753 OpID |= 1;
1754
Mike Stump2add4732009-04-01 20:28:16 +00001755 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1756
1757 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1758
1759 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1760 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1761 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1762
1763 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001764 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Chris Lattner93a00352010-08-07 00:20:46 +00001765 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1766 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001767
1768 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1769
Chris Lattner93a00352010-08-07 00:20:46 +00001770 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001771 const std::string *handlerName =
1772 &CGF.getContext().getLangOptions().OverflowHandler;
1773 if (handlerName->empty()) {
1774 EmitOverflowBB(overflowBB);
1775 Builder.SetInsertPoint(continueBB);
1776 return result;
1777 }
1778
1779 // If an overflow handler is set, then we want to call it and then use its
1780 // result, if it returns.
1781 Builder.SetInsertPoint(overflowBB);
1782
1783 // Get the overflow handler.
1784 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1785 std::vector<const llvm::Type*> argTypes;
1786 argTypes.push_back(CGF.Int64Ty); argTypes.push_back(CGF.Int64Ty);
1787 argTypes.push_back(Int8Ty); argTypes.push_back(Int8Ty);
1788 llvm::FunctionType *handlerTy =
1789 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1790 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1791
1792 // Sign extend the args to 64-bit, so that we can use the same handler for
1793 // all types of overflow.
1794 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1795 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1796
1797 // Call the handler with the two arguments, the operation, and the size of
1798 // the result.
1799 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1800 Builder.getInt8(OpID),
1801 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1802
1803 // Truncate the result back to the desired size.
1804 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1805 Builder.CreateBr(continueBB);
1806
Mike Stump2add4732009-04-01 20:28:16 +00001807 Builder.SetInsertPoint(continueBB);
David Chisnall7f18e672010-09-17 18:29:54 +00001808 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1809 phi->reserveOperandSpace(2);
1810 phi->addIncoming(result, initialBB);
1811 phi->addIncoming(handlerResult, overflowBB);
1812
1813 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001814}
Chris Lattner7f02f722007-08-24 05:35:26 +00001815
1816Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001817 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001818 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001819 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1820 case LangOptions::SOB_Undefined:
1821 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1822 case LangOptions::SOB_Defined:
1823 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1824 case LangOptions::SOB_Trapping:
1825 return EmitOverflowCheckedBinOp(Ops);
1826 }
1827 }
1828
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001829 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001830 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001831
Chris Lattner7f02f722007-08-24 05:35:26 +00001832 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001833 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001834
Chris Lattner7f215c12010-06-26 21:52:32 +00001835 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001836 // use this path.
1837 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1838
Steve Naroff14108da2009-07-10 23:34:53 +00001839 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001840 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001841 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001842 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001843 }
Chris Lattner9a207232010-06-26 21:48:21 +00001844
Chris Lattner8f925282008-01-03 06:36:51 +00001845 Value *Ptr, *Idx;
1846 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001847 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001848 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001849 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001850 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001851 Ptr = Ops.LHS;
1852 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001853 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001854 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001855 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1856 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001857 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001858 Ptr = Ops.RHS;
1859 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001860 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001861 }
1862
1863 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001864 if (Width < CGF.PointerWidthInBits) {
Chris Lattner8f925282008-01-03 06:36:51 +00001865 // Zero or sign extend the pointer value based on whether the index is
1866 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001867 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001868 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001869 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1870 else
1871 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1872 }
Steve Naroff14108da2009-07-10 23:34:53 +00001873 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001874 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001875 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001876 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001877 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001878 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001879 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001880 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001881 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1882 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1883 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001884 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001885
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001886 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1887 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1888 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001889 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001890 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001891 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001892 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001893 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001894 }
1895
Dan Gohman664f8932009-08-12 00:33:55 +00001896 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001897}
1898
1899Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001900 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001901 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001902 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1903 case LangOptions::SOB_Undefined:
1904 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1905 case LangOptions::SOB_Defined:
1906 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1907 case LangOptions::SOB_Trapping:
1908 return EmitOverflowCheckedBinOp(Ops);
1909 }
1910 }
1911
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001912 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001913 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001914
Chris Lattner7f02f722007-08-24 05:35:26 +00001915 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001916 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001917
Chris Lattner9a207232010-06-26 21:48:21 +00001918 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1919 // use this path.
1920 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1921
1922 if (BinOp->getLHS()->getType()->isPointerType() &&
1923 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001924 // The amount of the addition needs to account for the VLA size for
1925 // ptr-int
1926 // The amount of the division needs to account for the VLA size for
1927 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001928 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001929 }
1930
Chris Lattner9a207232010-06-26 21:48:21 +00001931 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001932 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001933 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1934 // pointer - int
1935 Value *Idx = Ops.RHS;
1936 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001937 if (Width < CGF.PointerWidthInBits) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001938 // Zero or sign extend the pointer value based on whether the index is
1939 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001940 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001941 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001942 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1943 else
1944 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1945 }
1946 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001947
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001948 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001949 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001950 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001951 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001952 CGF.getContext().
1953 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001954 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001955 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001956 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1957 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1958 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001959 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001960
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001961 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001962 // extensions. The GNU void* casts amount to no-ops since our void* type is
1963 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001964 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001965 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001966 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1967 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1968 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001969 }
1970
Dan Gohman664f8932009-08-12 00:33:55 +00001971 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001972 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001973 // pointer - pointer
1974 Value *LHS = Ops.LHS;
1975 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001976
Ken Dyck199c3d62010-01-11 17:06:35 +00001977 CharUnits ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001978
Chris Lattnere5ed1512009-02-11 07:21:43 +00001979 // Handle GCC extension for pointer arithmetic on void* and function pointer
1980 // types.
1981 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001982 ElementSize = CharUnits::One();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001983 } else {
Ken Dyck199c3d62010-01-11 17:06:35 +00001984 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001985 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001986
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001987 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1988 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1989 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1990 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001991
Chris Lattnere5ed1512009-02-11 07:21:43 +00001992 // Optimize out the shift for element size of 1.
Ken Dyck199c3d62010-01-11 17:06:35 +00001993 if (ElementSize.isOne())
Chris Lattnere5ed1512009-02-11 07:21:43 +00001994 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001995
1996 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001997 // pointer difference in C is only defined in the case where both operands
1998 // are pointing to elements of an array.
Ken Dyck199c3d62010-01-11 17:06:35 +00001999 Value *BytesPerElt =
2000 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
Dan Gohmandf110942009-08-11 22:40:09 +00002001 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002002 }
Chris Lattner7f02f722007-08-24 05:35:26 +00002003}
2004
2005Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2006 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2007 // RHS to the same size as the LHS.
2008 Value *RHS = Ops.RHS;
2009 if (Ops.LHS->getType() != RHS->getType())
2010 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002011
Mike Stumpbe07f602009-12-14 21:58:14 +00002012 if (CGF.CatchUndefined
2013 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2014 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2015 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2016 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2017 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002018 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002019 CGF.EmitBlock(Cont);
2020 }
2021
Chris Lattner7f02f722007-08-24 05:35:26 +00002022 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2023}
2024
2025Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2026 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2027 // RHS to the same size as the LHS.
2028 Value *RHS = Ops.RHS;
2029 if (Ops.LHS->getType() != RHS->getType())
2030 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002031
Mike Stumpbe07f602009-12-14 21:58:14 +00002032 if (CGF.CatchUndefined
2033 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2034 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2035 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2036 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2037 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002038 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002039 CGF.EmitBlock(Cont);
2040 }
2041
Douglas Gregorf6094622010-07-23 15:58:24 +00002042 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002043 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2044 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2045}
2046
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002047enum IntrinsicType { VCMPEQ, VCMPGT };
2048// return corresponding comparison intrinsic for given vector type
2049static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2050 BuiltinType::Kind ElemKind) {
2051 switch (ElemKind) {
2052 default: assert(0 && "unexpected element type");
2053 case BuiltinType::Char_U:
2054 case BuiltinType::UChar:
2055 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2056 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2057 break;
2058 case BuiltinType::Char_S:
2059 case BuiltinType::SChar:
2060 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2061 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2062 break;
2063 case BuiltinType::UShort:
2064 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2065 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2066 break;
2067 case BuiltinType::Short:
2068 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2069 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2070 break;
2071 case BuiltinType::UInt:
2072 case BuiltinType::ULong:
2073 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2074 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2075 break;
2076 case BuiltinType::Int:
2077 case BuiltinType::Long:
2078 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2079 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2080 break;
2081 case BuiltinType::Float:
2082 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2083 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2084 break;
2085 }
2086 return llvm::Intrinsic::not_intrinsic;
2087}
2088
Chris Lattner7f02f722007-08-24 05:35:26 +00002089Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2090 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002091 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002092 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002093 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002094 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002095 assert(E->getOpcode() == BO_EQ ||
2096 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002097 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2098 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002099 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002100 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002101 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002102 Value *LHS = Visit(E->getLHS());
2103 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002104
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002105 // If AltiVec, the comparison results in a numeric type, so we use
2106 // intrinsics comparing vectors and giving 0 or 1 as a result
2107 if (LHSTy->isVectorType() && CGF.getContext().getLangOptions().AltiVec) {
2108 // constants for mapping CR6 register bits to predicate result
2109 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2110
2111 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2112
2113 // in several cases vector arguments order will be reversed
2114 Value *FirstVecArg = LHS,
2115 *SecondVecArg = RHS;
2116
2117 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002118 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002119 BuiltinType::Kind ElementKind = BTy->getKind();
2120
2121 switch(E->getOpcode()) {
2122 default: assert(0 && "is not a comparison operation");
2123 case BO_EQ:
2124 CR6 = CR6_LT;
2125 ID = GetIntrinsic(VCMPEQ, ElementKind);
2126 break;
2127 case BO_NE:
2128 CR6 = CR6_EQ;
2129 ID = GetIntrinsic(VCMPEQ, ElementKind);
2130 break;
2131 case BO_LT:
2132 CR6 = CR6_LT;
2133 ID = GetIntrinsic(VCMPGT, ElementKind);
2134 std::swap(FirstVecArg, SecondVecArg);
2135 break;
2136 case BO_GT:
2137 CR6 = CR6_LT;
2138 ID = GetIntrinsic(VCMPGT, ElementKind);
2139 break;
2140 case BO_LE:
2141 if (ElementKind == BuiltinType::Float) {
2142 CR6 = CR6_LT;
2143 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2144 std::swap(FirstVecArg, SecondVecArg);
2145 }
2146 else {
2147 CR6 = CR6_EQ;
2148 ID = GetIntrinsic(VCMPGT, ElementKind);
2149 }
2150 break;
2151 case BO_GE:
2152 if (ElementKind == BuiltinType::Float) {
2153 CR6 = CR6_LT;
2154 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2155 }
2156 else {
2157 CR6 = CR6_EQ;
2158 ID = GetIntrinsic(VCMPGT, ElementKind);
2159 std::swap(FirstVecArg, SecondVecArg);
2160 }
2161 break;
2162 }
2163
2164 Value *CR6Param = llvm::ConstantInt::get(CGF.Int32Ty, CR6);
2165 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2166 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2167 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2168 }
2169
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002170 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002171 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002172 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002173 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002174 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002175 LHS, RHS, "cmp");
2176 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002177 // Unsigned integers and pointers.
2178 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002179 LHS, RHS, "cmp");
2180 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002181
2182 // If this is a vector comparison, sign extend the result to the appropriate
2183 // vector integer type and return it (don't convert to bool).
2184 if (LHSTy->isVectorType())
2185 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002186
Chris Lattner7f02f722007-08-24 05:35:26 +00002187 } else {
2188 // Complex Comparison: can only be an equality comparison.
2189 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2190 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002191
John McCall183700f2009-09-21 23:43:11 +00002192 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002193
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002194 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002195 if (CETy->isRealFloatingType()) {
2196 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2197 LHS.first, RHS.first, "cmp.r");
2198 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2199 LHS.second, RHS.second, "cmp.i");
2200 } else {
2201 // Complex comparisons can only be equality comparisons. As such, signed
2202 // and unsigned opcodes are the same.
2203 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2204 LHS.first, RHS.first, "cmp.r");
2205 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2206 LHS.second, RHS.second, "cmp.i");
2207 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002208
John McCall2de56d12010-08-25 11:45:40 +00002209 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002210 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2211 } else {
John McCall2de56d12010-08-25 11:45:40 +00002212 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002213 "Complex comparison other than == or != ?");
2214 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2215 }
2216 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002217
2218 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002219}
2220
2221Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002222 bool Ignore = TestAndClearIgnoreResultAssign();
2223
2224 // __block variables need to have the rhs evaluated first, plus this should
2225 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00002226 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00002227 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002228
Daniel Dunbared3849b2008-11-19 09:36:46 +00002229 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00002230 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2231 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00002232 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002233 if (LHS.isBitField())
2234 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
2235 &RHS);
2236 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00002237 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002238
2239 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002240 if (Ignore)
2241 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002242
John McCallb418d742010-11-16 10:08:07 +00002243 // The result of an assignment in C is the assigned r-value.
2244 if (!CGF.getContext().getLangOptions().CPlusPlus)
2245 return RHS;
2246
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002247 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002248 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002249 return RHS;
2250
2251 // If the lvalue is non-volatile, return the computed value of the assignment.
2252 if (!LHS.isVolatileQualified())
2253 return RHS;
2254
2255 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002256 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002257}
2258
2259Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002260 const llvm::Type *ResTy = ConvertType(E->getType());
2261
Chris Lattner20eb09d2008-11-12 08:26:50 +00002262 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2263 // If we have 1 && X, just emit X without inserting the control flow.
2264 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2265 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002266 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002267 // ZExt result to int or bool.
2268 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002269 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002270
Chris Lattner7804bcb2009-10-17 04:24:20 +00002271 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002272 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002273 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002274 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002275
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002276 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2277 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002278
John McCall150b4622011-01-26 04:00:11 +00002279 CodeGenFunction::ConditionalEvaluation eval(CGF);
2280
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002281 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2282 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2283
2284 // Any edges into the ContBlock are now from an (indeterminate number of)
2285 // edges from this first condition. All of these values will be false. Start
2286 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002287 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2288 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002289 PN->reserveOperandSpace(2); // Normal case, two inputs.
2290 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2291 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002292 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002293
John McCall150b4622011-01-26 04:00:11 +00002294 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002295 CGF.EmitBlock(RHSBlock);
2296 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002297 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002298
Chris Lattner7f02f722007-08-24 05:35:26 +00002299 // Reaquire the RHS block, as there may be subblocks inserted.
2300 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002301
2302 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2303 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00002304 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002305 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002306
Chris Lattner7f02f722007-08-24 05:35:26 +00002307 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002308 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002309}
2310
2311Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002312 const llvm::Type *ResTy = ConvertType(E->getType());
2313
Chris Lattner20eb09d2008-11-12 08:26:50 +00002314 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2315 // If we have 0 || X, just emit X without inserting the control flow.
2316 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2317 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002318 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002319 // ZExt result to int or bool.
2320 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002321 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002322
Chris Lattner7804bcb2009-10-17 04:24:20 +00002323 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002324 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002325 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002326 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002327
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002328 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2329 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002330
John McCall150b4622011-01-26 04:00:11 +00002331 CodeGenFunction::ConditionalEvaluation eval(CGF);
2332
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002333 // Branch on the LHS first. If it is true, go to the success (cont) block.
2334 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2335
2336 // Any edges into the ContBlock are now from an (indeterminate number of)
2337 // edges from this first condition. All of these values will be true. Start
2338 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002339 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2340 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002341 PN->reserveOperandSpace(2); // Normal case, two inputs.
2342 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2343 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002344 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002345
John McCall150b4622011-01-26 04:00:11 +00002346 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002347
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002348 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002349 CGF.EmitBlock(RHSBlock);
2350 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002351
John McCall150b4622011-01-26 04:00:11 +00002352 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002353
Chris Lattner7f02f722007-08-24 05:35:26 +00002354 // Reaquire the RHS block, as there may be subblocks inserted.
2355 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002356
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002357 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2358 // into the phi node for the edge with the value of RHSCond.
2359 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002360 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002361
Chris Lattner7f02f722007-08-24 05:35:26 +00002362 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002363 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002364}
2365
2366Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002367 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002368 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002369 return Visit(E->getRHS());
2370}
2371
2372//===----------------------------------------------------------------------===//
2373// Other Operators
2374//===----------------------------------------------------------------------===//
2375
Chris Lattner9802a512008-11-12 08:55:54 +00002376/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2377/// expression is cheap enough and side-effect-free enough to evaluate
2378/// unconditionally instead of conditionally. This is used to convert control
2379/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002380static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2381 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00002382 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002383 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002384
Chris Lattner9802a512008-11-12 08:55:54 +00002385 // TODO: Allow anything we can constant fold to an integer or fp constant.
2386 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2387 isa<FloatingLiteral>(E))
2388 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002389
Chris Lattner9802a512008-11-12 08:55:54 +00002390 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2391 // X and Y are local variables.
2392 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2393 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002394 if (VD->hasLocalStorage() && !(CGF.getContext()
2395 .getCanonicalType(VD->getType())
2396 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002397 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002398
Chris Lattner9802a512008-11-12 08:55:54 +00002399 return false;
2400}
2401
2402
Chris Lattner7f02f722007-08-24 05:35:26 +00002403Value *ScalarExprEmitter::
2404VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002405 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00002406 // If the condition constant folds and can be elided, try to avoid emitting
2407 // the condition and the dead arm.
2408 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00002409 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00002410 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00002411 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002412
Chris Lattner31a09842008-11-12 08:04:58 +00002413 // If the dead side doesn't have labels we need, and if the Live side isn't
2414 // the gnu missing ?: extension (which we could handle, but don't bother
2415 // to), just emit the Live part.
2416 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
2417 Live) // Live part isn't missing.
2418 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002419 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002420
Nate Begeman6155d732010-09-20 22:41:17 +00002421 // OpenCL: If the condition is a vector, we can treat this condition like
2422 // the select function.
2423 if (CGF.getContext().getLangOptions().OpenCL
2424 && E->getCond()->getType()->isVectorType()) {
2425 llvm::Value *CondV = CGF.EmitScalarExpr(E->getCond());
2426 llvm::Value *LHS = Visit(E->getLHS());
2427 llvm::Value *RHS = Visit(E->getRHS());
2428
2429 const llvm::Type *condType = ConvertType(E->getCond()->getType());
2430 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2431
2432 unsigned numElem = vecTy->getNumElements();
2433 const llvm::Type *elemType = vecTy->getElementType();
2434
2435 std::vector<llvm::Constant*> Zvals;
2436 for (unsigned i = 0; i < numElem; ++i)
2437 Zvals.push_back(llvm::ConstantInt::get(elemType,0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002438
Nate Begeman6155d732010-09-20 22:41:17 +00002439 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2440 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2441 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2442 llvm::VectorType::get(elemType,
2443 numElem),
2444 "sext");
2445 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2446
2447 // Cast float to int to perform ANDs if necessary.
2448 llvm::Value *RHSTmp = RHS;
2449 llvm::Value *LHSTmp = LHS;
2450 bool wasCast = false;
2451 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2452 if (rhsVTy->getElementType()->isFloatTy()) {
2453 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2454 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2455 wasCast = true;
2456 }
2457
2458 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2459 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2460 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2461 if (wasCast)
2462 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2463
2464 return tmp5;
2465 }
2466
Chris Lattner9802a512008-11-12 08:55:54 +00002467 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2468 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002469 // safe to evaluate the LHS and RHS unconditionally.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002470 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2471 CGF) &&
2472 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
Chris Lattner9802a512008-11-12 08:55:54 +00002473 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2474 llvm::Value *LHS = Visit(E->getLHS());
2475 llvm::Value *RHS = Visit(E->getRHS());
2476 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2477 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002478
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002479 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2480 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002481 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002482
2483 CodeGenFunction::ConditionalEvaluation eval(CGF);
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +00002484
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002485 // If we don't have the GNU missing condition extension, emit a branch on bool
2486 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00002487 if (E->getLHS()) {
2488 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2489 // the branch on bool.
2490 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2491 } else {
2492 // Otherwise, for the ?: extension, evaluate the conditional and then
2493 // convert it to bool the hard way. We do this explicitly because we need
2494 // the unconverted value for the missing middle value of the ?:.
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +00002495 Expr *save = E->getSAVE();
2496 assert(save && "VisitConditionalOperator - save is null");
2497 // Intentianlly not doing direct assignment to ConditionalSaveExprs[save] !!
2498 Value *SaveVal = CGF.EmitScalarExpr(save);
2499 CGF.ConditionalSaveExprs[save] = SaveVal;
2500 Value *CondVal = Visit(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00002501 // In some cases, EmitScalarConversion will delete the "CondVal" expression
2502 // if there are no extra uses (an optimization). Inhibit this by making an
2503 // extra dead use, because we're going to add a use of CondVal later. We
2504 // don't use the builder for this, because we don't want it to get optimized
2505 // away. This leaves dead code, but the ?: extension isn't common.
2506 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2507 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002508
Chris Lattner035cf422008-11-12 08:08:13 +00002509 Value *CondBoolVal =
2510 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2511 CGF.getContext().BoolTy);
2512 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00002513 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002514
Chris Lattner7f02f722007-08-24 05:35:26 +00002515 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002516 eval.begin(CGF);
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +00002517 Value *LHS = Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +00002518 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002519
Chris Lattner7f02f722007-08-24 05:35:26 +00002520 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002521 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002522
Chris Lattner7f02f722007-08-24 05:35:26 +00002523 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002524 eval.begin(CGF);
Eli Friedman856226c2008-05-16 20:38:39 +00002525 Value *RHS = Visit(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002526 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002527
John McCall150b4622011-01-26 04:00:11 +00002528 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002529 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002530
Eli Friedman48daf592009-12-07 20:25:53 +00002531 // If the LHS or RHS is a throw expression, it will be legitimately null.
2532 if (!LHS)
2533 return RHS;
2534 if (!RHS)
2535 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002536
Chris Lattner7f02f722007-08-24 05:35:26 +00002537 // Create a PHI node for the real part.
2538 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2539 PN->reserveOperandSpace(2);
2540 PN->addIncoming(LHS, LHSBlock);
2541 PN->addIncoming(RHS, RHSBlock);
2542 return PN;
2543}
2544
2545Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002546 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002547}
2548
Chris Lattner2202bce2007-11-30 17:56:23 +00002549Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002550 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002551 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2552
2553 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002554 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002555 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2556
Mike Stump7f79f9b2009-05-29 15:46:01 +00002557 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002558 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002559}
2560
John McCall6b5a61b2011-02-07 10:33:21 +00002561Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2562 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002563}
2564
Chris Lattner7f02f722007-08-24 05:35:26 +00002565//===----------------------------------------------------------------------===//
2566// Entry Point into this File
2567//===----------------------------------------------------------------------===//
2568
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002569/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2570/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002571Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002572 assert(E && !hasAggregateLLVMType(E->getType()) &&
2573 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002574
Mike Stump7f79f9b2009-05-29 15:46:01 +00002575 return ScalarExprEmitter(*this, IgnoreResultAssign)
2576 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00002577}
Chris Lattner3707b252007-08-26 06:48:56 +00002578
2579/// EmitScalarConversion - Emit a conversion from the specified type to the
2580/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002581Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2582 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002583 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2584 "Invalid scalar expression to emit");
2585 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2586}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002587
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002588/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2589/// type to the specified destination type, where the destination type is an
2590/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002591Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2592 QualType SrcTy,
2593 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002594 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002595 "Invalid complex -> scalar conversion");
2596 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2597 DstTy);
2598}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002599
Chris Lattner8c11a652010-06-26 22:09:34 +00002600
2601llvm::Value *CodeGenFunction::
2602EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2603 bool isInc, bool isPre) {
2604 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2605}
2606
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002607LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2608 llvm::Value *V;
2609 // object->isa or (*object).isa
2610 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002611 // build Class* type
2612 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002613
2614 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002615 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002616 V = CreateTempAlloca(ClassPtrTy, "resval");
2617 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2618 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002619 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2620 MakeAddrLValue(V, E->getType()), E->getType());
2621 } else {
2622 if (E->isArrow())
2623 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2624 else
2625 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002626 }
2627
2628 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002629 ClassPtrTy = ClassPtrTy->getPointerTo();
2630 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002631 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002632}
2633
Douglas Gregor6a03e342010-04-23 04:16:32 +00002634
John McCall2a416372010-12-05 02:00:02 +00002635LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002636 const CompoundAssignOperator *E) {
2637 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002638 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002639 switch (E->getOpcode()) {
2640#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002641 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002642 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002643 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002644 COMPOUND_OP(Mul);
2645 COMPOUND_OP(Div);
2646 COMPOUND_OP(Rem);
2647 COMPOUND_OP(Add);
2648 COMPOUND_OP(Sub);
2649 COMPOUND_OP(Shl);
2650 COMPOUND_OP(Shr);
2651 COMPOUND_OP(And);
2652 COMPOUND_OP(Xor);
2653 COMPOUND_OP(Or);
2654#undef COMPOUND_OP
2655
John McCall2de56d12010-08-25 11:45:40 +00002656 case BO_PtrMemD:
2657 case BO_PtrMemI:
2658 case BO_Mul:
2659 case BO_Div:
2660 case BO_Rem:
2661 case BO_Add:
2662 case BO_Sub:
2663 case BO_Shl:
2664 case BO_Shr:
2665 case BO_LT:
2666 case BO_GT:
2667 case BO_LE:
2668 case BO_GE:
2669 case BO_EQ:
2670 case BO_NE:
2671 case BO_And:
2672 case BO_Xor:
2673 case BO_Or:
2674 case BO_LAnd:
2675 case BO_LOr:
2676 case BO_Assign:
2677 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002678 assert(false && "Not valid compound assignment operators");
2679 break;
2680 }
2681
2682 llvm_unreachable("Unhandled compound assignment operator");
2683}