blob: e7ae6b5708a090bee9635535d0fe2c8a0a781f8e [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
John McCall545d9962011-06-25 02:11:03 +000085 Value *EmitLoadOfLValue(LValue LV) {
86 return CGF.EmitLoadOfLValue(LV).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) {
John McCall545d9962011-06-25 02:11:03 +000093 return EmitLoadOfLValue(EmitCheckedLValue(E));
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
Chris Lattner48431f92011-04-19 22:55:03 +0000143 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000144 }
145
Chris Lattner7f02f722007-08-24 05:35:26 +0000146 //===--------------------------------------------------------------------===//
147 // Visitor Methods
148 //===--------------------------------------------------------------------===//
149
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000150 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
152 }
153
Chris Lattner7f02f722007-08-24 05:35:26 +0000154 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000155 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000156 assert(0 && "Stmt can't have complex result type!");
157 return 0;
158 }
159 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000160
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000161 Value *VisitParenExpr(ParenExpr *PE) {
162 return Visit(PE->getSubExpr());
163 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000164 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
165 return Visit(GE->getResultExpr());
166 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000167
168 // Leaves.
169 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000170 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000171 }
172 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000173 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000174 }
175 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000176 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000177 }
Nate Begemane7579b52007-11-15 05:40:03 +0000178 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000179 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000180 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000181 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000182 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000183 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000184 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000185 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000186 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000187 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000188 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000189 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000190 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
191 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000192 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000193
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000194 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000195 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000196 }
John McCalle996ffd2011-02-16 08:02:54 +0000197
198 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000199 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000200 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000201
202 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000203 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000204 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000205
Chris Lattner7f02f722007-08-24 05:35:26 +0000206 // l-values.
207 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000208 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000209 if (!E->Evaluate(Result, CGF.getContext()))
210 return EmitLoadOfLValue(E);
211
212 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
213
214 llvm::Constant *C;
Chris Lattner48431f92011-04-19 22:55:03 +0000215 if (Result.Val.isInt())
216 C = Builder.getInt(Result.Val.getInt());
217 else if (Result.Val.isFloat())
John McCall189d6ef2010-10-09 01:34:31 +0000218 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
Chris Lattner48431f92011-04-19 22:55:03 +0000219 else
John McCall189d6ef2010-10-09 01:34:31 +0000220 return EmitLoadOfLValue(E);
John McCall189d6ef2010-10-09 01:34:31 +0000221
222 // Make sure we emit a debug reference to the global variable.
223 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
224 if (!CGF.getContext().DeclMustBeEmitted(VD))
225 CGF.EmitDeclRefExprDbgValue(E, C);
226 } else if (isa<EnumConstantDecl>(E->getDecl())) {
227 CGF.EmitDeclRefExprDbgValue(E, C);
228 }
229
230 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000231 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000232 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
233 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000234 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000235 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
236 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000237 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000238 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000239 return EmitLoadOfLValue(E);
240 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000241 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000242 assert(E->getObjectKind() == OK_Ordinary &&
243 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000244 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000245 }
246 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000247 if (E->getMethodDecl() &&
248 E->getMethodDecl()->getResultType()->isReferenceType())
249 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000250 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000251 }
252
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000253 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000254 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000255 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000256 return V;
257 }
258
Chris Lattner7f02f722007-08-24 05:35:26 +0000259 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000260 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000261 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000262 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000263 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
264 return EmitLoadOfLValue(E);
265 }
Devang Patel35634f52007-10-24 17:18:43 +0000266
Nate Begeman0533b302009-10-18 20:10:40 +0000267 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000268
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000269 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000270 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000271 }
John McCallbc8d40d2011-06-24 21:55:10 +0000272 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000273 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000274 CGF.EmitVariablyModifiedType(E->getType());
275 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000276 }
John McCallbc8d40d2011-06-24 21:55:10 +0000277 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000278
279 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000280 if (E->getCallReturnType()->isReferenceType())
281 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000282
Chris Lattner9b655512007-08-31 22:49:20 +0000283 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000284 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000285
Chris Lattner33793202007-08-31 22:09:40 +0000286 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000287
Mike Stumpa99038c2009-02-28 09:07:16 +0000288 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000289
Chris Lattner7f02f722007-08-24 05:35:26 +0000290 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000292 LValue LV = EmitLValue(E->getSubExpr());
293 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 }
295 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000296 LValue LV = EmitLValue(E->getSubExpr());
297 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000298 }
299 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000300 LValue LV = EmitLValue(E->getSubExpr());
301 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000302 }
303 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000304 LValue LV = EmitLValue(E->getSubExpr());
305 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000307
Anton Yartsev683564a2011-02-07 02:17:30 +0000308 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
309 llvm::Value *InVal,
310 llvm::Value *NextVal,
311 bool IsInc);
312
Chris Lattner8c11a652010-06-26 22:09:34 +0000313 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
314 bool isInc, bool isPre);
315
316
Chris Lattner7f02f722007-08-24 05:35:26 +0000317 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000318 if (isa<MemberPointerType>(E->getType())) // never sugared
319 return CGF.CGM.getMemberPointerConstant(E);
320
Chris Lattner7f02f722007-08-24 05:35:26 +0000321 return EmitLValue(E->getSubExpr()).getAddress();
322 }
John McCallfd569002010-12-04 12:43:24 +0000323 Value *VisitUnaryDeref(const UnaryOperator *E) {
324 if (E->getType()->isVoidType())
325 return Visit(E->getSubExpr()); // the actual value should be unused
326 return EmitLoadOfLValue(E);
327 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000329 // This differs from gcc, though, most likely due to a bug in gcc.
330 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000331 return Visit(E->getSubExpr());
332 }
333 Value *VisitUnaryMinus (const UnaryOperator *E);
334 Value *VisitUnaryNot (const UnaryOperator *E);
335 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000336 Value *VisitUnaryReal (const UnaryOperator *E);
337 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000338 Value *VisitUnaryExtension(const UnaryOperator *E) {
339 return Visit(E->getSubExpr());
340 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000341
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000342 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000343 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
344 return Visit(DAE->getExpr());
345 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000346 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
347 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000348 }
349
John McCall4765fa02010-12-06 08:20:24 +0000350 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
351 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000352 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000353 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
354 return CGF.EmitCXXNewExpr(E);
355 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000356 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
357 CGF.EmitCXXDeleteExpr(E);
358 return 0;
359 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000360 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000361 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000362 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000363
Francois Pichet6ad6f282010-12-07 00:08:36 +0000364 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000365 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000366 }
367
John Wiegley21ff2e52011-04-28 00:16:57 +0000368 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
369 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
370 }
371
John Wiegley55262202011-04-25 06:54:41 +0000372 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
373 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
374 }
375
Douglas Gregora71d8192009-09-04 17:36:40 +0000376 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
377 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000378 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000379 // operator (), and the result of such a call has type void. The only
380 // effect is the evaluation of the postfix-expression before the dot or
381 // arrow.
382 CGF.EmitScalarExpr(E->getBase());
383 return 0;
384 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000385
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000386 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000387 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000388 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000389
390 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
391 CGF.EmitCXXThrowExpr(E);
392 return 0;
393 }
394
Sebastian Redl98294de2010-09-10 21:04:00 +0000395 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000396 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000397 }
398
Chris Lattner7f02f722007-08-24 05:35:26 +0000399 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000400 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000401 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000402 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
403 case LangOptions::SOB_Undefined:
404 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
405 case LangOptions::SOB_Defined:
406 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
407 case LangOptions::SOB_Trapping:
408 return EmitOverflowCheckedBinOp(Ops);
409 }
410 }
411
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000412 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000413 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000414 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
415 }
Chris Lattner80230302010-09-11 21:47:09 +0000416 bool isTrapvOverflowBehavior() {
417 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
418 == LangOptions::SOB_Trapping;
419 }
Mike Stump2add4732009-04-01 20:28:16 +0000420 /// Create a binary op that checks for overflow.
421 /// Currently only supports +, - and *.
422 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000423 // Emit the overflow BB when -ftrapv option is activated.
424 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
425 Builder.SetInsertPoint(overflowBB);
426 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
427 Builder.CreateCall(Trap);
428 Builder.CreateUnreachable();
429 }
430 // Check for undefined division and modulus behaviors.
431 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
432 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000433 Value *EmitDiv(const BinOpInfo &Ops);
434 Value *EmitRem(const BinOpInfo &Ops);
435 Value *EmitAdd(const BinOpInfo &Ops);
436 Value *EmitSub(const BinOpInfo &Ops);
437 Value *EmitShl(const BinOpInfo &Ops);
438 Value *EmitShr(const BinOpInfo &Ops);
439 Value *EmitAnd(const BinOpInfo &Ops) {
440 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
441 }
442 Value *EmitXor(const BinOpInfo &Ops) {
443 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
444 }
445 Value *EmitOr (const BinOpInfo &Ops) {
446 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
447 }
448
Chris Lattner1f1ded92007-08-24 21:00:35 +0000449 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000450 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
451 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000452 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000453
Chris Lattner3ccf7742007-08-26 21:41:21 +0000454 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000455 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
456
457 // Binary operators and binary compound assignment operators.
458#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000459 Value *VisitBin ## OP(const BinaryOperator *E) { \
460 return Emit ## OP(EmitBinOps(E)); \
461 } \
462 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
463 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000464 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000465 HANDLEBINOP(Mul)
466 HANDLEBINOP(Div)
467 HANDLEBINOP(Rem)
468 HANDLEBINOP(Add)
469 HANDLEBINOP(Sub)
470 HANDLEBINOP(Shl)
471 HANDLEBINOP(Shr)
472 HANDLEBINOP(And)
473 HANDLEBINOP(Xor)
474 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000475#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000476
Chris Lattner7f02f722007-08-24 05:35:26 +0000477 // Comparisons.
478 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
479 unsigned SICmpOpc, unsigned FCmpOpc);
480#define VISITCOMP(CODE, UI, SI, FP) \
481 Value *VisitBin##CODE(const BinaryOperator *E) { \
482 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
483 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000484 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
485 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
486 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
487 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
488 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
489 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000490#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000491
Chris Lattner7f02f722007-08-24 05:35:26 +0000492 Value *VisitBinAssign (const BinaryOperator *E);
493
494 Value *VisitBinLAnd (const BinaryOperator *E);
495 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000496 Value *VisitBinComma (const BinaryOperator *E);
497
Eli Friedman25b825d2009-11-18 09:41:26 +0000498 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
499 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
500
Chris Lattner7f02f722007-08-24 05:35:26 +0000501 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000502 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000503 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000504 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000505 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000506 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
507 return CGF.EmitObjCStringLiteral(E);
508 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000509 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000510};
511} // end anonymous namespace.
512
513//===----------------------------------------------------------------------===//
514// Utilities
515//===----------------------------------------------------------------------===//
516
Chris Lattner9abc84e2007-08-26 16:42:57 +0000517/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000518/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000519Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000520 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000521
John McCalldaa8e4e2010-11-15 09:13:47 +0000522 if (SrcType->isRealFloatingType())
523 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000524
John McCall0bab0cd2010-08-23 01:21:21 +0000525 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
526 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000528 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000529 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000530
John McCalldaa8e4e2010-11-15 09:13:47 +0000531 if (isa<llvm::IntegerType>(Src->getType()))
532 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000533
John McCalldaa8e4e2010-11-15 09:13:47 +0000534 assert(isa<llvm::PointerType>(Src->getType()));
535 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000536}
537
Chris Lattner3707b252007-08-26 06:48:56 +0000538/// EmitScalarConversion - Emit a conversion from the specified type to the
539/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000540Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
541 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000542 SrcType = CGF.getContext().getCanonicalType(SrcType);
543 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000544 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000545
Chris Lattnercf289082007-08-26 07:21:11 +0000546 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000547
Chris Lattner3707b252007-08-26 06:48:56 +0000548 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000549 if (DstType->isBooleanType())
550 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000551
Chris Lattner3707b252007-08-26 06:48:56 +0000552 const llvm::Type *DstTy = ConvertType(DstType);
553
554 // Ignore conversions like int -> uint.
555 if (Src->getType() == DstTy)
556 return Src;
557
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000558 // Handle pointer conversions next: pointers can only be converted to/from
559 // other pointers and integers. Check for pointer types in terms of LLVM, as
560 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000561 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000562 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000563 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000564 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000565
Chris Lattner3707b252007-08-26 06:48:56 +0000566 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000567 // First, convert to the correct width so that we control the kind of
568 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000569 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000570 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000571 llvm::Value* IntResult =
572 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
573 // Then, cast to pointer.
574 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000575 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000576
Daniel Dunbar270cc662008-08-25 09:51:32 +0000577 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000578 // Must be an ptr to int cast.
579 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000580 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000581 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000582
Nate Begeman213541a2008-04-18 23:10:10 +0000583 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000584 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000585 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000586 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000587 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
588
589 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000590 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000591 llvm::Value *Idx = Builder.getInt32(0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000592 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
593
594 // Splat the element across to all elements
595 llvm::SmallVector<llvm::Constant*, 16> Args;
596 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000597 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +0000598 Args.push_back(Builder.getInt32(0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000599
Chris Lattnerfb018d12011-02-15 00:14:06 +0000600 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000601 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
602 return Yay;
603 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000604
Chris Lattner3b1ae002008-02-02 04:51:41 +0000605 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000606 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000607 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000608 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000609
Chris Lattner3707b252007-08-26 06:48:56 +0000610 // Finally, we have the arithmetic types: real int/float.
611 if (isa<llvm::IntegerType>(Src->getType())) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000612 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000613 if (isa<llvm::IntegerType>(DstTy))
614 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
615 else if (InputSigned)
616 return Builder.CreateSIToFP(Src, DstTy, "conv");
617 else
618 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000619 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000620
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000621 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000622 if (isa<llvm::IntegerType>(DstTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000623 if (DstType->isSignedIntegerOrEnumerationType())
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000624 return Builder.CreateFPToSI(Src, DstTy, "conv");
625 else
626 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000627 }
628
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000629 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000630 if (DstTy->getTypeID() < Src->getType()->getTypeID())
631 return Builder.CreateFPTrunc(Src, DstTy, "conv");
632 else
633 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000634}
635
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000636/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
637/// type to the specified destination type, where the destination type is an
638/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000639Value *ScalarExprEmitter::
640EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
641 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000642 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000643 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000644
Chris Lattnered70f0a2007-08-26 16:52:28 +0000645 // Handle conversions to bool first, they are special: comparisons against 0.
646 if (DstTy->isBooleanType()) {
647 // Complex != 0 -> (Real != 0) | (Imag != 0)
648 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
649 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
650 return Builder.CreateOr(Src.first, Src.second, "tobool");
651 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000652
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000653 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
654 // the imaginary part of the complex value is discarded and the value of the
655 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000656 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000657 return EmitScalarConversion(Src.first, SrcTy, DstTy);
658}
659
Anders Carlssona40a9f32010-05-22 17:45:10 +0000660Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000661 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
662 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
663
664 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000665}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000666
Chris Lattner7f02f722007-08-24 05:35:26 +0000667//===----------------------------------------------------------------------===//
668// Visitor Methods
669//===----------------------------------------------------------------------===//
670
671Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000672 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000673 if (E->getType()->isVoidType())
674 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000675 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000676}
677
Eli Friedmand38617c2008-05-14 19:38:39 +0000678Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000679 // Vector Mask Case
680 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000681 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000682 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
683 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
684 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000685
Nate Begeman37b6a572010-06-08 00:16:34 +0000686 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
687 unsigned LHSElts = LTy->getNumElements();
688
689 if (E->getNumSubExprs() == 3) {
690 Mask = CGF.EmitScalarExpr(E->getExpr(2));
691
692 // Shuffle LHS & RHS into one input vector.
693 llvm::SmallVector<llvm::Constant*, 32> concat;
694 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000695 concat.push_back(Builder.getInt32(2*i));
696 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000697 }
698
Chris Lattnerfb018d12011-02-15 00:14:06 +0000699 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000700 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
701 LHSElts *= 2;
702 } else {
703 Mask = RHS;
704 }
705
706 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
707 llvm::Constant* EltMask;
708
709 // Treat vec3 like vec4.
710 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
711 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
712 (1 << llvm::Log2_32(LHSElts+2))-1);
713 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
714 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
715 (1 << llvm::Log2_32(LHSElts+1))-1);
716 else
717 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
718 (1 << llvm::Log2_32(LHSElts))-1);
719
720 // Mask off the high bits of each shuffle index.
721 llvm::SmallVector<llvm::Constant *, 32> MaskV;
722 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
723 MaskV.push_back(EltMask);
724
Chris Lattnerfb018d12011-02-15 00:14:06 +0000725 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000726 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
727
728 // newv = undef
729 // mask = mask & maskbits
730 // for each elt
731 // n = extract mask i
732 // x = extract val n
733 // newv = insert newv, x, i
734 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
735 MTy->getNumElements());
736 Value* NewV = llvm::UndefValue::get(RTy);
737 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000738 Value *Indx = Builder.getInt32(i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000739 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000740 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000741
742 // Handle vec3 special since the index will be off by one for the RHS.
743 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
744 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000745 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000746 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000747 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000748 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
749 }
750 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
751 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
752 }
753 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000754 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000755
Eli Friedmand38617c2008-05-14 19:38:39 +0000756 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
757 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000758
759 // Handle vec3 special since the index will be off by one for the RHS.
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000760 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000761 llvm::SmallVector<llvm::Constant*, 32> indices;
762 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000763 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
764 if (VTy->getNumElements() == 3 && Idx > 3)
765 Idx -= 1;
766 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000767 }
768
Chris Lattnerfb018d12011-02-15 00:14:06 +0000769 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000770 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
771}
Eli Friedman28665272009-11-26 03:22:21 +0000772Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
773 Expr::EvalResult Result;
774 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
775 if (E->isArrow())
776 CGF.EmitScalarExpr(E->getBase());
777 else
778 EmitLValue(E->getBase());
Chris Lattner48431f92011-04-19 22:55:03 +0000779 return Builder.getInt(Result.Val.getInt());
Eli Friedman28665272009-11-26 03:22:21 +0000780 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000781
782 // Emit debug info for aggregate now, if it was delayed to reduce
783 // debug info size.
784 CGDebugInfo *DI = CGF.getDebugInfo();
785 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
786 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
787 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000788 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000789 DI->getOrCreateRecordType(PTy->getPointeeType(),
790 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000791 }
Eli Friedman28665272009-11-26 03:22:21 +0000792 return EmitLoadOfLValue(E);
793}
Eli Friedmand38617c2008-05-14 19:38:39 +0000794
Chris Lattner7f02f722007-08-24 05:35:26 +0000795Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000796 TestAndClearIgnoreResultAssign();
797
Chris Lattner7f02f722007-08-24 05:35:26 +0000798 // Emit subscript expressions in rvalue context's. For most cases, this just
799 // loads the lvalue formed by the subscript expr. However, we have to be
800 // careful, because the base of a vector subscript is occasionally an rvalue,
801 // so we can't get it as an lvalue.
802 if (!E->getBase()->getType()->isVectorType())
803 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000804
Chris Lattner7f02f722007-08-24 05:35:26 +0000805 // Handle the vector case. The base must be a vector, the index must be an
806 // integer value.
807 Value *Base = Visit(E->getBase());
808 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000809 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000810 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000811 return Builder.CreateExtractElement(Base, Idx, "vecext");
812}
813
Nate Begeman0533b302009-10-18 20:10:40 +0000814static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
815 unsigned Off, const llvm::Type *I32Ty) {
816 int MV = SVI->getMaskValue(Idx);
817 if (MV == -1)
818 return llvm::UndefValue::get(I32Ty);
819 return llvm::ConstantInt::get(I32Ty, Off+MV);
820}
821
822Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
823 bool Ignore = TestAndClearIgnoreResultAssign();
824 (void)Ignore;
825 assert (Ignore == false && "init list ignored");
826 unsigned NumInitElements = E->getNumInits();
827
828 if (E->hadArrayRangeDesignator())
829 CGF.ErrorUnsupported(E, "GNU array range designator extension");
830
831 const llvm::VectorType *VType =
832 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
833
834 // We have a scalar in braces. Just use the first element.
835 if (!VType)
836 return Visit(E->getInit(0));
837
838 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000839
840 // Loop over initializers collecting the Value for each, and remembering
841 // whether the source was swizzle (ExtVectorElementExpr). This will allow
842 // us to fold the shuffle for the swizzle into the shuffle for the vector
843 // initializer, since LLVM optimizers generally do not want to touch
844 // shuffles.
845 unsigned CurIdx = 0;
846 bool VIsUndefShuffle = false;
847 llvm::Value *V = llvm::UndefValue::get(VType);
848 for (unsigned i = 0; i != NumInitElements; ++i) {
849 Expr *IE = E->getInit(i);
850 Value *Init = Visit(IE);
851 llvm::SmallVector<llvm::Constant*, 16> Args;
852
853 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
854
855 // Handle scalar elements. If the scalar initializer is actually one
856 // element of a different vector of the same width, use shuffle instead of
857 // extract+insert.
858 if (!VVT) {
859 if (isa<ExtVectorElementExpr>(IE)) {
860 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
861
862 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
863 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
864 Value *LHS = 0, *RHS = 0;
865 if (CurIdx == 0) {
866 // insert into undef -> shuffle (src, undef)
867 Args.push_back(C);
868 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000869 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000870
871 LHS = EI->getVectorOperand();
872 RHS = V;
873 VIsUndefShuffle = true;
874 } else if (VIsUndefShuffle) {
875 // insert into undefshuffle && size match -> shuffle (v, src)
876 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
877 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000878 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000879 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Nate Begeman0533b302009-10-18 20:10:40 +0000880 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000881 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000882
883 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
884 RHS = EI->getVectorOperand();
885 VIsUndefShuffle = false;
886 }
887 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000888 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000889 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
890 ++CurIdx;
891 continue;
892 }
893 }
894 }
Chris Lattner48431f92011-04-19 22:55:03 +0000895 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
896 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000897 VIsUndefShuffle = false;
898 ++CurIdx;
899 continue;
900 }
901
902 unsigned InitElts = VVT->getNumElements();
903
904 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
905 // input is the same width as the vector being constructed, generate an
906 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000907 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000908 if (isa<ExtVectorElementExpr>(IE)) {
909 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
910 Value *SVOp = SVI->getOperand(0);
911 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
912
913 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000914 for (unsigned j = 0; j != CurIdx; ++j) {
915 // If the current vector initializer is a shuffle with undef, merge
916 // this shuffle directly into it.
917 if (VIsUndefShuffle) {
918 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000919 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000920 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000921 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000922 }
923 }
924 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000925 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000926 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000927 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000928
929 if (VIsUndefShuffle)
930 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
931
932 Init = SVOp;
933 }
934 }
935
936 // Extend init to result vector length, and then shuffle its contribution
937 // to the vector initializer into V.
938 if (Args.empty()) {
939 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000940 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000941 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000942 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000943 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000944 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000945 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000946
947 Args.clear();
948 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000949 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000950 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000951 Args.push_back(Builder.getInt32(j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000952 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000953 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000954 }
955
956 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
957 // merging subsequent shuffles into this one.
958 if (CurIdx == 0)
959 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000960 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000961 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
962 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
963 CurIdx += InitElts;
964 }
965
966 // FIXME: evaluate codegen vs. shuffling against constant null vector.
967 // Emit remaining default initializers.
968 const llvm::Type *EltTy = VType->getElementType();
969
970 // Emit remaining default initializers
971 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000972 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000973 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
974 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
975 }
976 return V;
977}
978
Anders Carlssona3697c92009-11-23 17:57:54 +0000979static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
980 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000981
John McCall2de56d12010-08-25 11:45:40 +0000982 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000983 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000984
985 if (isa<CXXThisExpr>(E)) {
986 // We always assume that 'this' is never null.
987 return false;
988 }
989
990 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000991 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000992 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000993 return false;
994 }
995
996 return true;
997}
998
Chris Lattner7f02f722007-08-24 05:35:26 +0000999// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1000// have to handle a more broad range of conversions than explicit casts, as they
1001// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001002Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001003 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001004 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001005 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001006
Mike Stump7f79f9b2009-05-29 15:46:01 +00001007 if (!DestTy->isVoidType())
1008 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001009
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001010 // Since almost all cast kinds apply to scalars, this switch doesn't have
1011 // a default case, so the compiler will warn on a missing case. The cases
1012 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001013 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001014 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1015
John McCall2de56d12010-08-25 11:45:40 +00001016 case CK_LValueBitCast:
1017 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001018 Value *V = EmitLValue(E).getAddress();
1019 V = Builder.CreateBitCast(V,
1020 ConvertType(CGF.getContext().getPointerType(DestTy)));
John McCall545d9962011-06-25 02:11:03 +00001021 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001022 }
1023
John McCall2de56d12010-08-25 11:45:40 +00001024 case CK_AnyPointerToObjCPointerCast:
1025 case CK_AnyPointerToBlockPointerCast:
1026 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001027 Value *Src = Visit(const_cast<Expr*>(E));
1028 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1029 }
John McCall2de56d12010-08-25 11:45:40 +00001030 case CK_NoOp:
1031 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001032 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001033
John McCall2de56d12010-08-25 11:45:40 +00001034 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001035 const CXXRecordDecl *DerivedClassDecl =
1036 DestTy->getCXXRecordDeclForPointerType();
1037
Anders Carlssona04efdf2010-04-24 21:23:59 +00001038 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001039 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001040 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001041 }
John McCall2de56d12010-08-25 11:45:40 +00001042 case CK_UncheckedDerivedToBase:
1043 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001044 const RecordType *DerivedClassTy =
1045 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1046 CXXRecordDecl *DerivedClassDecl =
1047 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1048
Anders Carlsson34a2d382010-04-24 21:06:20 +00001049 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001050 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001051 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001052 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001053 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001054 Value *V = Visit(const_cast<Expr*>(E));
1055 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1056 return CGF.EmitDynamicCast(V, DCE);
1057 }
Eli Friedmand8889622009-11-27 04:41:50 +00001058
John McCall2de56d12010-08-25 11:45:40 +00001059 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001060 assert(E->getType()->isArrayType() &&
1061 "Array to pointer decay must have array source type!");
1062
1063 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1064
1065 // Note that VLA pointers are always decayed, so we don't need to do
1066 // anything here.
1067 if (!E->getType()->isVariableArrayType()) {
1068 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1069 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1070 ->getElementType()) &&
1071 "Expected pointer to array");
1072 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1073 }
1074
1075 return V;
1076 }
John McCall2de56d12010-08-25 11:45:40 +00001077 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001078 return EmitLValue(E).getAddress();
1079
John McCall404cd162010-11-13 01:35:44 +00001080 case CK_NullToPointer:
1081 if (MustVisitNullValue(E))
1082 (void) Visit(E);
1083
1084 return llvm::ConstantPointerNull::get(
1085 cast<llvm::PointerType>(ConvertType(DestTy)));
1086
John McCall2de56d12010-08-25 11:45:40 +00001087 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001088 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001089 (void) Visit(E);
1090
John McCall0bab0cd2010-08-23 01:21:21 +00001091 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1092 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1093 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001094
John McCall2de56d12010-08-25 11:45:40 +00001095 case CK_BaseToDerivedMemberPointer:
1096 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001097 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001098
1099 // Note that the AST doesn't distinguish between checked and
1100 // unchecked member pointer conversions, so we always have to
1101 // implement checked conversions here. This is inefficient when
1102 // actual control flow may be required in order to perform the
1103 // check, which it is for data member pointers (but not member
1104 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001105 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001106 }
John McCallf85e1932011-06-15 23:02:42 +00001107
1108 case CK_ObjCProduceObject:
1109 return CGF.EmitARCRetainScalarExpr(E);
1110 case CK_ObjCConsumeObject:
1111 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1112
John McCall2bb5d002010-11-13 09:02:35 +00001113 case CK_FloatingRealToComplex:
1114 case CK_FloatingComplexCast:
1115 case CK_IntegralRealToComplex:
1116 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001117 case CK_IntegralComplexToFloatingComplex:
1118 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001119 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001120 case CK_ToUnion:
1121 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001122 break;
John McCallf6a16482010-12-04 03:47:34 +00001123
1124 case CK_GetObjCProperty: {
1125 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001126 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001127 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
John McCall545d9962011-06-25 02:11:03 +00001128 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E));
John McCallf6a16482010-12-04 03:47:34 +00001129 return RV.getScalarVal();
1130 }
John McCall1de4d4e2011-04-07 08:22:57 +00001131
John McCall0ae287a2010-12-01 04:43:34 +00001132 case CK_LValueToRValue:
1133 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001134 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001135 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001136
John McCall2de56d12010-08-25 11:45:40 +00001137 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001138 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001139
Anders Carlsson82debc72009-10-18 18:12:03 +00001140 // First, convert to the correct width so that we control the kind of
1141 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001142 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001143 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001144 llvm::Value* IntResult =
1145 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001146
Anders Carlsson82debc72009-10-18 18:12:03 +00001147 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001148 }
Eli Friedman65949422011-06-25 02:58:47 +00001149 case CK_PointerToIntegral:
1150 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1151 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001152
John McCall2de56d12010-08-25 11:45:40 +00001153 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001154 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001155 return 0;
1156 }
John McCall2de56d12010-08-25 11:45:40 +00001157 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001158 const llvm::Type *DstTy = ConvertType(DestTy);
1159 Value *Elt = Visit(const_cast<Expr*>(E));
1160
1161 // Insert the element in element zero of an undef vector
1162 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001163 llvm::Value *Idx = Builder.getInt32(0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001164 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1165
1166 // Splat the element across to all elements
1167 llvm::SmallVector<llvm::Constant*, 16> Args;
1168 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001169 llvm::Constant *Zero = Builder.getInt32(0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001170 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001171 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001172
Chris Lattnerfb018d12011-02-15 00:14:06 +00001173 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001174 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1175 return Yay;
1176 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001177
John McCall2de56d12010-08-25 11:45:40 +00001178 case CK_IntegralCast:
1179 case CK_IntegralToFloating:
1180 case CK_FloatingToIntegral:
1181 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001182 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001183
John McCalldaa8e4e2010-11-15 09:13:47 +00001184 case CK_IntegralToBoolean:
1185 return EmitIntToBoolConversion(Visit(E));
1186 case CK_PointerToBoolean:
1187 return EmitPointerToBoolConversion(Visit(E));
1188 case CK_FloatingToBoolean:
1189 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001190 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001191 llvm::Value *MemPtr = Visit(E);
1192 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1193 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001194 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001195
1196 case CK_FloatingComplexToReal:
1197 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001198 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001199
1200 case CK_FloatingComplexToBoolean:
1201 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001202 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001203
1204 // TODO: kill this function off, inline appropriate case here
1205 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1206 }
1207
John McCall0bab0cd2010-08-23 01:21:21 +00001208 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001209
John McCall61ad0e62010-11-16 06:21:14 +00001210 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001211 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001212}
1213
Chris Lattner33793202007-08-31 22:09:40 +00001214Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001215 CodeGenFunction::StmtExprEvaluation eval(CGF);
1216 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1217 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001218}
1219
Mike Stumpa99038c2009-02-28 09:07:16 +00001220Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
John McCalla5bcb8f2011-03-16 02:53:38 +00001221 LValue LV = CGF.EmitBlockDeclRefLValue(E);
John McCall545d9962011-06-25 02:11:03 +00001222 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Mike Stump4e7a1f72009-02-21 20:00:35 +00001223}
Chris Lattner33793202007-08-31 22:09:40 +00001224
Chris Lattner7f02f722007-08-24 05:35:26 +00001225//===----------------------------------------------------------------------===//
1226// Unary Operators
1227//===----------------------------------------------------------------------===//
1228
Chris Lattner8c11a652010-06-26 22:09:34 +00001229llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001230EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1231 llvm::Value *InVal,
1232 llvm::Value *NextVal, bool IsInc) {
1233 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1234 case LangOptions::SOB_Undefined:
1235 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1236 break;
1237 case LangOptions::SOB_Defined:
1238 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1239 break;
1240 case LangOptions::SOB_Trapping:
1241 BinOpInfo BinOp;
1242 BinOp.LHS = InVal;
1243 BinOp.RHS = NextVal;
1244 BinOp.Ty = E->getType();
1245 BinOp.Opcode = BO_Add;
1246 BinOp.E = E;
1247 return EmitOverflowCheckedBinOp(BinOp);
1248 break;
1249 }
1250 assert(false && "Unknown SignedOverflowBehaviorTy");
1251 return 0;
1252}
1253
John McCall5936e332011-02-15 09:22:45 +00001254llvm::Value *
1255ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1256 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001257
John McCall5936e332011-02-15 09:22:45 +00001258 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001259 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001260 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001261
John McCall5936e332011-02-15 09:22:45 +00001262 int amount = (isInc ? 1 : -1);
1263
1264 // Special case of integer increment that we have to check first: bool++.
1265 // Due to promotion rules, we get:
1266 // bool++ -> bool = bool + 1
1267 // -> bool = (int)bool + 1
1268 // -> bool = ((int)bool + 1 != 0)
1269 // An interesting aspect of this is that increment is always true.
1270 // Decrement does not have this property.
1271 if (isInc && type->isBooleanType()) {
1272 value = Builder.getTrue();
1273
1274 // Most common case by far: integer increment.
1275 } else if (type->isIntegerType()) {
1276
1277 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1278
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001279 // Note that signed integer inc/dec with width less than int can't
1280 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001281 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001282 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001283 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001284 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001285 else
1286 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1287
1288 // Next most common: pointer increment.
1289 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1290 QualType type = ptr->getPointeeType();
1291
1292 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001293 if (const VariableArrayType *vla
1294 = CGF.getContext().getAsVariableArrayType(type)) {
1295 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001296 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Chris Lattner2cb42222011-03-01 00:03:48 +00001297 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001298 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001299 else
John McCallbc8d40d2011-06-24 21:55:10 +00001300 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001301
1302 // Arithmetic on function pointers (!) is just +-1.
1303 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001304 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001305
1306 value = CGF.EmitCastToVoidPtr(value);
Chris Lattner2cb42222011-03-01 00:03:48 +00001307 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1308 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1309 else
1310 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001311 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 {
Chris Lattner48431f92011-04-19 22:55:03 +00001315 llvm::Value *amt = Builder.getInt32(amount);
Chris Lattner2cb42222011-03-01 00:03:48 +00001316 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1317 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1318 else
1319 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001320 }
1321
1322 // Vector increment/decrement.
1323 } else if (type->isVectorType()) {
1324 if (type->hasIntegerRepresentation()) {
1325 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1326
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001327 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001328 } 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
Chris Lattner2cb42222011-03-01 00:03:48 +00001364 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1365 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1366 else
1367 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001368 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001369 }
1370
1371 // Store the updated result through the lvalue.
1372 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001373 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001374 else
John McCall545d9962011-06-25 02:11:03 +00001375 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Chris Lattner8c11a652010-06-26 22:09:34 +00001376
1377 // If this is a postinc, return the value read from memory, otherwise use the
1378 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001379 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001380}
1381
1382
1383
Chris Lattner7f02f722007-08-24 05:35:26 +00001384Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001385 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001386 // Emit unary minus with EmitSub so we handle overflow cases etc.
1387 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001388 BinOp.RHS = Visit(E->getSubExpr());
1389
1390 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1391 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1392 else
1393 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001394 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001395 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001396 BinOp.E = E;
1397 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001398}
1399
1400Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001401 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001402 Value *Op = Visit(E->getSubExpr());
1403 return Builder.CreateNot(Op, "neg");
1404}
1405
1406Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1407 // Compare operand to zero.
1408 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001409
Chris Lattner7f02f722007-08-24 05:35:26 +00001410 // Invert value.
1411 // TODO: Could dynamically modify easy computations here. For example, if
1412 // the operand is an icmp ne, turn into icmp eq.
1413 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001414
Anders Carlsson9f84d882009-05-19 18:44:53 +00001415 // ZExt result to the expr type.
1416 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001417}
1418
Eli Friedman0027d2b2010-08-05 09:58:49 +00001419Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1420 // Try folding the offsetof to a constant.
1421 Expr::EvalResult EvalResult;
1422 if (E->Evaluate(EvalResult, CGF.getContext()))
Chris Lattner48431f92011-04-19 22:55:03 +00001423 return Builder.getInt(EvalResult.Val.getInt());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001424
1425 // Loop over the components of the offsetof to compute the value.
1426 unsigned n = E->getNumComponents();
1427 const llvm::Type* ResultType = ConvertType(E->getType());
1428 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1429 QualType CurrentType = E->getTypeSourceInfo()->getType();
1430 for (unsigned i = 0; i != n; ++i) {
1431 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001432 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001433 switch (ON.getKind()) {
1434 case OffsetOfExpr::OffsetOfNode::Array: {
1435 // Compute the index
1436 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1437 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001438 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001439 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1440
1441 // Save the element type
1442 CurrentType =
1443 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1444
1445 // Compute the element size
1446 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1447 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1448
1449 // Multiply out to compute the result
1450 Offset = Builder.CreateMul(Idx, ElemSize);
1451 break;
1452 }
1453
1454 case OffsetOfExpr::OffsetOfNode::Field: {
1455 FieldDecl *MemberDecl = ON.getField();
1456 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1457 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1458
1459 // Compute the index of the field in its parent.
1460 unsigned i = 0;
1461 // FIXME: It would be nice if we didn't have to loop here!
1462 for (RecordDecl::field_iterator Field = RD->field_begin(),
1463 FieldEnd = RD->field_end();
1464 Field != FieldEnd; (void)++Field, ++i) {
1465 if (*Field == MemberDecl)
1466 break;
1467 }
1468 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1469
1470 // Compute the offset to the field
1471 int64_t OffsetInt = RL.getFieldOffset(i) /
1472 CGF.getContext().getCharWidth();
1473 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1474
1475 // Save the element type.
1476 CurrentType = MemberDecl->getType();
1477 break;
1478 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001479
Eli Friedman0027d2b2010-08-05 09:58:49 +00001480 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001481 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001482
Eli Friedman0027d2b2010-08-05 09:58:49 +00001483 case OffsetOfExpr::OffsetOfNode::Base: {
1484 if (ON.getBase()->isVirtual()) {
1485 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1486 continue;
1487 }
1488
1489 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1490 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1491
1492 // Save the element type.
1493 CurrentType = ON.getBase()->getType();
1494
1495 // Compute the offset to the base.
1496 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1497 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001498 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001499 CGF.getContext().getCharWidth();
1500 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1501 break;
1502 }
1503 }
1504 Result = Builder.CreateAdd(Result, Offset);
1505 }
1506 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001507}
1508
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001509/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001510/// argument of the sizeof expression as an integer.
1511Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001512ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1513 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001514 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001515 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001516 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001517 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1518 if (E->isArgumentType()) {
1519 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001520 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001521 } else {
1522 // C99 6.5.3.4p2: If the argument is an expression of type
1523 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001524 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001525 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001526
John McCallbc8d40d2011-06-24 21:55:10 +00001527 QualType eltType;
1528 llvm::Value *numElts;
1529 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1530
1531 llvm::Value *size = numElts;
1532
1533 // Scale the number of non-VLA elements by the non-VLA element size.
1534 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1535 if (!eltSize.isOne())
1536 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1537
1538 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001539 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001540 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001541
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001542 // If this isn't sizeof(vla), the result must be constant; use the constant
1543 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001544 Expr::EvalResult Result;
1545 E->Evaluate(Result, CGF.getContext());
Chris Lattner48431f92011-04-19 22:55:03 +00001546 return Builder.getInt(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001547}
1548
Chris Lattner46f93d02007-08-24 21:20:17 +00001549Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1550 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001551 if (Op->getType()->isAnyComplexType()) {
1552 // If it's an l-value, load through the appropriate subobject l-value.
1553 // Note that we have to ask E because Op might be an l-value that
1554 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001555 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001556 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001557
1558 // Otherwise, calculate and project.
1559 return CGF.EmitComplexExpr(Op, false, true).first;
1560 }
1561
Chris Lattner46f93d02007-08-24 21:20:17 +00001562 return Visit(Op);
1563}
John McCallb418d742010-11-16 10:08:07 +00001564
Chris Lattner46f93d02007-08-24 21:20:17 +00001565Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1566 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001567 if (Op->getType()->isAnyComplexType()) {
1568 // If it's an l-value, load through the appropriate subobject l-value.
1569 // Note that we have to ask E because Op might be an l-value that
1570 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001571 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001572 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001573
1574 // Otherwise, calculate and project.
1575 return CGF.EmitComplexExpr(Op, true, false).second;
1576 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001577
Mike Stump7f79f9b2009-05-29 15:46:01 +00001578 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1579 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001580 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001581 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001582}
1583
Chris Lattner7f02f722007-08-24 05:35:26 +00001584//===----------------------------------------------------------------------===//
1585// Binary Operators
1586//===----------------------------------------------------------------------===//
1587
1588BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001589 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001590 BinOpInfo Result;
1591 Result.LHS = Visit(E->getLHS());
1592 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001593 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001594 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001595 Result.E = E;
1596 return Result;
1597}
1598
Douglas Gregor6a03e342010-04-23 04:16:32 +00001599LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1600 const CompoundAssignOperator *E,
1601 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001602 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001603 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001604 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001605
Eli Friedmanab3a8522009-03-28 01:22:36 +00001606 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001607 // This needs to go through the complex expression emitter, but it's a tad
1608 // complicated to do that... I'm leaving it out for now. (Note that we do
1609 // actually need the imaginary part of the RHS for multiplication and
1610 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001611 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001612 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001613 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001614 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001615
Mike Stumpcc0442f2009-05-22 19:07:20 +00001616 // Emit the RHS first. __block variables need to have the rhs evaluated
1617 // first, plus this should improve codegen a little.
1618 OpInfo.RHS = Visit(E->getRHS());
1619 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001620 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001621 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001622 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001623 LValue LHSLV = EmitCheckedLValue(E->getLHS());
John McCall545d9962011-06-25 02:11:03 +00001624 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001625 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1626 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001627
Chris Lattner1f1ded92007-08-24 21:00:35 +00001628 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001629 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001630
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001631 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001632 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001633
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001634 // Store the result value into the LHS lvalue. Bit-fields are handled
1635 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1636 // 'An assignment expression has the value of the left operand after the
1637 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001638 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001639 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001640 else
John McCall545d9962011-06-25 02:11:03 +00001641 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001642
Douglas Gregor6a03e342010-04-23 04:16:32 +00001643 return LHSLV;
1644}
1645
1646Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1647 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1648 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001649 Value *RHS;
1650 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1651
1652 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001653 if (Ignore)
1654 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001655
John McCallb418d742010-11-16 10:08:07 +00001656 // The result of an assignment in C is the assigned r-value.
1657 if (!CGF.getContext().getLangOptions().CPlusPlus)
1658 return RHS;
1659
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001660 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001661 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001662 return RHS;
1663
1664 // If the lvalue is non-volatile, return the computed value of the assignment.
1665 if (!LHS.isVolatileQualified())
1666 return RHS;
1667
1668 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001669 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001670}
1671
Chris Lattner80230302010-09-11 21:47:09 +00001672void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1673 const BinOpInfo &Ops,
1674 llvm::Value *Zero, bool isDiv) {
1675 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1676 llvm::BasicBlock *contBB =
1677 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1678
1679 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1680
1681 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1682 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001683 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001684 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1685
1686 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1687 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1688 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1689 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1690 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1691 overflowBB, contBB);
1692 } else {
1693 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1694 overflowBB, contBB);
1695 }
1696 EmitOverflowBB(overflowBB);
1697 Builder.SetInsertPoint(contBB);
1698}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001699
Chris Lattner7f02f722007-08-24 05:35:26 +00001700Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001701 if (isTrapvOverflowBehavior()) {
1702 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1703
1704 if (Ops.Ty->isIntegerType())
1705 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1706 else if (Ops.Ty->isRealFloatingType()) {
1707 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1708 CGF.CurFn);
1709 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1710 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1711 overflowBB, DivCont);
1712 EmitOverflowBB(overflowBB);
1713 Builder.SetInsertPoint(DivCont);
1714 }
1715 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001716 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001717 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001718 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001719 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1720 else
1721 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1722}
1723
1724Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1725 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001726 if (isTrapvOverflowBehavior()) {
1727 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1728
1729 if (Ops.Ty->isIntegerType())
1730 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1731 }
1732
Eli Friedman52d68742011-04-10 04:44:11 +00001733 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001734 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1735 else
1736 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1737}
1738
Mike Stump2add4732009-04-01 20:28:16 +00001739Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1740 unsigned IID;
1741 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001742
Chris Lattner9a207232010-06-26 21:48:21 +00001743 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001744 case BO_Add:
1745 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001746 OpID = 1;
1747 IID = llvm::Intrinsic::sadd_with_overflow;
1748 break;
John McCall2de56d12010-08-25 11:45:40 +00001749 case BO_Sub:
1750 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001751 OpID = 2;
1752 IID = llvm::Intrinsic::ssub_with_overflow;
1753 break;
John McCall2de56d12010-08-25 11:45:40 +00001754 case BO_Mul:
1755 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001756 OpID = 3;
1757 IID = llvm::Intrinsic::smul_with_overflow;
1758 break;
1759 default:
1760 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001761 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001762 }
Mike Stump035cf892009-04-02 18:15:54 +00001763 OpID <<= 1;
1764 OpID |= 1;
1765
Mike Stump2add4732009-04-01 20:28:16 +00001766 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1767
1768 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1769
1770 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1771 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1772 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1773
1774 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001775 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Chris Lattner93a00352010-08-07 00:20:46 +00001776 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1777 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001778
1779 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1780
Chris Lattner93a00352010-08-07 00:20:46 +00001781 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001782 const std::string *handlerName =
1783 &CGF.getContext().getLangOptions().OverflowHandler;
1784 if (handlerName->empty()) {
1785 EmitOverflowBB(overflowBB);
1786 Builder.SetInsertPoint(continueBB);
1787 return result;
1788 }
1789
1790 // If an overflow handler is set, then we want to call it and then use its
1791 // result, if it returns.
1792 Builder.SetInsertPoint(overflowBB);
1793
1794 // Get the overflow handler.
1795 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00001796 const llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001797 llvm::FunctionType *handlerTy =
1798 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1799 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1800
1801 // Sign extend the args to 64-bit, so that we can use the same handler for
1802 // all types of overflow.
1803 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1804 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1805
1806 // Call the handler with the two arguments, the operation, and the size of
1807 // the result.
1808 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1809 Builder.getInt8(OpID),
1810 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1811
1812 // Truncate the result back to the desired size.
1813 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1814 Builder.CreateBr(continueBB);
1815
Mike Stump2add4732009-04-01 20:28:16 +00001816 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001817 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001818 phi->addIncoming(result, initialBB);
1819 phi->addIncoming(handlerResult, overflowBB);
1820
1821 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001822}
Chris Lattner7f02f722007-08-24 05:35:26 +00001823
John McCall913dab22011-06-25 01:32:37 +00001824/// Emit pointer + index arithmetic.
1825static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1826 const BinOpInfo &op,
1827 bool isSubtraction) {
1828 // Must have binary (not unary) expr here. Unary pointer
1829 // increment/decrement doesn't use this path.
1830 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1831
1832 Value *pointer = op.LHS;
1833 Expr *pointerOperand = expr->getLHS();
1834 Value *index = op.RHS;
1835 Expr *indexOperand = expr->getRHS();
1836
1837 // In a subtraction, the LHS is always the pointer.
1838 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1839 std::swap(pointer, index);
1840 std::swap(pointerOperand, indexOperand);
1841 }
1842
1843 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1844 if (width != CGF.PointerWidthInBits) {
1845 // Zero-extend or sign-extend the pointer value according to
1846 // whether the index is signed or not.
1847 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1848 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1849 "idx.ext");
1850 }
1851
1852 // If this is subtraction, negate the index.
1853 if (isSubtraction)
1854 index = CGF.Builder.CreateNeg(index, "idx.neg");
1855
1856 const PointerType *pointerType
1857 = pointerOperand->getType()->getAs<PointerType>();
1858 if (!pointerType) {
1859 QualType objectType = pointerOperand->getType()
1860 ->castAs<ObjCObjectPointerType>()
1861 ->getPointeeType();
1862 llvm::Value *objectSize
1863 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1864
1865 index = CGF.Builder.CreateMul(index, objectSize);
1866
1867 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1868 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1869 return CGF.Builder.CreateBitCast(result, pointer->getType());
1870 }
1871
1872 QualType elementType = pointerType->getPointeeType();
1873 if (const VariableArrayType *vla
1874 = CGF.getContext().getAsVariableArrayType(elementType)) {
1875 // The element count here is the total number of non-VLA elements.
1876 llvm::Value *numElements = CGF.getVLASize(vla).first;
1877
1878 // Effectively, the multiply by the VLA size is part of the GEP.
1879 // GEP indexes are signed, and scaling an index isn't permitted to
1880 // signed-overflow, so we use the same semantics for our explicit
1881 // multiply. We suppress this if overflow is not undefined behavior.
1882 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1883 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1884 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1885 } else {
1886 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1887 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001888 }
John McCall913dab22011-06-25 01:32:37 +00001889 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001890 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001891
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001892 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1893 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1894 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001895 if (elementType->isVoidType() || elementType->isFunctionType()) {
1896 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1897 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1898 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001899 }
1900
John McCall913dab22011-06-25 01:32:37 +00001901 if (CGF.getLangOptions().isSignedOverflowDefined())
1902 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1903
1904 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001905}
1906
John McCall913dab22011-06-25 01:32:37 +00001907Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1908 if (op.LHS->getType()->isPointerTy() ||
1909 op.RHS->getType()->isPointerTy())
1910 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1911
1912 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1913 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1914 case LangOptions::SOB_Undefined:
1915 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1916 case LangOptions::SOB_Defined:
1917 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1918 case LangOptions::SOB_Trapping:
1919 return EmitOverflowCheckedBinOp(op);
1920 }
1921 }
1922
1923 if (op.LHS->getType()->isFPOrFPVectorTy())
1924 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
1925
1926 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1927}
1928
1929Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
1930 // The LHS is always a pointer if either side is.
1931 if (!op.LHS->getType()->isPointerTy()) {
1932 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001933 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1934 case LangOptions::SOB_Undefined:
John McCall913dab22011-06-25 01:32:37 +00001935 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001936 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00001937 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001938 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00001939 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00001940 }
1941 }
1942
John McCall913dab22011-06-25 01:32:37 +00001943 if (op.LHS->getType()->isFPOrFPVectorTy())
1944 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001945
John McCall913dab22011-06-25 01:32:37 +00001946 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001947 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001948
John McCall913dab22011-06-25 01:32:37 +00001949 // If the RHS is not a pointer, then we have normal pointer
1950 // arithmetic.
1951 if (!op.RHS->getType()->isPointerTy())
1952 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00001953
John McCall913dab22011-06-25 01:32:37 +00001954 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001955
John McCall913dab22011-06-25 01:32:37 +00001956 // Do the raw subtraction part.
1957 llvm::Value *LHS
1958 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
1959 llvm::Value *RHS
1960 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
1961 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00001962
John McCall913dab22011-06-25 01:32:37 +00001963 // Okay, figure out the element size.
1964 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1965 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001966
John McCall913dab22011-06-25 01:32:37 +00001967 llvm::Value *divisor = 0;
1968
1969 // For a variable-length array, this is going to be non-constant.
1970 if (const VariableArrayType *vla
1971 = CGF.getContext().getAsVariableArrayType(elementType)) {
1972 llvm::Value *numElements;
1973 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
1974
1975 divisor = numElements;
1976
1977 // Scale the number of non-VLA elements by the non-VLA element size.
1978 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
1979 if (!eltSize.isOne())
1980 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
1981
1982 // For everything elese, we can just compute it, safe in the
1983 // assumption that Sema won't let anything through that we can't
1984 // safely compute the size of.
1985 } else {
1986 CharUnits elementSize;
1987 // Handle GCC extension for pointer arithmetic on void* and
1988 // function pointer types.
1989 if (elementType->isVoidType() || elementType->isFunctionType())
1990 elementSize = CharUnits::One();
1991 else
1992 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1993
1994 // Don't even emit the divide for element size of 1.
1995 if (elementSize.isOne())
1996 return diffInChars;
1997
1998 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00001999 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002000
Chris Lattner2cb42222011-03-01 00:03:48 +00002001 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2002 // pointer difference in C is only defined in the case where both operands
2003 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002004 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002005}
2006
2007Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2008 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2009 // RHS to the same size as the LHS.
2010 Value *RHS = Ops.RHS;
2011 if (Ops.LHS->getType() != RHS->getType())
2012 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002013
Mike Stumpbe07f602009-12-14 21:58:14 +00002014 if (CGF.CatchUndefined
2015 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2016 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2017 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2018 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2019 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002020 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002021 CGF.EmitBlock(Cont);
2022 }
2023
Chris Lattner7f02f722007-08-24 05:35:26 +00002024 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2025}
2026
2027Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2028 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2029 // RHS to the same size as the LHS.
2030 Value *RHS = Ops.RHS;
2031 if (Ops.LHS->getType() != RHS->getType())
2032 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002033
Mike Stumpbe07f602009-12-14 21:58:14 +00002034 if (CGF.CatchUndefined
2035 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2036 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2037 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2038 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2039 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002040 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002041 CGF.EmitBlock(Cont);
2042 }
2043
Douglas Gregorf6094622010-07-23 15:58:24 +00002044 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002045 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2046 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2047}
2048
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002049enum IntrinsicType { VCMPEQ, VCMPGT };
2050// return corresponding comparison intrinsic for given vector type
2051static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2052 BuiltinType::Kind ElemKind) {
2053 switch (ElemKind) {
2054 default: assert(0 && "unexpected element type");
2055 case BuiltinType::Char_U:
2056 case BuiltinType::UChar:
2057 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2058 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2059 break;
2060 case BuiltinType::Char_S:
2061 case BuiltinType::SChar:
2062 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2063 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2064 break;
2065 case BuiltinType::UShort:
2066 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2067 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2068 break;
2069 case BuiltinType::Short:
2070 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2071 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2072 break;
2073 case BuiltinType::UInt:
2074 case BuiltinType::ULong:
2075 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2076 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2077 break;
2078 case BuiltinType::Int:
2079 case BuiltinType::Long:
2080 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2081 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2082 break;
2083 case BuiltinType::Float:
2084 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2085 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2086 break;
2087 }
2088 return llvm::Intrinsic::not_intrinsic;
2089}
2090
Chris Lattner7f02f722007-08-24 05:35:26 +00002091Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2092 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002093 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002094 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002095 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002096 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002097 assert(E->getOpcode() == BO_EQ ||
2098 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002099 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2100 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002101 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002102 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002103 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002104 Value *LHS = Visit(E->getLHS());
2105 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002106
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002107 // If AltiVec, the comparison results in a numeric type, so we use
2108 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002109 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002110 // constants for mapping CR6 register bits to predicate result
2111 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2112
2113 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2114
2115 // in several cases vector arguments order will be reversed
2116 Value *FirstVecArg = LHS,
2117 *SecondVecArg = RHS;
2118
2119 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002120 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002121 BuiltinType::Kind ElementKind = BTy->getKind();
2122
2123 switch(E->getOpcode()) {
2124 default: assert(0 && "is not a comparison operation");
2125 case BO_EQ:
2126 CR6 = CR6_LT;
2127 ID = GetIntrinsic(VCMPEQ, ElementKind);
2128 break;
2129 case BO_NE:
2130 CR6 = CR6_EQ;
2131 ID = GetIntrinsic(VCMPEQ, ElementKind);
2132 break;
2133 case BO_LT:
2134 CR6 = CR6_LT;
2135 ID = GetIntrinsic(VCMPGT, ElementKind);
2136 std::swap(FirstVecArg, SecondVecArg);
2137 break;
2138 case BO_GT:
2139 CR6 = CR6_LT;
2140 ID = GetIntrinsic(VCMPGT, ElementKind);
2141 break;
2142 case BO_LE:
2143 if (ElementKind == BuiltinType::Float) {
2144 CR6 = CR6_LT;
2145 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2146 std::swap(FirstVecArg, SecondVecArg);
2147 }
2148 else {
2149 CR6 = CR6_EQ;
2150 ID = GetIntrinsic(VCMPGT, ElementKind);
2151 }
2152 break;
2153 case BO_GE:
2154 if (ElementKind == BuiltinType::Float) {
2155 CR6 = CR6_LT;
2156 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2157 }
2158 else {
2159 CR6 = CR6_EQ;
2160 ID = GetIntrinsic(VCMPGT, ElementKind);
2161 std::swap(FirstVecArg, SecondVecArg);
2162 }
2163 break;
2164 }
2165
Chris Lattner48431f92011-04-19 22:55:03 +00002166 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002167 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2168 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2169 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2170 }
2171
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002172 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002173 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002174 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002175 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002176 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002177 LHS, RHS, "cmp");
2178 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002179 // Unsigned integers and pointers.
2180 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002181 LHS, RHS, "cmp");
2182 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002183
2184 // If this is a vector comparison, sign extend the result to the appropriate
2185 // vector integer type and return it (don't convert to bool).
2186 if (LHSTy->isVectorType())
2187 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002188
Chris Lattner7f02f722007-08-24 05:35:26 +00002189 } else {
2190 // Complex Comparison: can only be an equality comparison.
2191 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2192 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002193
John McCall183700f2009-09-21 23:43:11 +00002194 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002195
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002196 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002197 if (CETy->isRealFloatingType()) {
2198 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2199 LHS.first, RHS.first, "cmp.r");
2200 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2201 LHS.second, RHS.second, "cmp.i");
2202 } else {
2203 // Complex comparisons can only be equality comparisons. As such, signed
2204 // and unsigned opcodes are the same.
2205 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2206 LHS.first, RHS.first, "cmp.r");
2207 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2208 LHS.second, RHS.second, "cmp.i");
2209 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002210
John McCall2de56d12010-08-25 11:45:40 +00002211 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002212 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2213 } else {
John McCall2de56d12010-08-25 11:45:40 +00002214 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002215 "Complex comparison other than == or != ?");
2216 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2217 }
2218 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002219
2220 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002221}
2222
2223Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002224 bool Ignore = TestAndClearIgnoreResultAssign();
2225
John McCallf85e1932011-06-15 23:02:42 +00002226 Value *RHS;
2227 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002228
John McCallf85e1932011-06-15 23:02:42 +00002229 switch (E->getLHS()->getType().getObjCLifetime()) {
2230 case Qualifiers::OCL_Strong:
2231 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2232 break;
2233
2234 case Qualifiers::OCL_Autoreleasing:
2235 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2236 break;
2237
2238 case Qualifiers::OCL_Weak:
2239 RHS = Visit(E->getRHS());
2240 LHS = EmitCheckedLValue(E->getLHS());
2241 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2242 break;
2243
2244 // No reason to do any of these differently.
2245 case Qualifiers::OCL_None:
2246 case Qualifiers::OCL_ExplicitNone:
2247 // __block variables need to have the rhs evaluated first, plus
2248 // this should improve codegen just a little.
2249 RHS = Visit(E->getRHS());
2250 LHS = EmitCheckedLValue(E->getLHS());
2251
2252 // Store the value into the LHS. Bit-fields are handled specially
2253 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2254 // 'An assignment expression has the value of the left operand after
2255 // the assignment...'.
2256 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002257 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002258 else
John McCall545d9962011-06-25 02:11:03 +00002259 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002260 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002261
2262 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002263 if (Ignore)
2264 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002265
John McCallb418d742010-11-16 10:08:07 +00002266 // The result of an assignment in C is the assigned r-value.
2267 if (!CGF.getContext().getLangOptions().CPlusPlus)
2268 return RHS;
2269
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002270 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002271 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002272 return RHS;
2273
2274 // If the lvalue is non-volatile, return the computed value of the assignment.
2275 if (!LHS.isVolatileQualified())
2276 return RHS;
2277
2278 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002279 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002280}
2281
2282Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002283 const llvm::Type *ResTy = ConvertType(E->getType());
2284
Chris Lattner20eb09d2008-11-12 08:26:50 +00002285 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2286 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002287 bool LHSCondVal;
2288 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2289 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002290 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002291 // ZExt result to int or bool.
2292 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002293 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002294
Chris Lattner7804bcb2009-10-17 04:24:20 +00002295 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002296 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002297 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002298 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002299
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002300 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2301 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002302
John McCall150b4622011-01-26 04:00:11 +00002303 CodeGenFunction::ConditionalEvaluation eval(CGF);
2304
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002305 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2306 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2307
2308 // Any edges into the ContBlock are now from an (indeterminate number of)
2309 // edges from this first condition. All of these values will be false. Start
2310 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002311 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002312 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002313 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2314 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002315 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002316
John McCall150b4622011-01-26 04:00:11 +00002317 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002318 CGF.EmitBlock(RHSBlock);
2319 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002320 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002321
Chris Lattner7f02f722007-08-24 05:35:26 +00002322 // Reaquire the RHS block, as there may be subblocks inserted.
2323 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002324
2325 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2326 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002327 if (CGF.getDebugInfo())
2328 // There is no need to emit line number for unconditional branch.
2329 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002330 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002331 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002332
Chris Lattner7f02f722007-08-24 05:35:26 +00002333 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002334 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002335}
2336
2337Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002338 const llvm::Type *ResTy = ConvertType(E->getType());
2339
Chris Lattner20eb09d2008-11-12 08:26:50 +00002340 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2341 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002342 bool LHSCondVal;
2343 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2344 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002345 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002346 // ZExt result to int or bool.
2347 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002348 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002349
Chris Lattner7804bcb2009-10-17 04:24:20 +00002350 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002351 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002352 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002353 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002354
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002355 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2356 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002357
John McCall150b4622011-01-26 04:00:11 +00002358 CodeGenFunction::ConditionalEvaluation eval(CGF);
2359
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002360 // Branch on the LHS first. If it is true, go to the success (cont) block.
2361 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2362
2363 // Any edges into the ContBlock are now from an (indeterminate number of)
2364 // edges from this first condition. All of these values will be true. Start
2365 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002366 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002367 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002368 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2369 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002370 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002371
John McCall150b4622011-01-26 04:00:11 +00002372 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002373
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002374 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002375 CGF.EmitBlock(RHSBlock);
2376 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002377
John McCall150b4622011-01-26 04:00:11 +00002378 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002379
Chris Lattner7f02f722007-08-24 05:35:26 +00002380 // Reaquire the RHS block, as there may be subblocks inserted.
2381 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002382
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002383 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2384 // into the phi node for the edge with the value of RHSCond.
2385 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002386 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002387
Chris Lattner7f02f722007-08-24 05:35:26 +00002388 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002389 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002390}
2391
2392Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002393 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002394 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002395 return Visit(E->getRHS());
2396}
2397
2398//===----------------------------------------------------------------------===//
2399// Other Operators
2400//===----------------------------------------------------------------------===//
2401
Chris Lattner9802a512008-11-12 08:55:54 +00002402/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2403/// expression is cheap enough and side-effect-free enough to evaluate
2404/// unconditionally instead of conditionally. This is used to convert control
2405/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002406static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2407 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002408 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002409
Chris Lattnerc6bea672011-04-16 23:15:35 +00002410 // Anything that is an integer or floating point constant is fine.
2411 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002412 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002413
Chris Lattner9802a512008-11-12 08:55:54 +00002414 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2415 // X and Y are local variables.
2416 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2417 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002418 if (VD->hasLocalStorage() && !(CGF.getContext()
2419 .getCanonicalType(VD->getType())
2420 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002421 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002422
Chris Lattner9802a512008-11-12 08:55:54 +00002423 return false;
2424}
2425
2426
Chris Lattner7f02f722007-08-24 05:35:26 +00002427Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002428VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002429 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002430
2431 // Bind the common expression if necessary.
2432 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2433
2434 Expr *condExpr = E->getCond();
2435 Expr *lhsExpr = E->getTrueExpr();
2436 Expr *rhsExpr = E->getFalseExpr();
2437
Chris Lattner31a09842008-11-12 08:04:58 +00002438 // If the condition constant folds and can be elided, try to avoid emitting
2439 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002440 bool CondExprBool;
2441 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002442 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002443 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002444
Chris Lattner31a09842008-11-12 08:04:58 +00002445 // If the dead side doesn't have labels we need, and if the Live side isn't
2446 // the gnu missing ?: extension (which we could handle, but don't bother
2447 // to), just emit the Live part.
John McCall56ca35d2011-02-17 10:25:35 +00002448 if (!CGF.ContainsLabel(dead))
2449 return Visit(live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002450 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002451
Nate Begeman6155d732010-09-20 22:41:17 +00002452 // OpenCL: If the condition is a vector, we can treat this condition like
2453 // the select function.
2454 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002455 && condExpr->getType()->isVectorType()) {
2456 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2457 llvm::Value *LHS = Visit(lhsExpr);
2458 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002459
John McCall56ca35d2011-02-17 10:25:35 +00002460 const llvm::Type *condType = ConvertType(condExpr->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002461 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2462
2463 unsigned numElem = vecTy->getNumElements();
2464 const llvm::Type *elemType = vecTy->getElementType();
2465
2466 std::vector<llvm::Constant*> Zvals;
2467 for (unsigned i = 0; i < numElem; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +00002468 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002469
Nate Begeman6155d732010-09-20 22:41:17 +00002470 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2471 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2472 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2473 llvm::VectorType::get(elemType,
2474 numElem),
2475 "sext");
2476 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2477
2478 // Cast float to int to perform ANDs if necessary.
2479 llvm::Value *RHSTmp = RHS;
2480 llvm::Value *LHSTmp = LHS;
2481 bool wasCast = false;
2482 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2483 if (rhsVTy->getElementType()->isFloatTy()) {
2484 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2485 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2486 wasCast = true;
2487 }
2488
2489 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2490 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2491 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2492 if (wasCast)
2493 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2494
2495 return tmp5;
2496 }
2497
Chris Lattner9802a512008-11-12 08:55:54 +00002498 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2499 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002500 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002501 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2502 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2503 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2504 llvm::Value *LHS = Visit(lhsExpr);
2505 llvm::Value *RHS = Visit(rhsExpr);
Chris Lattner9802a512008-11-12 08:55:54 +00002506 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2507 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002508
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002509 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2510 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002511 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002512
2513 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002514 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002515
Chris Lattner7f02f722007-08-24 05:35:26 +00002516 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002517 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002518 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002519 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002520
Chris Lattner7f02f722007-08-24 05:35:26 +00002521 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002522 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002523
Chris Lattner7f02f722007-08-24 05:35:26 +00002524 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002525 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002526 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002527 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002528
John McCall150b4622011-01-26 04:00:11 +00002529 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002530 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002531
Eli Friedman48daf592009-12-07 20:25:53 +00002532 // If the LHS or RHS is a throw expression, it will be legitimately null.
2533 if (!LHS)
2534 return RHS;
2535 if (!RHS)
2536 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002537
Chris Lattner7f02f722007-08-24 05:35:26 +00002538 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002539 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002540 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
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002565Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2566 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
2567 const llvm::Type * DstTy = ConvertType(E->getDstType());
2568
2569 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2570 // a shuffle vector instead of a bitcast.
2571 const llvm::Type *SrcTy = Src->getType();
2572 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2573 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2574 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2575 if ((numElementsDst == 3 && numElementsSrc == 4)
2576 || (numElementsDst == 4 && numElementsSrc == 3)) {
2577
2578
2579 // In the case of going from int4->float3, a bitcast is needed before
2580 // doing a shuffle.
2581 const llvm::Type *srcElemTy =
2582 cast<llvm::VectorType>(SrcTy)->getElementType();
2583 const llvm::Type *dstElemTy =
2584 cast<llvm::VectorType>(DstTy)->getElementType();
2585
2586 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2587 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2588 // Create a float type of the same size as the source or destination.
2589 const llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2590 numElementsSrc);
2591
2592 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2593 }
2594
2595 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2596
2597 llvm::SmallVector<llvm::Constant*, 3> Args;
2598 Args.push_back(Builder.getInt32(0));
2599 Args.push_back(Builder.getInt32(1));
2600 Args.push_back(Builder.getInt32(2));
2601
2602 if (numElementsDst == 4)
2603 Args.push_back(llvm::UndefValue::get(
2604 llvm::Type::getInt32Ty(CGF.getLLVMContext())));
2605
2606 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2607
2608 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2609 }
2610 }
2611
2612 return Builder.CreateBitCast(Src, DstTy, "astype");
2613}
2614
Chris Lattner7f02f722007-08-24 05:35:26 +00002615//===----------------------------------------------------------------------===//
2616// Entry Point into this File
2617//===----------------------------------------------------------------------===//
2618
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002619/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2620/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002621Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002622 assert(E && !hasAggregateLLVMType(E->getType()) &&
2623 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002624
Devang Patel5de7a0e2011-03-07 18:29:53 +00002625 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002626 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002627 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002628 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002629 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002630 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002631 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002632}
Chris Lattner3707b252007-08-26 06:48:56 +00002633
2634/// EmitScalarConversion - Emit a conversion from the specified type to the
2635/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002636Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2637 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002638 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2639 "Invalid scalar expression to emit");
2640 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2641}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002642
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002643/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2644/// type to the specified destination type, where the destination type is an
2645/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002646Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2647 QualType SrcTy,
2648 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002649 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002650 "Invalid complex -> scalar conversion");
2651 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2652 DstTy);
2653}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002654
Chris Lattner8c11a652010-06-26 22:09:34 +00002655
2656llvm::Value *CodeGenFunction::
2657EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2658 bool isInc, bool isPre) {
2659 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2660}
2661
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002662LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2663 llvm::Value *V;
2664 // object->isa or (*object).isa
2665 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002666 // build Class* type
2667 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002668
2669 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002670 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002671 V = CreateTempAlloca(ClassPtrTy, "resval");
2672 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2673 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002674 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
John McCall545d9962011-06-25 02:11:03 +00002675 MakeAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002676 } else {
2677 if (E->isArrow())
2678 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2679 else
2680 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002681 }
2682
2683 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002684 ClassPtrTy = ClassPtrTy->getPointerTo();
2685 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002686 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002687}
2688
Douglas Gregor6a03e342010-04-23 04:16:32 +00002689
John McCall2a416372010-12-05 02:00:02 +00002690LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002691 const CompoundAssignOperator *E) {
2692 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002693 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002694 switch (E->getOpcode()) {
2695#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002696 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002697 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002698 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002699 COMPOUND_OP(Mul);
2700 COMPOUND_OP(Div);
2701 COMPOUND_OP(Rem);
2702 COMPOUND_OP(Add);
2703 COMPOUND_OP(Sub);
2704 COMPOUND_OP(Shl);
2705 COMPOUND_OP(Shr);
2706 COMPOUND_OP(And);
2707 COMPOUND_OP(Xor);
2708 COMPOUND_OP(Or);
2709#undef COMPOUND_OP
2710
John McCall2de56d12010-08-25 11:45:40 +00002711 case BO_PtrMemD:
2712 case BO_PtrMemI:
2713 case BO_Mul:
2714 case BO_Div:
2715 case BO_Rem:
2716 case BO_Add:
2717 case BO_Sub:
2718 case BO_Shl:
2719 case BO_Shr:
2720 case BO_LT:
2721 case BO_GT:
2722 case BO_LE:
2723 case BO_GE:
2724 case BO_EQ:
2725 case BO_NE:
2726 case BO_And:
2727 case BO_Xor:
2728 case BO_Or:
2729 case BO_LAnd:
2730 case BO_LOr:
2731 case BO_Assign:
2732 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002733 assert(false && "Not valid compound assignment operators");
2734 break;
2735 }
2736
2737 llvm_unreachable("Unhandled compound assignment operator");
2738}