blob: 0e8afb04d00f4ebf7c946e7128a4df17e19e4b5b [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
Lang Hamesbe9af122012-10-02 04:45:10 +000048 bool FPContractable;
Chris Lattner9a207232010-06-26 21:48:21 +000049 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000050};
51
John McCall404cd162010-11-13 01:35:44 +000052static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
57}
58
Benjamin Kramer85b45212009-11-28 19:45:26 +000059class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000060 : public StmtVisitor<ScalarExprEmitter, Value*> {
61 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000062 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000064 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000065public:
66
Mike Stump7f79f9b2009-05-29 15:46:01 +000067 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000068 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000069 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000070 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000071
Chris Lattner7f02f722007-08-24 05:35:26 +000072 //===--------------------------------------------------------------------===//
73 // Utilities
74 //===--------------------------------------------------------------------===//
75
Mike Stump7f79f9b2009-05-29 15:46:01 +000076 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000077 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
79 return I;
80 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000081
Chris Lattner2acc6e32011-07-18 04:24:23 +000082 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000083 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith7ac9ef12012-09-08 02:08:36 +000084 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith2c9f87c2012-08-24 00:54:33 +000086 }
Chris Lattner7f02f722007-08-24 05:35:26 +000087
John McCall545d9962011-06-25 02:11:03 +000088 Value *EmitLoadOfLValue(LValue LV) {
89 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000090 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000091
Chris Lattner7f02f722007-08-24 05:35:26 +000092 /// EmitLoadOfLValue - Given an expression with complex type that represents a
93 /// value l-value, this method emits the address of the l-value, then loads
94 /// and returns the result.
95 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith7ac9ef12012-09-08 02:08:36 +000096 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
Chris Lattner7f02f722007-08-24 05:35:26 +000097 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000098
Chris Lattner9abc84e2007-08-26 16:42:57 +000099 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000100 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000101 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000102
Chris Lattner3707b252007-08-26 06:48:56 +0000103 /// EmitScalarConversion - Emit a conversion from the specified type to the
104 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000105 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
106
107 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000108 /// complex type to the specified destination type, where the destination type
109 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000110 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
111 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000112
Anders Carlssona40a9f32010-05-22 17:45:10 +0000113 /// EmitNullValue - Emit a value that corresponds to null for the given type.
114 Value *EmitNullValue(QualType Ty);
115
John McCalldaa8e4e2010-11-15 09:13:47 +0000116 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
117 Value *EmitFloatToBoolConversion(Value *V) {
118 // Compare against 0.0 for fp scalars.
119 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
120 return Builder.CreateFCmpUNE(V, Zero, "tobool");
121 }
122
123 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
124 Value *EmitPointerToBoolConversion(Value *V) {
125 Value *Zero = llvm::ConstantPointerNull::get(
126 cast<llvm::PointerType>(V->getType()));
127 return Builder.CreateICmpNE(V, Zero, "tobool");
128 }
129
130 Value *EmitIntToBoolConversion(Value *V) {
131 // Because of the type rules of C, we often end up computing a
132 // logical value, then zero extending it to int, then wanting it
133 // as a logical value again. Optimize this common case.
134 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
135 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
136 Value *Result = ZI->getOperand(0);
137 // If there aren't any more uses, zap the instruction to save space.
138 // Note that there can be more uses, for example if this
139 // is the result of an assignment.
140 if (ZI->use_empty())
141 ZI->eraseFromParent();
142 return Result;
143 }
144 }
145
Chris Lattner48431f92011-04-19 22:55:03 +0000146 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000147 }
148
Chris Lattner7f02f722007-08-24 05:35:26 +0000149 //===--------------------------------------------------------------------===//
150 // Visitor Methods
151 //===--------------------------------------------------------------------===//
152
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000153 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000154 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
155 }
156
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000158 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000159 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000160 }
161 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000162
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000163 Value *VisitParenExpr(ParenExpr *PE) {
164 return Visit(PE->getSubExpr());
165 }
John McCall91a57552011-07-15 05:09:51 +0000166 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
167 return Visit(E->getReplacement());
168 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000169 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
170 return Visit(GE->getResultExpr());
171 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000172
173 // Leaves.
174 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000175 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 }
177 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000178 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000179 }
180 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000182 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000183 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
184 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
185 }
Nate Begemane7579b52007-11-15 05:40:03 +0000186 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000187 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000188 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000189 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000190 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000191 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000192 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000193 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000194 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000195 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000196 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000197 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000198 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
199 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000200 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000201
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000202 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000203 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000204 }
John McCalle996ffd2011-02-16 08:02:54 +0000205
John McCall4b9c2d22011-11-06 09:01:30 +0000206 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
207 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
208 }
209
John McCalle996ffd2011-02-16 08:02:54 +0000210 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000211 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000212 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000213
214 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000215 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000216 }
John McCalldd2ecee2012-03-10 03:05:10 +0000217
Chris Lattner7f02f722007-08-24 05:35:26 +0000218 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000219 Value *VisitDeclRefExpr(DeclRefExpr *E) {
220 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000221 if (result.isReference())
John McCallf4b88a42012-03-10 09:33:50 +0000222 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000223 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000224 }
John McCallf4b88a42012-03-10 09:33:50 +0000225 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000226 }
227
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000228 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
229 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000230 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000231 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
232 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000233 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000234 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000235 return EmitLoadOfLValue(E);
236 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000237 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000238 if (E->getMethodDecl() &&
239 E->getMethodDecl()->getResultType()->isReferenceType())
240 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000242 }
243
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000244 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000245 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000246 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000247 return V;
248 }
249
Chris Lattner7f02f722007-08-24 05:35:26 +0000250 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000251 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000252 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000253 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000254 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
255 return EmitLoadOfLValue(E);
256 }
Devang Patel35634f52007-10-24 17:18:43 +0000257
Nate Begeman0533b302009-10-18 20:10:40 +0000258 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000259
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000260 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000261 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000262 }
John McCallbc8d40d2011-06-24 21:55:10 +0000263 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000265 CGF.EmitVariablyModifiedType(E->getType());
266 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000267 }
John McCallbc8d40d2011-06-24 21:55:10 +0000268 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000269
270 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000271 if (E->getCallReturnType()->isReferenceType())
272 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000273
Chris Lattner9b655512007-08-31 22:49:20 +0000274 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000275 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000276
Chris Lattner33793202007-08-31 22:09:40 +0000277 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000278
Chris Lattner7f02f722007-08-24 05:35:26 +0000279 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000280 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000281 LValue LV = EmitLValue(E->getSubExpr());
282 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000283 }
284 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000285 LValue LV = EmitLValue(E->getSubExpr());
286 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 }
288 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000296
Anton Yartsev683564a2011-02-07 02:17:30 +0000297 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
298 llvm::Value *InVal,
299 llvm::Value *NextVal,
300 bool IsInc);
301
Chris Lattner8c11a652010-06-26 22:09:34 +0000302 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
303 bool isInc, bool isPre);
304
305
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000307 if (isa<MemberPointerType>(E->getType())) // never sugared
308 return CGF.CGM.getMemberPointerConstant(E);
309
Chris Lattner7f02f722007-08-24 05:35:26 +0000310 return EmitLValue(E->getSubExpr()).getAddress();
311 }
John McCallfd569002010-12-04 12:43:24 +0000312 Value *VisitUnaryDeref(const UnaryOperator *E) {
313 if (E->getType()->isVoidType())
314 return Visit(E->getSubExpr()); // the actual value should be unused
315 return EmitLoadOfLValue(E);
316 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000317 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000318 // This differs from gcc, though, most likely due to a bug in gcc.
319 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000320 return Visit(E->getSubExpr());
321 }
322 Value *VisitUnaryMinus (const UnaryOperator *E);
323 Value *VisitUnaryNot (const UnaryOperator *E);
324 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000325 Value *VisitUnaryReal (const UnaryOperator *E);
326 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000327 Value *VisitUnaryExtension(const UnaryOperator *E) {
328 return Visit(E->getSubExpr());
329 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000330
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000331 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000332 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000333 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000334 }
335
Chris Lattner04421082008-04-08 04:40:51 +0000336 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
337 return Visit(DAE->getExpr());
338 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000339 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
340 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000341 }
342
John McCall4765fa02010-12-06 08:20:24 +0000343 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000344 CGF.enterFullExpression(E);
345 CodeGenFunction::RunCleanupsScope Scope(CGF);
346 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000347 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000348 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
349 return CGF.EmitCXXNewExpr(E);
350 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000351 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
352 CGF.EmitCXXDeleteExpr(E);
353 return 0;
354 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000355 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000356 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000357 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000358
Francois Pichet6ad6f282010-12-07 00:08:36 +0000359 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000360 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000361 }
362
John Wiegley21ff2e52011-04-28 00:16:57 +0000363 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
364 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
365 }
366
John Wiegley55262202011-04-25 06:54:41 +0000367 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
368 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
369 }
370
Douglas Gregora71d8192009-09-04 17:36:40 +0000371 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
372 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000373 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000374 // operator (), and the result of such a call has type void. The only
375 // effect is the evaluation of the postfix-expression before the dot or
376 // arrow.
377 CGF.EmitScalarExpr(E->getBase());
378 return 0;
379 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000380
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000381 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000382 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000383 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000384
385 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
386 CGF.EmitCXXThrowExpr(E);
387 return 0;
388 }
389
Sebastian Redl98294de2010-09-10 21:04:00 +0000390 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000391 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000392 }
393
Chris Lattner7f02f722007-08-24 05:35:26 +0000394 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000395 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000396 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000397 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000398 case LangOptions::SOB_Defined:
399 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000400 case LangOptions::SOB_Undefined:
401 if (!CGF.CatchUndefined)
402 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
403 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000404 case LangOptions::SOB_Trapping:
405 return EmitOverflowCheckedBinOp(Ops);
406 }
407 }
408
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000409 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000410 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000411 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
412 }
Chris Lattner80230302010-09-11 21:47:09 +0000413 bool isTrapvOverflowBehavior() {
Richard Smith9d3e2262012-08-25 00:32:28 +0000414 return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
415 == LangOptions::SOB_Trapping || CGF.CatchUndefined;
Chris Lattner80230302010-09-11 21:47:09 +0000416 }
Mike Stump2add4732009-04-01 20:28:16 +0000417 /// Create a binary op that checks for overflow.
418 /// Currently only supports +, - and *.
419 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000420
Chris Lattner80230302010-09-11 21:47:09 +0000421 // Check for undefined division and modulus behaviors.
422 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
423 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000424 Value *EmitDiv(const BinOpInfo &Ops);
425 Value *EmitRem(const BinOpInfo &Ops);
426 Value *EmitAdd(const BinOpInfo &Ops);
427 Value *EmitSub(const BinOpInfo &Ops);
428 Value *EmitShl(const BinOpInfo &Ops);
429 Value *EmitShr(const BinOpInfo &Ops);
430 Value *EmitAnd(const BinOpInfo &Ops) {
431 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
432 }
433 Value *EmitXor(const BinOpInfo &Ops) {
434 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
435 }
436 Value *EmitOr (const BinOpInfo &Ops) {
437 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
438 }
439
Chris Lattner1f1ded92007-08-24 21:00:35 +0000440 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000441 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
442 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000443 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000444
Chris Lattner3ccf7742007-08-26 21:41:21 +0000445 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000446 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
447
448 // Binary operators and binary compound assignment operators.
449#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000450 Value *VisitBin ## OP(const BinaryOperator *E) { \
451 return Emit ## OP(EmitBinOps(E)); \
452 } \
453 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
454 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000455 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000456 HANDLEBINOP(Mul)
457 HANDLEBINOP(Div)
458 HANDLEBINOP(Rem)
459 HANDLEBINOP(Add)
460 HANDLEBINOP(Sub)
461 HANDLEBINOP(Shl)
462 HANDLEBINOP(Shr)
463 HANDLEBINOP(And)
464 HANDLEBINOP(Xor)
465 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000466#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000467
Chris Lattner7f02f722007-08-24 05:35:26 +0000468 // Comparisons.
469 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
470 unsigned SICmpOpc, unsigned FCmpOpc);
471#define VISITCOMP(CODE, UI, SI, FP) \
472 Value *VisitBin##CODE(const BinaryOperator *E) { \
473 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
474 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000475 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
476 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
477 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
478 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
479 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
480 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000481#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000482
Chris Lattner7f02f722007-08-24 05:35:26 +0000483 Value *VisitBinAssign (const BinaryOperator *E);
484
485 Value *VisitBinLAnd (const BinaryOperator *E);
486 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000487 Value *VisitBinComma (const BinaryOperator *E);
488
Eli Friedman25b825d2009-11-18 09:41:26 +0000489 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
490 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
491
Chris Lattner7f02f722007-08-24 05:35:26 +0000492 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000493 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000494 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000495 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000496 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000497 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
498 return CGF.EmitObjCStringLiteral(E);
499 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000500 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
501 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000502 }
503 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
504 return CGF.EmitObjCArrayLiteral(E);
505 }
506 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
507 return CGF.EmitObjCDictionaryLiteral(E);
508 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000509 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000510 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000511};
512} // end anonymous namespace.
513
514//===----------------------------------------------------------------------===//
515// Utilities
516//===----------------------------------------------------------------------===//
517
Chris Lattner9abc84e2007-08-26 16:42:57 +0000518/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000519/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000520Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000521 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000522
John McCalldaa8e4e2010-11-15 09:13:47 +0000523 if (SrcType->isRealFloatingType())
524 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000525
John McCall0bab0cd2010-08-23 01:21:21 +0000526 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
527 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000528
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000529 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000530 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000531
John McCalldaa8e4e2010-11-15 09:13:47 +0000532 if (isa<llvm::IntegerType>(Src->getType()))
533 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000534
John McCalldaa8e4e2010-11-15 09:13:47 +0000535 assert(isa<llvm::PointerType>(Src->getType()));
536 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000537}
538
Chris Lattner3707b252007-08-26 06:48:56 +0000539/// EmitScalarConversion - Emit a conversion from the specified type to the
540/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000541Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
542 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000543 SrcType = CGF.getContext().getCanonicalType(SrcType);
544 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000545 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000546
Chris Lattnercf289082007-08-26 07:21:11 +0000547 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000548
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000549 llvm::Type *SrcTy = Src->getType();
550
551 // Floating casts might be a bit special: if we're doing casts to / from half
552 // FP, we should go via special intrinsics.
553 if (SrcType->isHalfType()) {
554 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
555 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000556 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000557 }
558
Chris Lattner3707b252007-08-26 06:48:56 +0000559 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000560 if (DstType->isBooleanType())
561 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000562
Chris Lattner2acc6e32011-07-18 04:24:23 +0000563 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000564
565 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000566 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000567 return Src;
568
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000569 // Handle pointer conversions next: pointers can only be converted to/from
570 // other pointers and integers. Check for pointer types in terms of LLVM, as
571 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000572 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000573 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000574 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000575 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000576
Chris Lattner3707b252007-08-26 06:48:56 +0000577 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000578 // First, convert to the correct width so that we control the kind of
579 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000580 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000581 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000582 llvm::Value* IntResult =
583 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
584 // Then, cast to pointer.
585 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000586 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000587
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000588 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000589 // Must be an ptr to int cast.
590 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000591 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000592 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000593
Nate Begeman213541a2008-04-18 23:10:10 +0000594 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000595 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000596 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000597 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000598 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
599
600 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000601 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000602 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000603 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000604
605 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000606 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2ce88422012-01-25 05:34:41 +0000607 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
608 Builder.getInt32(0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000609 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
610 return Yay;
611 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000612
Chris Lattner3b1ae002008-02-02 04:51:41 +0000613 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000614 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000615 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000616 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000617
Chris Lattner3707b252007-08-26 06:48:56 +0000618 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000619 Value *Res = NULL;
620 llvm::Type *ResTy = DstTy;
621
622 // Cast to half via float
623 if (DstType->isHalfType())
Chris Lattner8b418682012-02-07 00:39:47 +0000624 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000625
626 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000627 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000628 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000629 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000630 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000631 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000632 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000633 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
634 } else if (isa<llvm::IntegerType>(DstTy)) {
635 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000636 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000637 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000638 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000639 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
640 } else {
641 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
642 "Unknown real conversion");
643 if (DstTy->getTypeID() < SrcTy->getTypeID())
644 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
645 else
646 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000647 }
648
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000649 if (DstTy != ResTy) {
650 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
651 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
652 }
653
654 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000655}
656
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000657/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
658/// type to the specified destination type, where the destination type is an
659/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000660Value *ScalarExprEmitter::
661EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
662 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000663 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000664 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000665
Chris Lattnered70f0a2007-08-26 16:52:28 +0000666 // Handle conversions to bool first, they are special: comparisons against 0.
667 if (DstTy->isBooleanType()) {
668 // Complex != 0 -> (Real != 0) | (Imag != 0)
669 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
670 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
671 return Builder.CreateOr(Src.first, Src.second, "tobool");
672 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000673
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000674 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
675 // the imaginary part of the complex value is discarded and the value of the
676 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000677 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000678 return EmitScalarConversion(Src.first, SrcTy, DstTy);
679}
680
Anders Carlssona40a9f32010-05-22 17:45:10 +0000681Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000682 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
683 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
684
685 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000686}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000687
Chris Lattner7f02f722007-08-24 05:35:26 +0000688//===----------------------------------------------------------------------===//
689// Visitor Methods
690//===----------------------------------------------------------------------===//
691
692Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000693 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000694 if (E->getType()->isVoidType())
695 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000696 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000697}
698
Eli Friedmand38617c2008-05-14 19:38:39 +0000699Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000700 // Vector Mask Case
701 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000702 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000703 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
704 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
705 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000706
Chris Lattner2acc6e32011-07-18 04:24:23 +0000707 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000708 unsigned LHSElts = LTy->getNumElements();
709
710 if (E->getNumSubExprs() == 3) {
711 Mask = CGF.EmitScalarExpr(E->getExpr(2));
712
713 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000714 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000715 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000716 concat.push_back(Builder.getInt32(2*i));
717 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000718 }
719
Chris Lattnerfb018d12011-02-15 00:14:06 +0000720 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000721 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
722 LHSElts *= 2;
723 } else {
724 Mask = RHS;
725 }
726
Chris Lattner2acc6e32011-07-18 04:24:23 +0000727 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000728 llvm::Constant* EltMask;
729
730 // Treat vec3 like vec4.
731 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
732 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
733 (1 << llvm::Log2_32(LHSElts+2))-1);
734 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
735 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
736 (1 << llvm::Log2_32(LHSElts+1))-1);
737 else
738 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
739 (1 << llvm::Log2_32(LHSElts))-1);
740
741 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000742 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
743 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000744 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
745
746 // newv = undef
747 // mask = mask & maskbits
748 // for each elt
749 // n = extract mask i
750 // x = extract val n
751 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000752 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000753 MTy->getNumElements());
754 Value* NewV = llvm::UndefValue::get(RTy);
755 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman87b9c032012-04-05 21:48:40 +0000756 Value *IIndx = Builder.getInt32(i);
757 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000758 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000759
760 // Handle vec3 special since the index will be off by one for the RHS.
761 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
762 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000763 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000764 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000765 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000766 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
767 }
768 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +0000769 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +0000770 }
771 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000772 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000773
Eli Friedmand38617c2008-05-14 19:38:39 +0000774 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
775 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000776
777 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000778 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000779 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000780 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000781 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
782 if (VTy->getNumElements() == 3 && Idx > 3)
783 Idx -= 1;
784 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000785 }
786
Chris Lattnerfb018d12011-02-15 00:14:06 +0000787 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000788 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
789}
Eli Friedman28665272009-11-26 03:22:21 +0000790Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000791 llvm::APSInt Value;
792 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000793 if (E->isArrow())
794 CGF.EmitScalarExpr(E->getBase());
795 else
796 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000797 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000798 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000799
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000800 // Emit debug info for aggregate now, if it was delayed to reduce
Devang Patel78ba3d42010-10-04 21:46:04 +0000801 // debug info size.
802 CGDebugInfo *DI = CGF.getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000803 if (DI &&
804 CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
Devang Patel78ba3d42010-10-04 21:46:04 +0000805 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
806 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000807 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000808 DI->getOrCreateRecordType(PTy->getPointeeType(),
Devang Patel78ba3d42010-10-04 21:46:04 +0000809 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000810 }
Eli Friedman28665272009-11-26 03:22:21 +0000811 return EmitLoadOfLValue(E);
812}
Eli Friedmand38617c2008-05-14 19:38:39 +0000813
Chris Lattner7f02f722007-08-24 05:35:26 +0000814Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000815 TestAndClearIgnoreResultAssign();
816
Chris Lattner7f02f722007-08-24 05:35:26 +0000817 // Emit subscript expressions in rvalue context's. For most cases, this just
818 // loads the lvalue formed by the subscript expr. However, we have to be
819 // careful, because the base of a vector subscript is occasionally an rvalue,
820 // so we can't get it as an lvalue.
821 if (!E->getBase()->getType()->isVectorType())
822 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000823
Chris Lattner7f02f722007-08-24 05:35:26 +0000824 // Handle the vector case. The base must be a vector, the index must be an
825 // integer value.
826 Value *Base = Visit(E->getBase());
827 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000828 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000829 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000830 return Builder.CreateExtractElement(Base, Idx, "vecext");
831}
832
Nate Begeman0533b302009-10-18 20:10:40 +0000833static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000834 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000835 int MV = SVI->getMaskValue(Idx);
836 if (MV == -1)
837 return llvm::UndefValue::get(I32Ty);
838 return llvm::ConstantInt::get(I32Ty, Off+MV);
839}
840
841Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
842 bool Ignore = TestAndClearIgnoreResultAssign();
843 (void)Ignore;
844 assert (Ignore == false && "init list ignored");
845 unsigned NumInitElements = E->getNumInits();
846
847 if (E->hadArrayRangeDesignator())
848 CGF.ErrorUnsupported(E, "GNU array range designator extension");
849
Chris Lattner2acc6e32011-07-18 04:24:23 +0000850 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000851 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
852
Sebastian Redlcea8d962011-09-24 17:48:14 +0000853 if (!VType) {
854 if (NumInitElements == 0) {
855 // C++11 value-initialization for the scalar.
856 return EmitNullValue(E->getType());
857 }
858 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +0000859 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +0000860 }
Nate Begeman0533b302009-10-18 20:10:40 +0000861
862 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000863
864 // Loop over initializers collecting the Value for each, and remembering
865 // whether the source was swizzle (ExtVectorElementExpr). This will allow
866 // us to fold the shuffle for the swizzle into the shuffle for the vector
867 // initializer, since LLVM optimizers generally do not want to touch
868 // shuffles.
869 unsigned CurIdx = 0;
870 bool VIsUndefShuffle = false;
871 llvm::Value *V = llvm::UndefValue::get(VType);
872 for (unsigned i = 0; i != NumInitElements; ++i) {
873 Expr *IE = E->getInit(i);
874 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000875 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000876
Chris Lattner2acc6e32011-07-18 04:24:23 +0000877 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000878
879 // Handle scalar elements. If the scalar initializer is actually one
880 // element of a different vector of the same width, use shuffle instead of
881 // extract+insert.
882 if (!VVT) {
883 if (isa<ExtVectorElementExpr>(IE)) {
884 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
885
886 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
887 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
888 Value *LHS = 0, *RHS = 0;
889 if (CurIdx == 0) {
890 // insert into undef -> shuffle (src, undef)
891 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +0000892 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000893
894 LHS = EI->getVectorOperand();
895 RHS = V;
896 VIsUndefShuffle = true;
897 } else if (VIsUndefShuffle) {
898 // insert into undefshuffle && size match -> shuffle (v, src)
899 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
900 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000901 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000902 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000903 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
904
Nate Begeman0533b302009-10-18 20:10:40 +0000905 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
906 RHS = EI->getVectorOperand();
907 VIsUndefShuffle = false;
908 }
909 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000910 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000911 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
912 ++CurIdx;
913 continue;
914 }
915 }
916 }
Chris Lattner48431f92011-04-19 22:55:03 +0000917 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
918 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000919 VIsUndefShuffle = false;
920 ++CurIdx;
921 continue;
922 }
923
924 unsigned InitElts = VVT->getNumElements();
925
926 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
927 // input is the same width as the vector being constructed, generate an
928 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000929 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000930 if (isa<ExtVectorElementExpr>(IE)) {
931 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
932 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000933 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000934
935 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000936 for (unsigned j = 0; j != CurIdx; ++j) {
937 // If the current vector initializer is a shuffle with undef, merge
938 // this shuffle directly into it.
939 if (VIsUndefShuffle) {
940 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000941 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000942 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000943 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000944 }
945 }
946 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000947 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000948 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000949
950 if (VIsUndefShuffle)
951 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
952
953 Init = SVOp;
954 }
955 }
956
957 // Extend init to result vector length, and then shuffle its contribution
958 // to the vector initializer into V.
959 if (Args.empty()) {
960 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000961 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000962 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000963 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000964 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000965 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000966
967 Args.clear();
968 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000969 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000970 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000971 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000972 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000973 }
974
975 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
976 // merging subsequent shuffles into this one.
977 if (CurIdx == 0)
978 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000979 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000980 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
981 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
982 CurIdx += InitElts;
983 }
984
985 // FIXME: evaluate codegen vs. shuffling against constant null vector.
986 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000987 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +0000988
989 // Emit remaining default initializers
990 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000991 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000992 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
993 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
994 }
995 return V;
996}
997
Anders Carlssona3697c92009-11-23 17:57:54 +0000998static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
999 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001000
John McCall2de56d12010-08-25 11:45:40 +00001001 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001002 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001003
1004 if (isa<CXXThisExpr>(E)) {
1005 // We always assume that 'this' is never null.
1006 return false;
1007 }
1008
1009 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001010 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001011 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001012 return false;
1013 }
1014
1015 return true;
1016}
1017
Chris Lattner7f02f722007-08-24 05:35:26 +00001018// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1019// have to handle a more broad range of conversions than explicit casts, as they
1020// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001021Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001022 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001023 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001024 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001025
Mike Stump7f79f9b2009-05-29 15:46:01 +00001026 if (!DestTy->isVoidType())
1027 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001028
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001029 // Since almost all cast kinds apply to scalars, this switch doesn't have
1030 // a default case, so the compiler will warn on a missing case. The cases
1031 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001032 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001033 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001034 case CK_BuiltinFnToFnPtr:
1035 llvm_unreachable("builtin functions are handled elsewhere");
1036
John McCall2de56d12010-08-25 11:45:40 +00001037 case CK_LValueBitCast:
1038 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001039 Value *V = EmitLValue(E).getAddress();
1040 V = Builder.CreateBitCast(V,
1041 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001042 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001043 }
John McCalldc05b112011-09-10 01:16:55 +00001044
John McCall1d9b3b22011-09-09 05:25:32 +00001045 case CK_CPointerToObjCPointerCast:
1046 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001047 case CK_AnyPointerToBlockPointerCast:
1048 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001049 Value *Src = Visit(const_cast<Expr*>(E));
1050 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1051 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001052 case CK_AtomicToNonAtomic:
1053 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001054 case CK_NoOp:
1055 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001056 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001057
John McCall2de56d12010-08-25 11:45:40 +00001058 case CK_BaseToDerived: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001059 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1060 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1061
1062 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001063 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001064 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001065 }
John McCall2de56d12010-08-25 11:45:40 +00001066 case CK_UncheckedDerivedToBase:
1067 case CK_DerivedToBase: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001068 const CXXRecordDecl *DerivedClassDecl =
1069 E->getType()->getPointeeCXXRecordDecl();
1070 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson191dfe92009-09-12 04:57:16 +00001071
Anders Carlsson34a2d382010-04-24 21:06:20 +00001072 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001073 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001074 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001075 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001076 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001077 Value *V = Visit(const_cast<Expr*>(E));
1078 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1079 return CGF.EmitDynamicCast(V, DCE);
1080 }
Eli Friedmand8889622009-11-27 04:41:50 +00001081
John McCall2de56d12010-08-25 11:45:40 +00001082 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001083 assert(E->getType()->isArrayType() &&
1084 "Array to pointer decay must have array source type!");
1085
1086 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1087
1088 // Note that VLA pointers are always decayed, so we don't need to do
1089 // anything here.
1090 if (!E->getType()->isVariableArrayType()) {
1091 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1092 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1093 ->getElementType()) &&
1094 "Expected pointer to array");
1095 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1096 }
1097
Chris Lattner410b12e2011-07-20 04:31:01 +00001098 // Make sure the array decay ends up being the right type. This matters if
1099 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001100 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001101 }
John McCall2de56d12010-08-25 11:45:40 +00001102 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001103 return EmitLValue(E).getAddress();
1104
John McCall404cd162010-11-13 01:35:44 +00001105 case CK_NullToPointer:
1106 if (MustVisitNullValue(E))
1107 (void) Visit(E);
1108
1109 return llvm::ConstantPointerNull::get(
1110 cast<llvm::PointerType>(ConvertType(DestTy)));
1111
John McCall2de56d12010-08-25 11:45:40 +00001112 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001113 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001114 (void) Visit(E);
1115
John McCall0bab0cd2010-08-23 01:21:21 +00001116 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1117 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1118 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001119
John McCall4d4e5c12012-02-15 01:22:51 +00001120 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001121 case CK_BaseToDerivedMemberPointer:
1122 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001123 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001124
1125 // Note that the AST doesn't distinguish between checked and
1126 // unchecked member pointer conversions, so we always have to
1127 // implement checked conversions here. This is inefficient when
1128 // actual control flow may be required in order to perform the
1129 // check, which it is for data member pointers (but not member
1130 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001131 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001132 }
John McCallf85e1932011-06-15 23:02:42 +00001133
John McCall33e56f32011-09-10 06:18:15 +00001134 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001135 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001136 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001137 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001138 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001139 llvm::Value *value = Visit(E);
1140 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1141 return CGF.EmitObjCConsumeObject(E->getType(), value);
1142 }
John McCall348f16f2011-10-04 06:23:45 +00001143 case CK_ARCExtendBlockObject:
1144 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001145
Douglas Gregorac1303e2012-02-22 05:02:47 +00001146 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001147 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregorac1303e2012-02-22 05:02:47 +00001148
John McCall2bb5d002010-11-13 09:02:35 +00001149 case CK_FloatingRealToComplex:
1150 case CK_FloatingComplexCast:
1151 case CK_IntegralRealToComplex:
1152 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001153 case CK_IntegralComplexToFloatingComplex:
1154 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001155 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001156 case CK_ToUnion:
1157 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001158
John McCall0ae287a2010-12-01 04:43:34 +00001159 case CK_LValueToRValue:
1160 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001161 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001162 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001163
John McCall2de56d12010-08-25 11:45:40 +00001164 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001165 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001166
Anders Carlsson82debc72009-10-18 18:12:03 +00001167 // First, convert to the correct width so that we control the kind of
1168 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001169 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001170 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001171 llvm::Value* IntResult =
1172 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001173
Anders Carlsson82debc72009-10-18 18:12:03 +00001174 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001175 }
Eli Friedman65949422011-06-25 02:58:47 +00001176 case CK_PointerToIntegral:
1177 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1178 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001179
John McCall2de56d12010-08-25 11:45:40 +00001180 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001181 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001182 return 0;
1183 }
John McCall2de56d12010-08-25 11:45:40 +00001184 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001185 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001186 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001187 Elt = EmitScalarConversion(Elt, E->getType(),
1188 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001189
1190 // Insert the element in element zero of an undef vector
1191 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001192 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001193 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001194
1195 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001196 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001197 llvm::Constant *Zero = Builder.getInt32(0);
Chris Lattner2ce88422012-01-25 05:34:41 +00001198 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001199 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1200 return Yay;
1201 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001202
John McCall2de56d12010-08-25 11:45:40 +00001203 case CK_IntegralCast:
1204 case CK_IntegralToFloating:
1205 case CK_FloatingToIntegral:
1206 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001207 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001208 case CK_IntegralToBoolean:
1209 return EmitIntToBoolConversion(Visit(E));
1210 case CK_PointerToBoolean:
1211 return EmitPointerToBoolConversion(Visit(E));
1212 case CK_FloatingToBoolean:
1213 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001214 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001215 llvm::Value *MemPtr = Visit(E);
1216 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1217 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001218 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001219
1220 case CK_FloatingComplexToReal:
1221 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001222 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001223
1224 case CK_FloatingComplexToBoolean:
1225 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001226 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001227
1228 // TODO: kill this function off, inline appropriate case here
1229 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1230 }
1231
John McCall0bab0cd2010-08-23 01:21:21 +00001232 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001233
John McCall61ad0e62010-11-16 06:21:14 +00001234 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001235}
1236
Chris Lattner33793202007-08-31 22:09:40 +00001237Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001238 CodeGenFunction::StmtExprEvaluation eval(CGF);
1239 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1240 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001241}
1242
Chris Lattner7f02f722007-08-24 05:35:26 +00001243//===----------------------------------------------------------------------===//
1244// Unary Operators
1245//===----------------------------------------------------------------------===//
1246
Chris Lattner8c11a652010-06-26 22:09:34 +00001247llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001248EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1249 llvm::Value *InVal,
1250 llvm::Value *NextVal, bool IsInc) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001251 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001252 case LangOptions::SOB_Defined:
1253 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001254 case LangOptions::SOB_Undefined:
1255 if (!CGF.CatchUndefined)
1256 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1257 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001258 case LangOptions::SOB_Trapping:
1259 BinOpInfo BinOp;
1260 BinOp.LHS = InVal;
1261 BinOp.RHS = NextVal;
1262 BinOp.Ty = E->getType();
1263 BinOp.Opcode = BO_Add;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001264 BinOp.FPContractable = false;
Anton Yartsev683564a2011-02-07 02:17:30 +00001265 BinOp.E = E;
1266 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001267 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001268 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001269}
1270
John McCall5936e332011-02-15 09:22:45 +00001271llvm::Value *
1272ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1273 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001274
John McCall5936e332011-02-15 09:22:45 +00001275 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001276 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001277 llvm::Value *input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001278 llvm::PHINode *atomicPHI = 0;
Anton Yartsev683564a2011-02-07 02:17:30 +00001279
John McCall5936e332011-02-15 09:22:45 +00001280 int amount = (isInc ? 1 : -1);
1281
David Chisnall7a7ee302012-01-16 17:27:18 +00001282 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1283 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1284 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1285 Builder.CreateBr(opBB);
1286 Builder.SetInsertPoint(opBB);
1287 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1288 atomicPHI->addIncoming(value, startBB);
1289 type = atomicTy->getValueType();
1290 value = atomicPHI;
1291 }
1292
John McCall5936e332011-02-15 09:22:45 +00001293 // Special case of integer increment that we have to check first: bool++.
1294 // Due to promotion rules, we get:
1295 // bool++ -> bool = bool + 1
1296 // -> bool = (int)bool + 1
1297 // -> bool = ((int)bool + 1 != 0)
1298 // An interesting aspect of this is that increment is always true.
1299 // Decrement does not have this property.
1300 if (isInc && type->isBooleanType()) {
1301 value = Builder.getTrue();
1302
1303 // Most common case by far: integer increment.
1304 } else if (type->isIntegerType()) {
1305
Michael Liao36d5cea2012-08-28 16:55:13 +00001306 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001307
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001308 // Note that signed integer inc/dec with width less than int can't
1309 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001310 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001311 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001312 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001313 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001314 else
1315 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1316
1317 // Next most common: pointer increment.
1318 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1319 QualType type = ptr->getPointeeType();
1320
1321 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001322 if (const VariableArrayType *vla
1323 = CGF.getContext().getAsVariableArrayType(type)) {
1324 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001325 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001327 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001328 else
John McCallbc8d40d2011-06-24 21:55:10 +00001329 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001330
1331 // Arithmetic on function pointers (!) is just +-1.
1332 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001333 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001334
1335 value = CGF.EmitCastToVoidPtr(value);
David Blaikie4e4d0842012-03-11 07:00:24 +00001336 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001337 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1338 else
1339 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001340 value = Builder.CreateBitCast(value, input->getType());
1341
1342 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001343 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001344 llvm::Value *amt = Builder.getInt32(amount);
David Blaikie4e4d0842012-03-11 07:00:24 +00001345 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001346 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1347 else
1348 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001349 }
1350
1351 // Vector increment/decrement.
1352 } else if (type->isVectorType()) {
1353 if (type->hasIntegerRepresentation()) {
1354 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1355
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001356 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001357 } else {
1358 value = Builder.CreateFAdd(
1359 value,
1360 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001361 isInc ? "inc" : "dec");
1362 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001363
John McCall5936e332011-02-15 09:22:45 +00001364 // Floating point.
1365 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001366 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001367 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001368
1369 if (type->isHalfType()) {
1370 // Another special case: half FP increment should be done via float
1371 value =
1372 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1373 input);
1374 }
1375
John McCall5936e332011-02-15 09:22:45 +00001376 if (value->getType()->isFloatTy())
1377 amt = llvm::ConstantFP::get(VMContext,
1378 llvm::APFloat(static_cast<float>(amount)));
1379 else if (value->getType()->isDoubleTy())
1380 amt = llvm::ConstantFP::get(VMContext,
1381 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001382 else {
John McCall5936e332011-02-15 09:22:45 +00001383 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001384 bool ignored;
1385 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1386 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001387 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001388 }
John McCall5936e332011-02-15 09:22:45 +00001389 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1390
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001391 if (type->isHalfType())
1392 value =
1393 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1394 value);
1395
John McCall5936e332011-02-15 09:22:45 +00001396 // Objective-C pointer types.
1397 } else {
1398 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1399 value = CGF.EmitCastToVoidPtr(value);
1400
1401 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1402 if (!isInc) size = -size;
1403 llvm::Value *sizeValue =
1404 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1405
David Blaikie4e4d0842012-03-11 07:00:24 +00001406 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001407 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1408 else
1409 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001410 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001411 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001412
1413 if (atomicPHI) {
1414 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1415 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1416 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1417 value, llvm::SequentiallyConsistent);
1418 atomicPHI->addIncoming(old, opBB);
1419 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1420 Builder.CreateCondBr(success, contBB, opBB);
1421 Builder.SetInsertPoint(contBB);
1422 return isPre ? value : input;
1423 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001424
Chris Lattner8c11a652010-06-26 22:09:34 +00001425 // Store the updated result through the lvalue.
1426 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001427 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001428 else
John McCall545d9962011-06-25 02:11:03 +00001429 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001430
Chris Lattner8c11a652010-06-26 22:09:34 +00001431 // If this is a postinc, return the value read from memory, otherwise use the
1432 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001433 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001434}
1435
1436
1437
Chris Lattner7f02f722007-08-24 05:35:26 +00001438Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001439 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001440 // Emit unary minus with EmitSub so we handle overflow cases etc.
1441 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001442 BinOp.RHS = Visit(E->getSubExpr());
1443
1444 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1445 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1446 else
1447 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001448 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001449 BinOp.Opcode = BO_Sub;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001450 BinOp.FPContractable = false;
Chris Lattner9a207232010-06-26 21:48:21 +00001451 BinOp.E = E;
1452 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001453}
1454
1455Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001456 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001457 Value *Op = Visit(E->getSubExpr());
1458 return Builder.CreateNot(Op, "neg");
1459}
1460
1461Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001462
1463 // Perform vector logical not on comparison with zero vector.
1464 if (E->getType()->isExtVectorType()) {
1465 Value *Oper = Visit(E->getSubExpr());
1466 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1467 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1468 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1469 }
1470
Chris Lattner7f02f722007-08-24 05:35:26 +00001471 // Compare operand to zero.
1472 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001473
Chris Lattner7f02f722007-08-24 05:35:26 +00001474 // Invert value.
1475 // TODO: Could dynamically modify easy computations here. For example, if
1476 // the operand is an icmp ne, turn into icmp eq.
1477 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001478
Anders Carlsson9f84d882009-05-19 18:44:53 +00001479 // ZExt result to the expr type.
1480 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001481}
1482
Eli Friedman0027d2b2010-08-05 09:58:49 +00001483Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1484 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001485 llvm::APSInt Value;
1486 if (E->EvaluateAsInt(Value, CGF.getContext()))
1487 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001488
1489 // Loop over the components of the offsetof to compute the value.
1490 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001491 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001492 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1493 QualType CurrentType = E->getTypeSourceInfo()->getType();
1494 for (unsigned i = 0; i != n; ++i) {
1495 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001496 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001497 switch (ON.getKind()) {
1498 case OffsetOfExpr::OffsetOfNode::Array: {
1499 // Compute the index
1500 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1501 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001502 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001503 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1504
1505 // Save the element type
1506 CurrentType =
1507 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1508
1509 // Compute the element size
1510 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1511 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1512
1513 // Multiply out to compute the result
1514 Offset = Builder.CreateMul(Idx, ElemSize);
1515 break;
1516 }
1517
1518 case OffsetOfExpr::OffsetOfNode::Field: {
1519 FieldDecl *MemberDecl = ON.getField();
1520 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1521 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1522
1523 // Compute the index of the field in its parent.
1524 unsigned i = 0;
1525 // FIXME: It would be nice if we didn't have to loop here!
1526 for (RecordDecl::field_iterator Field = RD->field_begin(),
1527 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001528 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001529 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001530 break;
1531 }
1532 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1533
1534 // Compute the offset to the field
1535 int64_t OffsetInt = RL.getFieldOffset(i) /
1536 CGF.getContext().getCharWidth();
1537 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1538
1539 // Save the element type.
1540 CurrentType = MemberDecl->getType();
1541 break;
1542 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001543
Eli Friedman0027d2b2010-08-05 09:58:49 +00001544 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001545 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001546
Eli Friedman0027d2b2010-08-05 09:58:49 +00001547 case OffsetOfExpr::OffsetOfNode::Base: {
1548 if (ON.getBase()->isVirtual()) {
1549 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1550 continue;
1551 }
1552
1553 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1554 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1555
1556 // Save the element type.
1557 CurrentType = ON.getBase()->getType();
1558
1559 // Compute the offset to the base.
1560 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1561 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001562 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1563 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001564 break;
1565 }
1566 }
1567 Result = Builder.CreateAdd(Result, Offset);
1568 }
1569 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001570}
1571
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001572/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001573/// argument of the sizeof expression as an integer.
1574Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001575ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1576 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001577 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001578 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001579 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001580 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1581 if (E->isArgumentType()) {
1582 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001583 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001584 } else {
1585 // C99 6.5.3.4p2: If the argument is an expression of type
1586 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001587 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001588 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001589
John McCallbc8d40d2011-06-24 21:55:10 +00001590 QualType eltType;
1591 llvm::Value *numElts;
1592 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1593
1594 llvm::Value *size = numElts;
1595
1596 // Scale the number of non-VLA elements by the non-VLA element size.
1597 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1598 if (!eltSize.isOne())
1599 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1600
1601 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001602 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001603 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001604
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001605 // If this isn't sizeof(vla), the result must be constant; use the constant
1606 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001607 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001608}
1609
Chris Lattner46f93d02007-08-24 21:20:17 +00001610Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1611 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001612 if (Op->getType()->isAnyComplexType()) {
1613 // If it's an l-value, load through the appropriate subobject l-value.
1614 // Note that we have to ask E because Op might be an l-value that
1615 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001616 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001617 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001618
1619 // Otherwise, calculate and project.
1620 return CGF.EmitComplexExpr(Op, false, true).first;
1621 }
1622
Chris Lattner46f93d02007-08-24 21:20:17 +00001623 return Visit(Op);
1624}
John McCallb418d742010-11-16 10:08:07 +00001625
Chris Lattner46f93d02007-08-24 21:20:17 +00001626Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1627 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001628 if (Op->getType()->isAnyComplexType()) {
1629 // If it's an l-value, load through the appropriate subobject l-value.
1630 // Note that we have to ask E because Op might be an l-value that
1631 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001632 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001633 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001634
1635 // Otherwise, calculate and project.
1636 return CGF.EmitComplexExpr(Op, true, false).second;
1637 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001638
Mike Stump7f79f9b2009-05-29 15:46:01 +00001639 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1640 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001641 if (Op->isGLValue())
1642 CGF.EmitLValue(Op);
1643 else
1644 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001645 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001646}
1647
Chris Lattner7f02f722007-08-24 05:35:26 +00001648//===----------------------------------------------------------------------===//
1649// Binary Operators
1650//===----------------------------------------------------------------------===//
1651
1652BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001653 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001654 BinOpInfo Result;
1655 Result.LHS = Visit(E->getLHS());
1656 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001657 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001658 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00001659 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00001660 Result.E = E;
1661 return Result;
1662}
1663
Douglas Gregor6a03e342010-04-23 04:16:32 +00001664LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1665 const CompoundAssignOperator *E,
1666 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001667 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001668 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001669 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001670
Eli Friedmanab3a8522009-03-28 01:22:36 +00001671 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001672 // This needs to go through the complex expression emitter, but it's a tad
1673 // complicated to do that... I'm leaving it out for now. (Note that we do
1674 // actually need the imaginary part of the RHS for multiplication and
1675 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001676 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001677 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001678 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001679 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001680
Mike Stumpcc0442f2009-05-22 19:07:20 +00001681 // Emit the RHS first. __block variables need to have the rhs evaluated
1682 // first, plus this should improve codegen a little.
1683 OpInfo.RHS = Visit(E->getRHS());
1684 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001685 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerddc57332012-10-03 20:58:04 +00001686 OpInfo.FPContractable = false;
Mike Stumpcc0442f2009-05-22 19:07:20 +00001687 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001688 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00001689 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall545d9962011-06-25 02:11:03 +00001690 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
David Chisnall7a7ee302012-01-16 17:27:18 +00001691
1692 llvm::PHINode *atomicPHI = 0;
Eli Friedman860a3192012-06-16 02:19:17 +00001693 if (LHSTy->isAtomicType()) {
David Chisnall7a7ee302012-01-16 17:27:18 +00001694 // FIXME: For floating point types, we should be saving and restoring the
1695 // floating point environment in the loop.
1696 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1697 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1698 Builder.CreateBr(opBB);
1699 Builder.SetInsertPoint(opBB);
1700 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1701 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001702 OpInfo.LHS = atomicPHI;
1703 }
Eli Friedman860a3192012-06-16 02:19:17 +00001704
1705 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1706 E->getComputationLHSType());
1707
Chris Lattner1f1ded92007-08-24 21:00:35 +00001708 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001709 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001710
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001711 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001712 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001713
1714 if (atomicPHI) {
1715 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1716 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1717 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1718 Result, llvm::SequentiallyConsistent);
1719 atomicPHI->addIncoming(old, opBB);
1720 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1721 Builder.CreateCondBr(success, contBB, opBB);
1722 Builder.SetInsertPoint(contBB);
1723 return LHSLV;
1724 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001725
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001726 // Store the result value into the LHS lvalue. Bit-fields are handled
1727 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1728 // 'An assignment expression has the value of the left operand after the
1729 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001730 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001731 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001732 else
John McCall545d9962011-06-25 02:11:03 +00001733 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001734
Douglas Gregor6a03e342010-04-23 04:16:32 +00001735 return LHSLV;
1736}
1737
1738Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1739 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1740 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001741 Value *RHS;
1742 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1743
1744 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001745 if (Ignore)
1746 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001747
John McCallb418d742010-11-16 10:08:07 +00001748 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00001749 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00001750 return RHS;
1751
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001752 // If the lvalue is non-volatile, return the computed value of the assignment.
1753 if (!LHS.isVolatileQualified())
1754 return RHS;
1755
1756 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001757 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001758}
1759
Chris Lattner80230302010-09-11 21:47:09 +00001760void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00001761 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001762 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001763
1764 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1765 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001766 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001767 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1768
Richard Smith7ac9ef12012-09-08 02:08:36 +00001769 llvm::Value *Cond1 = Builder.CreateICmpNE(Ops.RHS, Zero);
1770 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1771 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
1772 llvm::Value *Cond2 = Builder.CreateOr(LHSCmp, RHSCmp, "or");
1773 CGF.EmitCheck(Builder.CreateAnd(Cond1, Cond2, "and"));
Chris Lattner80230302010-09-11 21:47:09 +00001774 } else {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001775 CGF.EmitCheck(Builder.CreateICmpNE(Ops.RHS, Zero));
Chris Lattner80230302010-09-11 21:47:09 +00001776 }
Chris Lattner80230302010-09-11 21:47:09 +00001777}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001778
Chris Lattner7f02f722007-08-24 05:35:26 +00001779Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001780 if (isTrapvOverflowBehavior()) {
Chris Lattner80230302010-09-11 21:47:09 +00001781 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1782
1783 if (Ops.Ty->isIntegerType())
1784 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Richard Smith7ac9ef12012-09-08 02:08:36 +00001785 else if (Ops.Ty->isRealFloatingType())
1786 CGF.EmitCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero));
Chris Lattner80230302010-09-11 21:47:09 +00001787 }
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001788 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1789 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
David Blaikie4e4d0842012-03-11 07:00:24 +00001790 if (CGF.getContext().getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001791 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1792 llvm::Type *ValTy = Val->getType();
1793 if (ValTy->isFloatTy() ||
1794 (isa<llvm::VectorType>(ValTy) &&
1795 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00001796 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001797 }
1798 return Val;
1799 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001800 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001801 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1802 else
1803 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1804}
1805
1806Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1807 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001808 if (isTrapvOverflowBehavior()) {
1809 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1810
1811 if (Ops.Ty->isIntegerType())
1812 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1813 }
1814
Eli Friedman52d68742011-04-10 04:44:11 +00001815 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001816 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1817 else
1818 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1819}
1820
Mike Stump2add4732009-04-01 20:28:16 +00001821Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1822 unsigned IID;
1823 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001824
Chris Lattner9a207232010-06-26 21:48:21 +00001825 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001826 case BO_Add:
1827 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001828 OpID = 1;
1829 IID = llvm::Intrinsic::sadd_with_overflow;
1830 break;
John McCall2de56d12010-08-25 11:45:40 +00001831 case BO_Sub:
1832 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001833 OpID = 2;
1834 IID = llvm::Intrinsic::ssub_with_overflow;
1835 break;
John McCall2de56d12010-08-25 11:45:40 +00001836 case BO_Mul:
1837 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001838 OpID = 3;
1839 IID = llvm::Intrinsic::smul_with_overflow;
1840 break;
1841 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001842 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00001843 }
Mike Stump035cf892009-04-02 18:15:54 +00001844 OpID <<= 1;
1845 OpID |= 1;
1846
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001847 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001848
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001849 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001850
1851 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1852 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1853 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1854
Richard Smith7ac9ef12012-09-08 02:08:36 +00001855 // Handle overflow with llvm.trap if no custom handler has been specified.
1856 const std::string *handlerName =
1857 &CGF.getContext().getLangOpts().OverflowHandler;
1858 if (handlerName->empty()) {
1859 CGF.EmitCheck(Builder.CreateNot(overflow));
1860 return result;
1861 }
1862
Mike Stump2add4732009-04-01 20:28:16 +00001863 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001864 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001865 llvm::Function::iterator insertPt = initialBB;
1866 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1867 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001868 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001869
1870 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1871
David Chisnall7f18e672010-09-17 18:29:54 +00001872 // If an overflow handler is set, then we want to call it and then use its
1873 // result, if it returns.
1874 Builder.SetInsertPoint(overflowBB);
1875
1876 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00001877 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001878 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001879 llvm::FunctionType *handlerTy =
1880 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1881 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1882
1883 // Sign extend the args to 64-bit, so that we can use the same handler for
1884 // all types of overflow.
1885 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1886 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1887
1888 // Call the handler with the two arguments, the operation, and the size of
1889 // the result.
1890 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1891 Builder.getInt8(OpID),
1892 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1893
1894 // Truncate the result back to the desired size.
1895 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1896 Builder.CreateBr(continueBB);
1897
Mike Stump2add4732009-04-01 20:28:16 +00001898 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001899 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001900 phi->addIncoming(result, initialBB);
1901 phi->addIncoming(handlerResult, overflowBB);
1902
1903 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001904}
Chris Lattner7f02f722007-08-24 05:35:26 +00001905
John McCall913dab22011-06-25 01:32:37 +00001906/// Emit pointer + index arithmetic.
1907static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1908 const BinOpInfo &op,
1909 bool isSubtraction) {
1910 // Must have binary (not unary) expr here. Unary pointer
1911 // increment/decrement doesn't use this path.
1912 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1913
1914 Value *pointer = op.LHS;
1915 Expr *pointerOperand = expr->getLHS();
1916 Value *index = op.RHS;
1917 Expr *indexOperand = expr->getRHS();
1918
1919 // In a subtraction, the LHS is always the pointer.
1920 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1921 std::swap(pointer, index);
1922 std::swap(pointerOperand, indexOperand);
1923 }
1924
1925 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1926 if (width != CGF.PointerWidthInBits) {
1927 // Zero-extend or sign-extend the pointer value according to
1928 // whether the index is signed or not.
1929 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1930 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1931 "idx.ext");
1932 }
1933
1934 // If this is subtraction, negate the index.
1935 if (isSubtraction)
1936 index = CGF.Builder.CreateNeg(index, "idx.neg");
1937
1938 const PointerType *pointerType
1939 = pointerOperand->getType()->getAs<PointerType>();
1940 if (!pointerType) {
1941 QualType objectType = pointerOperand->getType()
1942 ->castAs<ObjCObjectPointerType>()
1943 ->getPointeeType();
1944 llvm::Value *objectSize
1945 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1946
1947 index = CGF.Builder.CreateMul(index, objectSize);
1948
1949 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1950 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1951 return CGF.Builder.CreateBitCast(result, pointer->getType());
1952 }
1953
1954 QualType elementType = pointerType->getPointeeType();
1955 if (const VariableArrayType *vla
1956 = CGF.getContext().getAsVariableArrayType(elementType)) {
1957 // The element count here is the total number of non-VLA elements.
1958 llvm::Value *numElements = CGF.getVLASize(vla).first;
1959
1960 // Effectively, the multiply by the VLA size is part of the GEP.
1961 // GEP indexes are signed, and scaling an index isn't permitted to
1962 // signed-overflow, so we use the same semantics for our explicit
1963 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00001964 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00001965 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1966 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1967 } else {
1968 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1969 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001970 }
John McCall913dab22011-06-25 01:32:37 +00001971 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001972 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001973
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001974 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1975 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1976 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001977 if (elementType->isVoidType() || elementType->isFunctionType()) {
1978 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1979 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1980 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001981 }
1982
David Blaikie4e4d0842012-03-11 07:00:24 +00001983 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00001984 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1985
1986 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001987}
1988
Lang Hamesbe9af122012-10-02 04:45:10 +00001989// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
1990// Addend. Use negMul and negAdd to negate the first operand of the Mul or
1991// the add operand respectively. This allows fmuladd to represent a*b-c, or
1992// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
1993// efficient operations.
1994static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
1995 const CodeGenFunction &CGF, CGBuilderTy &Builder,
1996 bool negMul, bool negAdd) {
1997 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
1998
1999 Value *MulOp0 = MulOp->getOperand(0);
2000 Value *MulOp1 = MulOp->getOperand(1);
2001 if (negMul) {
2002 MulOp0 =
2003 Builder.CreateFSub(
2004 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2005 "neg");
2006 } else if (negAdd) {
2007 Addend =
2008 Builder.CreateFSub(
2009 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2010 "neg");
2011 }
2012
2013 Value *FMulAdd =
2014 Builder.CreateCall3(
2015 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2016 MulOp0, MulOp1, Addend);
2017 MulOp->eraseFromParent();
2018
2019 return FMulAdd;
2020}
2021
2022// Check whether it would be legal to emit an fmuladd intrinsic call to
2023// represent op and if so, build the fmuladd.
2024//
2025// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2026// Does NOT check the type of the operation - it's assumed that this function
2027// will be called from contexts where it's known that the type is contractable.
2028static Value* tryEmitFMulAdd(const BinOpInfo &op,
2029 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2030 bool isSub=false) {
2031
2032 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2033 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2034 "Only fadd/fsub can be the root of an fmuladd.");
2035
2036 // Check whether this op is marked as fusable.
2037 if (!op.FPContractable)
2038 return 0;
2039
2040 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2041 // either disabled, or handled entirely by the LLVM backend).
2042 if (CGF.getContext().getLangOpts().getFPContractMode() != LangOptions::FPC_On)
2043 return 0;
2044
2045 // We have a potentially fusable op. Look for a mul on one of the operands.
2046 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2047 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002048 assert(LHSBinOp->getNumUses() == 0 &&
2049 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002050 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2051 }
2052 } else if (llvm::BinaryOperator* RHSBinOp =
2053 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2054 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002055 assert(RHSBinOp->getNumUses() == 0 &&
2056 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002057 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2058 }
2059 }
2060
2061 return 0;
2062}
2063
John McCall913dab22011-06-25 01:32:37 +00002064Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2065 if (op.LHS->getType()->isPointerTy() ||
2066 op.RHS->getType()->isPointerTy())
2067 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2068
2069 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002070 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002071 case LangOptions::SOB_Defined:
2072 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002073 case LangOptions::SOB_Undefined:
2074 if (!CGF.CatchUndefined)
2075 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2076 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002077 case LangOptions::SOB_Trapping:
2078 return EmitOverflowCheckedBinOp(op);
2079 }
2080 }
2081
Lang Hamesbe9af122012-10-02 04:45:10 +00002082 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2083 // Try to form an fmuladd.
2084 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2085 return FMulAdd;
2086
John McCall913dab22011-06-25 01:32:37 +00002087 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002088 }
John McCall913dab22011-06-25 01:32:37 +00002089
2090 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2091}
2092
2093Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2094 // The LHS is always a pointer if either side is.
2095 if (!op.LHS->getType()->isPointerTy()) {
2096 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002097 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002098 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002099 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002100 case LangOptions::SOB_Undefined:
2101 if (!CGF.CatchUndefined)
2102 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2103 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002104 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002105 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002106 }
2107 }
2108
Lang Hamesbe9af122012-10-02 04:45:10 +00002109 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2110 // Try to form an fmuladd.
2111 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2112 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002113 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002114 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002115
John McCall913dab22011-06-25 01:32:37 +00002116 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002117 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002118
John McCall913dab22011-06-25 01:32:37 +00002119 // If the RHS is not a pointer, then we have normal pointer
2120 // arithmetic.
2121 if (!op.RHS->getType()->isPointerTy())
2122 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002123
John McCall913dab22011-06-25 01:32:37 +00002124 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002125
John McCall913dab22011-06-25 01:32:37 +00002126 // Do the raw subtraction part.
2127 llvm::Value *LHS
2128 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2129 llvm::Value *RHS
2130 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2131 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002132
John McCall913dab22011-06-25 01:32:37 +00002133 // Okay, figure out the element size.
2134 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2135 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002136
John McCall913dab22011-06-25 01:32:37 +00002137 llvm::Value *divisor = 0;
2138
2139 // For a variable-length array, this is going to be non-constant.
2140 if (const VariableArrayType *vla
2141 = CGF.getContext().getAsVariableArrayType(elementType)) {
2142 llvm::Value *numElements;
2143 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2144
2145 divisor = numElements;
2146
2147 // Scale the number of non-VLA elements by the non-VLA element size.
2148 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2149 if (!eltSize.isOne())
2150 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2151
2152 // For everything elese, we can just compute it, safe in the
2153 // assumption that Sema won't let anything through that we can't
2154 // safely compute the size of.
2155 } else {
2156 CharUnits elementSize;
2157 // Handle GCC extension for pointer arithmetic on void* and
2158 // function pointer types.
2159 if (elementType->isVoidType() || elementType->isFunctionType())
2160 elementSize = CharUnits::One();
2161 else
2162 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2163
2164 // Don't even emit the divide for element size of 1.
2165 if (elementSize.isOne())
2166 return diffInChars;
2167
2168 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002169 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002170
Chris Lattner2cb42222011-03-01 00:03:48 +00002171 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2172 // pointer difference in C is only defined in the case where both operands
2173 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002174 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002175}
2176
2177Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2178 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2179 // RHS to the same size as the LHS.
2180 Value *RHS = Ops.RHS;
2181 if (Ops.LHS->getType() != RHS->getType())
2182 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002183
Richard Smith9d3e2262012-08-25 00:32:28 +00002184 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002185 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith9d3e2262012-08-25 00:32:28 +00002186 llvm::Value *WidthMinusOne =
Richard Smith5b092ef2012-08-25 05:43:00 +00002187 llvm::ConstantInt::get(RHS->getType(), Width - 1);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002188 CGF.EmitCheck(Builder.CreateICmpULE(RHS, WidthMinusOne));
Richard Smith9d3e2262012-08-25 00:32:28 +00002189
2190 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2191 // Check whether we are shifting any non-zero bits off the top of the
2192 // integer.
Richard Smith9d3e2262012-08-25 00:32:28 +00002193 llvm::Value *BitsShiftedOff =
2194 Builder.CreateLShr(Ops.LHS,
2195 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2196 /*NUW*/true, /*NSW*/true),
2197 "shl.check");
2198 if (CGF.getLangOpts().CPlusPlus) {
2199 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2200 // Under C++11's rules, shifting a 1 bit into the sign bit is
2201 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2202 // define signed left shifts, so we use the C99 and C++11 rules there).
2203 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2204 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2205 }
2206 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002207 CGF.EmitCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero));
Richard Smith9d3e2262012-08-25 00:32:28 +00002208 }
Mike Stumpbe07f602009-12-14 21:58:14 +00002209 }
2210
Chris Lattner7f02f722007-08-24 05:35:26 +00002211 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2212}
2213
2214Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2215 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2216 // RHS to the same size as the LHS.
2217 Value *RHS = Ops.RHS;
2218 if (Ops.LHS->getType() != RHS->getType())
2219 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002220
Richard Smith9d3e2262012-08-25 00:32:28 +00002221 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002222 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith7ac9ef12012-09-08 02:08:36 +00002223 llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
2224 CGF.EmitCheck(Builder.CreateICmpULT(RHS, WidthVal));
Mike Stumpbe07f602009-12-14 21:58:14 +00002225 }
2226
Douglas Gregorf6094622010-07-23 15:58:24 +00002227 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002228 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2229 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2230}
2231
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002232enum IntrinsicType { VCMPEQ, VCMPGT };
2233// return corresponding comparison intrinsic for given vector type
2234static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2235 BuiltinType::Kind ElemKind) {
2236 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002237 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002238 case BuiltinType::Char_U:
2239 case BuiltinType::UChar:
2240 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2241 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002242 case BuiltinType::Char_S:
2243 case BuiltinType::SChar:
2244 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2245 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002246 case BuiltinType::UShort:
2247 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2248 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002249 case BuiltinType::Short:
2250 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2251 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002252 case BuiltinType::UInt:
2253 case BuiltinType::ULong:
2254 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2255 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002256 case BuiltinType::Int:
2257 case BuiltinType::Long:
2258 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2259 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002260 case BuiltinType::Float:
2261 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2262 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002263 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002264}
2265
Chris Lattner7f02f722007-08-24 05:35:26 +00002266Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2267 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002268 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002269 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002270 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002271 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002272 assert(E->getOpcode() == BO_EQ ||
2273 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002274 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2275 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002276 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002277 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002278 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002279 Value *LHS = Visit(E->getLHS());
2280 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002281
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002282 // If AltiVec, the comparison results in a numeric type, so we use
2283 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002284 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002285 // constants for mapping CR6 register bits to predicate result
2286 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2287
2288 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2289
2290 // in several cases vector arguments order will be reversed
2291 Value *FirstVecArg = LHS,
2292 *SecondVecArg = RHS;
2293
2294 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002295 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002296 BuiltinType::Kind ElementKind = BTy->getKind();
2297
2298 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002299 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002300 case BO_EQ:
2301 CR6 = CR6_LT;
2302 ID = GetIntrinsic(VCMPEQ, ElementKind);
2303 break;
2304 case BO_NE:
2305 CR6 = CR6_EQ;
2306 ID = GetIntrinsic(VCMPEQ, ElementKind);
2307 break;
2308 case BO_LT:
2309 CR6 = CR6_LT;
2310 ID = GetIntrinsic(VCMPGT, ElementKind);
2311 std::swap(FirstVecArg, SecondVecArg);
2312 break;
2313 case BO_GT:
2314 CR6 = CR6_LT;
2315 ID = GetIntrinsic(VCMPGT, ElementKind);
2316 break;
2317 case BO_LE:
2318 if (ElementKind == BuiltinType::Float) {
2319 CR6 = CR6_LT;
2320 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2321 std::swap(FirstVecArg, SecondVecArg);
2322 }
2323 else {
2324 CR6 = CR6_EQ;
2325 ID = GetIntrinsic(VCMPGT, ElementKind);
2326 }
2327 break;
2328 case BO_GE:
2329 if (ElementKind == BuiltinType::Float) {
2330 CR6 = CR6_LT;
2331 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2332 }
2333 else {
2334 CR6 = CR6_EQ;
2335 ID = GetIntrinsic(VCMPGT, ElementKind);
2336 std::swap(FirstVecArg, SecondVecArg);
2337 }
2338 break;
2339 }
2340
Chris Lattner48431f92011-04-19 22:55:03 +00002341 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002342 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2343 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2344 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2345 }
2346
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002347 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002348 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002349 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002350 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002351 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002352 LHS, RHS, "cmp");
2353 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002354 // Unsigned integers and pointers.
2355 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002356 LHS, RHS, "cmp");
2357 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002358
2359 // If this is a vector comparison, sign extend the result to the appropriate
2360 // vector integer type and return it (don't convert to bool).
2361 if (LHSTy->isVectorType())
2362 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002363
Chris Lattner7f02f722007-08-24 05:35:26 +00002364 } else {
2365 // Complex Comparison: can only be an equality comparison.
2366 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2367 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002368
John McCall183700f2009-09-21 23:43:11 +00002369 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002370
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002371 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002372 if (CETy->isRealFloatingType()) {
2373 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2374 LHS.first, RHS.first, "cmp.r");
2375 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2376 LHS.second, RHS.second, "cmp.i");
2377 } else {
2378 // Complex comparisons can only be equality comparisons. As such, signed
2379 // and unsigned opcodes are the same.
2380 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2381 LHS.first, RHS.first, "cmp.r");
2382 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2383 LHS.second, RHS.second, "cmp.i");
2384 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002385
John McCall2de56d12010-08-25 11:45:40 +00002386 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002387 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2388 } else {
John McCall2de56d12010-08-25 11:45:40 +00002389 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002390 "Complex comparison other than == or != ?");
2391 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2392 }
2393 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002394
2395 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002396}
2397
2398Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002399 bool Ignore = TestAndClearIgnoreResultAssign();
2400
John McCallf85e1932011-06-15 23:02:42 +00002401 Value *RHS;
2402 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002403
John McCallf85e1932011-06-15 23:02:42 +00002404 switch (E->getLHS()->getType().getObjCLifetime()) {
2405 case Qualifiers::OCL_Strong:
2406 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2407 break;
2408
2409 case Qualifiers::OCL_Autoreleasing:
2410 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2411 break;
2412
2413 case Qualifiers::OCL_Weak:
2414 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002415 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002416 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2417 break;
2418
2419 // No reason to do any of these differently.
2420 case Qualifiers::OCL_None:
2421 case Qualifiers::OCL_ExplicitNone:
2422 // __block variables need to have the rhs evaluated first, plus
2423 // this should improve codegen just a little.
2424 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002425 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002426
2427 // Store the value into the LHS. Bit-fields are handled specially
2428 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2429 // 'An assignment expression has the value of the left operand after
2430 // the assignment...'.
2431 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002432 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002433 else
John McCall545d9962011-06-25 02:11:03 +00002434 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002435 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002436
2437 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002438 if (Ignore)
2439 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002440
John McCallb418d742010-11-16 10:08:07 +00002441 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002442 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002443 return RHS;
2444
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002445 // If the lvalue is non-volatile, return the computed value of the assignment.
2446 if (!LHS.isVolatileQualified())
2447 return RHS;
2448
2449 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002450 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002451}
2452
2453Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002454
2455 // Perform vector logical and on comparisons with zero vectors.
2456 if (E->getType()->isVectorType()) {
2457 Value *LHS = Visit(E->getLHS());
2458 Value *RHS = Visit(E->getRHS());
2459 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2460 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2461 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2462 Value *And = Builder.CreateAnd(LHS, RHS);
2463 return Builder.CreateSExt(And, Zero->getType(), "sext");
2464 }
2465
Chris Lattner2acc6e32011-07-18 04:24:23 +00002466 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002467
Chris Lattner20eb09d2008-11-12 08:26:50 +00002468 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2469 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002470 bool LHSCondVal;
2471 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2472 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002473 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002474 // ZExt result to int or bool.
2475 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002476 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002477
Chris Lattner7804bcb2009-10-17 04:24:20 +00002478 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002479 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002480 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002481 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002482
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002483 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2484 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002485
John McCall150b4622011-01-26 04:00:11 +00002486 CodeGenFunction::ConditionalEvaluation eval(CGF);
2487
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002488 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2489 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2490
2491 // Any edges into the ContBlock are now from an (indeterminate number of)
2492 // edges from this first condition. All of these values will be false. Start
2493 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002494 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002495 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002496 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2497 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002498 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002499
John McCall150b4622011-01-26 04:00:11 +00002500 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002501 CGF.EmitBlock(RHSBlock);
2502 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002503 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002504
Chris Lattner7f02f722007-08-24 05:35:26 +00002505 // Reaquire the RHS block, as there may be subblocks inserted.
2506 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002507
2508 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2509 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002510 if (CGF.getDebugInfo())
2511 // There is no need to emit line number for unconditional branch.
2512 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002513 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002514 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002515
Chris Lattner7f02f722007-08-24 05:35:26 +00002516 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002517 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002518}
2519
2520Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002521
2522 // Perform vector logical or on comparisons with zero vectors.
2523 if (E->getType()->isVectorType()) {
2524 Value *LHS = Visit(E->getLHS());
2525 Value *RHS = Visit(E->getRHS());
2526 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2527 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2528 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2529 Value *Or = Builder.CreateOr(LHS, RHS);
2530 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2531 }
2532
Chris Lattner2acc6e32011-07-18 04:24:23 +00002533 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002534
Chris Lattner20eb09d2008-11-12 08:26:50 +00002535 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2536 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002537 bool LHSCondVal;
2538 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2539 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002540 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002541 // ZExt result to int or bool.
2542 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002543 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002544
Chris Lattner7804bcb2009-10-17 04:24:20 +00002545 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002546 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002547 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002548 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002549
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002550 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2551 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002552
John McCall150b4622011-01-26 04:00:11 +00002553 CodeGenFunction::ConditionalEvaluation eval(CGF);
2554
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002555 // Branch on the LHS first. If it is true, go to the success (cont) block.
2556 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2557
2558 // Any edges into the ContBlock are now from an (indeterminate number of)
2559 // edges from this first condition. All of these values will be true. Start
2560 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002561 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002562 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002563 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2564 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002565 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002566
John McCall150b4622011-01-26 04:00:11 +00002567 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002568
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002569 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002570 CGF.EmitBlock(RHSBlock);
2571 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002572
John McCall150b4622011-01-26 04:00:11 +00002573 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002574
Chris Lattner7f02f722007-08-24 05:35:26 +00002575 // Reaquire the RHS block, as there may be subblocks inserted.
2576 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002577
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002578 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2579 // into the phi node for the edge with the value of RHSCond.
2580 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002581 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002582
Chris Lattner7f02f722007-08-24 05:35:26 +00002583 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002584 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002585}
2586
2587Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002588 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002589 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002590 return Visit(E->getRHS());
2591}
2592
2593//===----------------------------------------------------------------------===//
2594// Other Operators
2595//===----------------------------------------------------------------------===//
2596
Chris Lattner9802a512008-11-12 08:55:54 +00002597/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2598/// expression is cheap enough and side-effect-free enough to evaluate
2599/// unconditionally instead of conditionally. This is used to convert control
2600/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002601static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2602 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002603 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002604
Chris Lattnerc6bea672011-04-16 23:15:35 +00002605 // Anything that is an integer or floating point constant is fine.
2606 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002607 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002608
Chris Lattner9802a512008-11-12 08:55:54 +00002609 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2610 // X and Y are local variables.
2611 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2612 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002613 if (VD->hasLocalStorage() && !(CGF.getContext()
2614 .getCanonicalType(VD->getType())
2615 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002616 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002617
Chris Lattner9802a512008-11-12 08:55:54 +00002618 return false;
2619}
2620
2621
Chris Lattner7f02f722007-08-24 05:35:26 +00002622Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002623VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002624 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002625
2626 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002627 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002628
2629 Expr *condExpr = E->getCond();
2630 Expr *lhsExpr = E->getTrueExpr();
2631 Expr *rhsExpr = E->getFalseExpr();
2632
Chris Lattner31a09842008-11-12 08:04:58 +00002633 // If the condition constant folds and can be elided, try to avoid emitting
2634 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002635 bool CondExprBool;
2636 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002637 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002638 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002639
Eli Friedmanc8645e32011-10-15 02:10:40 +00002640 // If the dead side doesn't have labels we need, just emit the Live part.
2641 if (!CGF.ContainsLabel(dead)) {
2642 Value *Result = Visit(live);
2643
2644 // If the live part is a throw expression, it acts like it has a void
2645 // type, so evaluating it returns a null Value*. However, a conditional
2646 // with non-void type must return a non-null Value*.
2647 if (!Result && !E->getType()->isVoidType())
2648 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2649
2650 return Result;
2651 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002652 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002653
Nate Begeman6155d732010-09-20 22:41:17 +00002654 // OpenCL: If the condition is a vector, we can treat this condition like
2655 // the select function.
David Blaikie4e4d0842012-03-11 07:00:24 +00002656 if (CGF.getContext().getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002657 && condExpr->getType()->isVectorType()) {
2658 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2659 llvm::Value *LHS = Visit(lhsExpr);
2660 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002661
Chris Lattner2acc6e32011-07-18 04:24:23 +00002662 llvm::Type *condType = ConvertType(condExpr->getType());
2663 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002664
2665 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002666 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002667
Chris Lattner2ce88422012-01-25 05:34:41 +00002668 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00002669 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2670 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2671 llvm::VectorType::get(elemType,
2672 numElem),
2673 "sext");
2674 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2675
2676 // Cast float to int to perform ANDs if necessary.
2677 llvm::Value *RHSTmp = RHS;
2678 llvm::Value *LHSTmp = LHS;
2679 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002680 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00002681 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00002682 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2683 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2684 wasCast = true;
2685 }
2686
2687 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2688 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2689 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2690 if (wasCast)
2691 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2692
2693 return tmp5;
2694 }
2695
Chris Lattner9802a512008-11-12 08:55:54 +00002696 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2697 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002698 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002699 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2700 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2701 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2702 llvm::Value *LHS = Visit(lhsExpr);
2703 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002704 if (!LHS) {
2705 // If the conditional has void type, make sure we return a null Value*.
2706 assert(!RHS && "LHS and RHS types must match");
2707 return 0;
2708 }
Chris Lattner9802a512008-11-12 08:55:54 +00002709 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2710 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002711
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002712 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2713 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002714 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002715
2716 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002717 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002718
Chris Lattner7f02f722007-08-24 05:35:26 +00002719 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002720 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002721 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002722 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002723
Chris Lattner7f02f722007-08-24 05:35:26 +00002724 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002725 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002726
Chris Lattner7f02f722007-08-24 05:35:26 +00002727 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002728 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002729 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002730 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002731
John McCall150b4622011-01-26 04:00:11 +00002732 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002733 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002734
Eli Friedman48daf592009-12-07 20:25:53 +00002735 // If the LHS or RHS is a throw expression, it will be legitimately null.
2736 if (!LHS)
2737 return RHS;
2738 if (!RHS)
2739 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002740
Chris Lattner7f02f722007-08-24 05:35:26 +00002741 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002742 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002743 PN->addIncoming(LHS, LHSBlock);
2744 PN->addIncoming(RHS, RHSBlock);
2745 return PN;
2746}
2747
2748Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002749 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002750}
2751
Chris Lattner2202bce2007-11-30 17:56:23 +00002752Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002753 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002754 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2755
2756 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002757 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002758 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2759
Mike Stump7f79f9b2009-05-29 15:46:01 +00002760 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002761 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002762}
2763
John McCall6b5a61b2011-02-07 10:33:21 +00002764Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2765 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002766}
2767
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002768Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2769 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002770 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002771
2772 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2773 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002774 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002775 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2776 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2777 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2778 if ((numElementsDst == 3 && numElementsSrc == 4)
2779 || (numElementsDst == 4 && numElementsSrc == 3)) {
2780
2781
2782 // In the case of going from int4->float3, a bitcast is needed before
2783 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002784 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002785 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002786 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002787 cast<llvm::VectorType>(DstTy)->getElementType();
2788
2789 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2790 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2791 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002792 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002793 numElementsSrc);
2794
2795 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2796 }
2797
2798 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2799
Chris Lattner5f9e2722011-07-23 10:55:15 +00002800 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002801 Args.push_back(Builder.getInt32(0));
2802 Args.push_back(Builder.getInt32(1));
2803 Args.push_back(Builder.getInt32(2));
2804
2805 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00002806 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002807
2808 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2809
2810 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2811 }
2812 }
2813
2814 return Builder.CreateBitCast(Src, DstTy, "astype");
2815}
2816
Eli Friedman276b0612011-10-11 02:20:01 +00002817Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2818 return CGF.EmitAtomicExpr(E).getScalarVal();
2819}
2820
Chris Lattner7f02f722007-08-24 05:35:26 +00002821//===----------------------------------------------------------------------===//
2822// Entry Point into this File
2823//===----------------------------------------------------------------------===//
2824
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002825/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2826/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002827Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002828 assert(E && !hasAggregateLLVMType(E->getType()) &&
2829 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002830
Devang Patel5de7a0e2011-03-07 18:29:53 +00002831 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002832 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002833 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002834 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002835 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002836 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002837 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002838}
Chris Lattner3707b252007-08-26 06:48:56 +00002839
2840/// EmitScalarConversion - Emit a conversion from the specified type to the
2841/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002842Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2843 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002844 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2845 "Invalid scalar expression to emit");
2846 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2847}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002848
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002849/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2850/// type to the specified destination type, where the destination type is an
2851/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002852Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2853 QualType SrcTy,
2854 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002855 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002856 "Invalid complex -> scalar conversion");
2857 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2858 DstTy);
2859}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002860
Chris Lattner8c11a652010-06-26 22:09:34 +00002861
2862llvm::Value *CodeGenFunction::
2863EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2864 bool isInc, bool isPre) {
2865 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2866}
2867
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002868LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2869 llvm::Value *V;
2870 // object->isa or (*object).isa
2871 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002872 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002873 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002874
2875 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002876 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00002877 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002878 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2879 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002880 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00002881 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002882 } else {
2883 if (E->isArrow())
2884 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2885 else
2886 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002887 }
2888
2889 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002890 ClassPtrTy = ClassPtrTy->getPointerTo();
2891 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00002892 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002893}
2894
Douglas Gregor6a03e342010-04-23 04:16:32 +00002895
John McCall2a416372010-12-05 02:00:02 +00002896LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002897 const CompoundAssignOperator *E) {
2898 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002899 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002900 switch (E->getOpcode()) {
2901#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002902 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002903 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002904 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002905 COMPOUND_OP(Mul);
2906 COMPOUND_OP(Div);
2907 COMPOUND_OP(Rem);
2908 COMPOUND_OP(Add);
2909 COMPOUND_OP(Sub);
2910 COMPOUND_OP(Shl);
2911 COMPOUND_OP(Shr);
2912 COMPOUND_OP(And);
2913 COMPOUND_OP(Xor);
2914 COMPOUND_OP(Or);
2915#undef COMPOUND_OP
2916
John McCall2de56d12010-08-25 11:45:40 +00002917 case BO_PtrMemD:
2918 case BO_PtrMemI:
2919 case BO_Mul:
2920 case BO_Div:
2921 case BO_Rem:
2922 case BO_Add:
2923 case BO_Sub:
2924 case BO_Shl:
2925 case BO_Shr:
2926 case BO_LT:
2927 case BO_GT:
2928 case BO_LE:
2929 case BO_GE:
2930 case BO_EQ:
2931 case BO_NE:
2932 case BO_And:
2933 case BO_Xor:
2934 case BO_Or:
2935 case BO_LAnd:
2936 case BO_LOr:
2937 case BO_Assign:
2938 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00002939 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00002940 }
2941
2942 llvm_unreachable("Unhandled compound assignment operator");
2943}