blob: d556cdfd467b2d4cf23651c939f877d4e5884169 [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel78ba3d42010-10-04 21:46:04 +000014#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Devang Patel78ba3d42010-10-04 21:46:04 +000019#include "CGDebugInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Constants.h"
26#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000028#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000029#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000030#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000031#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000049};
50
John McCall404cd162010-11-13 01:35:44 +000051static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
56}
57
Benjamin Kramer85b45212009-11-28 19:45:26 +000058class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000059 : public StmtVisitor<ScalarExprEmitter, Value*> {
60 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000061 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000062 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000063 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000064public:
65
Mike Stump7f79f9b2009-05-29 15:46:01 +000066 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000067 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000068 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000069 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Utilities
73 //===--------------------------------------------------------------------===//
74
Mike Stump7f79f9b2009-05-29 15:46:01 +000075 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000076 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
78 return I;
79 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000080
Chris Lattner2acc6e32011-07-18 04:24:23 +000081 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000082 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000084
John McCall545d9962011-06-25 02:11:03 +000085 Value *EmitLoadOfLValue(LValue LV) {
86 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000087 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000088
Chris Lattner7f02f722007-08-24 05:35:26 +000089 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
John McCall545d9962011-06-25 02:11:03 +000093 return EmitLoadOfLValue(EmitCheckedLValue(E));
Chris Lattner7f02f722007-08-24 05:35:26 +000094 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095
Chris Lattner9abc84e2007-08-26 16:42:57 +000096 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000097 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000098 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000099
Chris Lattner3707b252007-08-26 06:48:56 +0000100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
103
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000109
Anders Carlssona40a9f32010-05-22 17:45:10 +0000110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
112
John McCalldaa8e4e2010-11-15 09:13:47 +0000113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
118 }
119
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
125 }
126
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
137 if (ZI->use_empty())
138 ZI->eraseFromParent();
139 return Result;
140 }
141 }
142
Chris Lattner48431f92011-04-19 22:55:03 +0000143 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000144 }
145
Chris Lattner7f02f722007-08-24 05:35:26 +0000146 //===--------------------------------------------------------------------===//
147 // Visitor Methods
148 //===--------------------------------------------------------------------===//
149
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000150 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
152 }
153
Chris Lattner7f02f722007-08-24 05:35:26 +0000154 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000155 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000156 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 }
158 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000159
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000160 Value *VisitParenExpr(ParenExpr *PE) {
161 return Visit(PE->getSubExpr());
162 }
John McCall91a57552011-07-15 05:09:51 +0000163 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
164 return Visit(E->getReplacement());
165 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000166 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
167 return Visit(GE->getResultExpr());
168 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000169
170 // Leaves.
171 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000172 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000173 }
174 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000175 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 }
177 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000179 }
Nate Begemane7579b52007-11-15 05:40:03 +0000180 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000182 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000183 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000184 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000185 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000186 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000187 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000188 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000189 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000190 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000191 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000192 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
193 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000194 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000195
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000196 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000197 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000198 }
John McCalle996ffd2011-02-16 08:02:54 +0000199
John McCall4b9c2d22011-11-06 09:01:30 +0000200 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
201 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
202 }
203
John McCalle996ffd2011-02-16 08:02:54 +0000204 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000205 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000206 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000207
208 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000209 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000210 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000211
Chris Lattner7f02f722007-08-24 05:35:26 +0000212 // l-values.
213 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000214 Expr::EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +0000215 if (!E->EvaluateAsRValue(Result, CGF.getContext()))
John McCall189d6ef2010-10-09 01:34:31 +0000216 return EmitLoadOfLValue(E);
217
218 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
219
220 llvm::Constant *C;
Chris Lattner48431f92011-04-19 22:55:03 +0000221 if (Result.Val.isInt())
222 C = Builder.getInt(Result.Val.getInt());
223 else if (Result.Val.isFloat())
John McCall189d6ef2010-10-09 01:34:31 +0000224 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
Chris Lattner48431f92011-04-19 22:55:03 +0000225 else
John McCall189d6ef2010-10-09 01:34:31 +0000226 return EmitLoadOfLValue(E);
John McCall189d6ef2010-10-09 01:34:31 +0000227
228 // Make sure we emit a debug reference to the global variable.
229 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
230 if (!CGF.getContext().DeclMustBeEmitted(VD))
231 CGF.EmitDeclRefExprDbgValue(E, C);
232 } else if (isa<EnumConstantDecl>(E->getDecl())) {
233 CGF.EmitDeclRefExprDbgValue(E, C);
234 }
235
236 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000237 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000238 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
239 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000240 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000241 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
242 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000243 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000244 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000245 return EmitLoadOfLValue(E);
246 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000247 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000248 if (E->getMethodDecl() &&
249 E->getMethodDecl()->getResultType()->isReferenceType())
250 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000251 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000252 }
253
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000254 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000255 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000256 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000257 return V;
258 }
259
Chris Lattner7f02f722007-08-24 05:35:26 +0000260 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000261 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000262 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000263 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000264 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
265 return EmitLoadOfLValue(E);
266 }
Devang Patel35634f52007-10-24 17:18:43 +0000267
Nate Begeman0533b302009-10-18 20:10:40 +0000268 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000269
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000270 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000271 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000272 }
John McCallbc8d40d2011-06-24 21:55:10 +0000273 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000274 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000275 CGF.EmitVariablyModifiedType(E->getType());
276 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000277 }
John McCallbc8d40d2011-06-24 21:55:10 +0000278 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000279
280 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000281 if (E->getCallReturnType()->isReferenceType())
282 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000283
Chris Lattner9b655512007-08-31 22:49:20 +0000284 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000285 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000286
Chris Lattner33793202007-08-31 22:09:40 +0000287 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000288
Mike Stumpa99038c2009-02-28 09:07:16 +0000289 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000290
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000292 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
296 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 }
300 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000301 LValue LV = EmitLValue(E->getSubExpr());
302 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 }
304 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000305 LValue LV = EmitLValue(E->getSubExpr());
306 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000307 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000308
Anton Yartsev683564a2011-02-07 02:17:30 +0000309 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
310 llvm::Value *InVal,
311 llvm::Value *NextVal,
312 bool IsInc);
313
Chris Lattner8c11a652010-06-26 22:09:34 +0000314 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
315 bool isInc, bool isPre);
316
317
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000319 if (isa<MemberPointerType>(E->getType())) // never sugared
320 return CGF.CGM.getMemberPointerConstant(E);
321
Chris Lattner7f02f722007-08-24 05:35:26 +0000322 return EmitLValue(E->getSubExpr()).getAddress();
323 }
John McCallfd569002010-12-04 12:43:24 +0000324 Value *VisitUnaryDeref(const UnaryOperator *E) {
325 if (E->getType()->isVoidType())
326 return Visit(E->getSubExpr()); // the actual value should be unused
327 return EmitLoadOfLValue(E);
328 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000329 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000330 // This differs from gcc, though, most likely due to a bug in gcc.
331 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000332 return Visit(E->getSubExpr());
333 }
334 Value *VisitUnaryMinus (const UnaryOperator *E);
335 Value *VisitUnaryNot (const UnaryOperator *E);
336 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000337 Value *VisitUnaryReal (const UnaryOperator *E);
338 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000339 Value *VisitUnaryExtension(const UnaryOperator *E) {
340 return Visit(E->getSubExpr());
341 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000342
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000343 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000344 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000345 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000346 }
347
Chris Lattner04421082008-04-08 04:40:51 +0000348 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
349 return Visit(DAE->getExpr());
350 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000351 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
352 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000353 }
354
John McCall4765fa02010-12-06 08:20:24 +0000355 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000356 CGF.enterFullExpression(E);
357 CodeGenFunction::RunCleanupsScope Scope(CGF);
358 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000359 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000360 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
361 return CGF.EmitCXXNewExpr(E);
362 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000363 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
364 CGF.EmitCXXDeleteExpr(E);
365 return 0;
366 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000367 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000368 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000369 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000370
Francois Pichet6ad6f282010-12-07 00:08:36 +0000371 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000372 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000373 }
374
John Wiegley21ff2e52011-04-28 00:16:57 +0000375 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
377 }
378
John Wiegley55262202011-04-25 06:54:41 +0000379 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
380 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
381 }
382
Douglas Gregora71d8192009-09-04 17:36:40 +0000383 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
384 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000385 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000386 // operator (), and the result of such a call has type void. The only
387 // effect is the evaluation of the postfix-expression before the dot or
388 // arrow.
389 CGF.EmitScalarExpr(E->getBase());
390 return 0;
391 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000392
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000393 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000394 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000395 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000396
397 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
398 CGF.EmitCXXThrowExpr(E);
399 return 0;
400 }
401
Sebastian Redl98294de2010-09-10 21:04:00 +0000402 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000403 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000404 }
405
Chris Lattner7f02f722007-08-24 05:35:26 +0000406 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000407 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000408 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000409 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
410 case LangOptions::SOB_Undefined:
411 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
412 case LangOptions::SOB_Defined:
413 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
414 case LangOptions::SOB_Trapping:
415 return EmitOverflowCheckedBinOp(Ops);
416 }
417 }
418
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000419 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000420 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000421 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
422 }
Chris Lattner80230302010-09-11 21:47:09 +0000423 bool isTrapvOverflowBehavior() {
424 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
425 == LangOptions::SOB_Trapping;
426 }
Mike Stump2add4732009-04-01 20:28:16 +0000427 /// Create a binary op that checks for overflow.
428 /// Currently only supports +, - and *.
429 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000430 // Emit the overflow BB when -ftrapv option is activated.
431 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
432 Builder.SetInsertPoint(overflowBB);
433 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
434 Builder.CreateCall(Trap);
435 Builder.CreateUnreachable();
436 }
437 // Check for undefined division and modulus behaviors.
438 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
439 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000440 Value *EmitDiv(const BinOpInfo &Ops);
441 Value *EmitRem(const BinOpInfo &Ops);
442 Value *EmitAdd(const BinOpInfo &Ops);
443 Value *EmitSub(const BinOpInfo &Ops);
444 Value *EmitShl(const BinOpInfo &Ops);
445 Value *EmitShr(const BinOpInfo &Ops);
446 Value *EmitAnd(const BinOpInfo &Ops) {
447 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
448 }
449 Value *EmitXor(const BinOpInfo &Ops) {
450 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
451 }
452 Value *EmitOr (const BinOpInfo &Ops) {
453 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
454 }
455
Chris Lattner1f1ded92007-08-24 21:00:35 +0000456 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000457 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
458 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000459 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000460
Chris Lattner3ccf7742007-08-26 21:41:21 +0000461 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000462 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
463
464 // Binary operators and binary compound assignment operators.
465#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000466 Value *VisitBin ## OP(const BinaryOperator *E) { \
467 return Emit ## OP(EmitBinOps(E)); \
468 } \
469 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
470 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000471 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000472 HANDLEBINOP(Mul)
473 HANDLEBINOP(Div)
474 HANDLEBINOP(Rem)
475 HANDLEBINOP(Add)
476 HANDLEBINOP(Sub)
477 HANDLEBINOP(Shl)
478 HANDLEBINOP(Shr)
479 HANDLEBINOP(And)
480 HANDLEBINOP(Xor)
481 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000482#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000483
Chris Lattner7f02f722007-08-24 05:35:26 +0000484 // Comparisons.
485 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
486 unsigned SICmpOpc, unsigned FCmpOpc);
487#define VISITCOMP(CODE, UI, SI, FP) \
488 Value *VisitBin##CODE(const BinaryOperator *E) { \
489 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
490 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000491 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
492 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
493 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
494 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
495 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
496 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000497#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000498
Chris Lattner7f02f722007-08-24 05:35:26 +0000499 Value *VisitBinAssign (const BinaryOperator *E);
500
501 Value *VisitBinLAnd (const BinaryOperator *E);
502 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000503 Value *VisitBinComma (const BinaryOperator *E);
504
Eli Friedman25b825d2009-11-18 09:41:26 +0000505 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
506 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
507
Chris Lattner7f02f722007-08-24 05:35:26 +0000508 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000509 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000510 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000511 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000512 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000513 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
514 return CGF.EmitObjCStringLiteral(E);
515 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000516 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000517 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000518};
519} // end anonymous namespace.
520
521//===----------------------------------------------------------------------===//
522// Utilities
523//===----------------------------------------------------------------------===//
524
Chris Lattner9abc84e2007-08-26 16:42:57 +0000525/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000526/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000527Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000528 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000529
John McCalldaa8e4e2010-11-15 09:13:47 +0000530 if (SrcType->isRealFloatingType())
531 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000532
John McCall0bab0cd2010-08-23 01:21:21 +0000533 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
534 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000535
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000536 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000537 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000538
John McCalldaa8e4e2010-11-15 09:13:47 +0000539 if (isa<llvm::IntegerType>(Src->getType()))
540 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000541
John McCalldaa8e4e2010-11-15 09:13:47 +0000542 assert(isa<llvm::PointerType>(Src->getType()));
543 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000544}
545
Chris Lattner3707b252007-08-26 06:48:56 +0000546/// EmitScalarConversion - Emit a conversion from the specified type to the
547/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000548Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
549 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000550 SrcType = CGF.getContext().getCanonicalType(SrcType);
551 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000552 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000553
Chris Lattnercf289082007-08-26 07:21:11 +0000554 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000555
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000556 llvm::Type *SrcTy = Src->getType();
557
558 // Floating casts might be a bit special: if we're doing casts to / from half
559 // FP, we should go via special intrinsics.
560 if (SrcType->isHalfType()) {
561 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
562 SrcType = CGF.getContext().FloatTy;
563 SrcTy = llvm::Type::getFloatTy(VMContext);
564 }
565
Chris Lattner3707b252007-08-26 06:48:56 +0000566 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000567 if (DstType->isBooleanType())
568 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000569
Chris Lattner2acc6e32011-07-18 04:24:23 +0000570 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000571
572 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000573 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000574 return Src;
575
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000576 // Handle pointer conversions next: pointers can only be converted to/from
577 // other pointers and integers. Check for pointer types in terms of LLVM, as
578 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000579 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000580 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000581 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000582 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000583
Chris Lattner3707b252007-08-26 06:48:56 +0000584 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000585 // First, convert to the correct width so that we control the kind of
586 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000587 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000588 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000589 llvm::Value* IntResult =
590 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
591 // Then, cast to pointer.
592 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000593 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000594
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000595 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000596 // Must be an ptr to int cast.
597 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000598 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000599 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000600
Nate Begeman213541a2008-04-18 23:10:10 +0000601 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000602 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000603 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000604 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000605 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
606
607 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000608 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000609 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000610 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000611
612 // Splat the element across to all elements
Chris Lattner5f9e2722011-07-23 10:55:15 +0000613 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000614 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000615 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +0000616 Args.push_back(Builder.getInt32(0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000617
Chris Lattnerfb018d12011-02-15 00:14:06 +0000618 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000619 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
620 return Yay;
621 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000622
Chris Lattner3b1ae002008-02-02 04:51:41 +0000623 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000624 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000625 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000626 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000627
Chris Lattner3707b252007-08-26 06:48:56 +0000628 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000629 Value *Res = NULL;
630 llvm::Type *ResTy = DstTy;
631
632 // Cast to half via float
633 if (DstType->isHalfType())
634 DstTy = llvm::Type::getFloatTy(VMContext);
635
636 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000637 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000638 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000639 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000640 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000641 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000642 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000643 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
644 } else if (isa<llvm::IntegerType>(DstTy)) {
645 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000646 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000647 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000648 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000649 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
650 } else {
651 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
652 "Unknown real conversion");
653 if (DstTy->getTypeID() < SrcTy->getTypeID())
654 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
655 else
656 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000657 }
658
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000659 if (DstTy != ResTy) {
660 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
661 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
662 }
663
664 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000665}
666
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000667/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
668/// type to the specified destination type, where the destination type is an
669/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000670Value *ScalarExprEmitter::
671EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
672 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000673 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000674 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000675
Chris Lattnered70f0a2007-08-26 16:52:28 +0000676 // Handle conversions to bool first, they are special: comparisons against 0.
677 if (DstTy->isBooleanType()) {
678 // Complex != 0 -> (Real != 0) | (Imag != 0)
679 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
680 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
681 return Builder.CreateOr(Src.first, Src.second, "tobool");
682 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000683
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000684 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
685 // the imaginary part of the complex value is discarded and the value of the
686 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000687 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000688 return EmitScalarConversion(Src.first, SrcTy, DstTy);
689}
690
Anders Carlssona40a9f32010-05-22 17:45:10 +0000691Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000692 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
693 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
694
695 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000696}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000697
Chris Lattner7f02f722007-08-24 05:35:26 +0000698//===----------------------------------------------------------------------===//
699// Visitor Methods
700//===----------------------------------------------------------------------===//
701
702Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000703 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000704 if (E->getType()->isVoidType())
705 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000706 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000707}
708
Eli Friedmand38617c2008-05-14 19:38:39 +0000709Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000710 // Vector Mask Case
711 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000712 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000713 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
714 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
715 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000716
Chris Lattner2acc6e32011-07-18 04:24:23 +0000717 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000718 unsigned LHSElts = LTy->getNumElements();
719
720 if (E->getNumSubExprs() == 3) {
721 Mask = CGF.EmitScalarExpr(E->getExpr(2));
722
723 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000724 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000725 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000726 concat.push_back(Builder.getInt32(2*i));
727 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000728 }
729
Chris Lattnerfb018d12011-02-15 00:14:06 +0000730 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000731 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
732 LHSElts *= 2;
733 } else {
734 Mask = RHS;
735 }
736
Chris Lattner2acc6e32011-07-18 04:24:23 +0000737 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000738 llvm::Constant* EltMask;
739
740 // Treat vec3 like vec4.
741 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
742 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
743 (1 << llvm::Log2_32(LHSElts+2))-1);
744 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
745 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
746 (1 << llvm::Log2_32(LHSElts+1))-1);
747 else
748 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
749 (1 << llvm::Log2_32(LHSElts))-1);
750
751 // Mask off the high bits of each shuffle index.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000752 SmallVector<llvm::Constant *, 32> MaskV;
Nate Begeman37b6a572010-06-08 00:16:34 +0000753 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
754 MaskV.push_back(EltMask);
755
Chris Lattnerfb018d12011-02-15 00:14:06 +0000756 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000757 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
758
759 // newv = undef
760 // mask = mask & maskbits
761 // for each elt
762 // n = extract mask i
763 // x = extract val n
764 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000765 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000766 MTy->getNumElements());
767 Value* NewV = llvm::UndefValue::get(RTy);
768 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000769 Value *Indx = Builder.getInt32(i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000770 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000771 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000772
773 // Handle vec3 special since the index will be off by one for the RHS.
774 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
775 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000776 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000777 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000778 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000779 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
780 }
781 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
782 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
783 }
784 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000785 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000786
Eli Friedmand38617c2008-05-14 19:38:39 +0000787 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
788 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000789
790 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000791 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000792 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000793 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000794 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
795 if (VTy->getNumElements() == 3 && Idx > 3)
796 Idx -= 1;
797 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000798 }
799
Chris Lattnerfb018d12011-02-15 00:14:06 +0000800 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000801 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
802}
Eli Friedman28665272009-11-26 03:22:21 +0000803Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
804 Expr::EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +0000805 if (E->EvaluateAsRValue(Result, CGF.getContext()) && Result.Val.isInt()) {
Eli Friedman28665272009-11-26 03:22:21 +0000806 if (E->isArrow())
807 CGF.EmitScalarExpr(E->getBase());
808 else
809 EmitLValue(E->getBase());
Chris Lattner48431f92011-04-19 22:55:03 +0000810 return Builder.getInt(Result.Val.getInt());
Eli Friedman28665272009-11-26 03:22:21 +0000811 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000812
813 // Emit debug info for aggregate now, if it was delayed to reduce
814 // debug info size.
815 CGDebugInfo *DI = CGF.getDebugInfo();
816 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
817 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
818 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000819 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000820 DI->getOrCreateRecordType(PTy->getPointeeType(),
821 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000822 }
Eli Friedman28665272009-11-26 03:22:21 +0000823 return EmitLoadOfLValue(E);
824}
Eli Friedmand38617c2008-05-14 19:38:39 +0000825
Chris Lattner7f02f722007-08-24 05:35:26 +0000826Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000827 TestAndClearIgnoreResultAssign();
828
Chris Lattner7f02f722007-08-24 05:35:26 +0000829 // Emit subscript expressions in rvalue context's. For most cases, this just
830 // loads the lvalue formed by the subscript expr. However, we have to be
831 // careful, because the base of a vector subscript is occasionally an rvalue,
832 // so we can't get it as an lvalue.
833 if (!E->getBase()->getType()->isVectorType())
834 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000835
Chris Lattner7f02f722007-08-24 05:35:26 +0000836 // Handle the vector case. The base must be a vector, the index must be an
837 // integer value.
838 Value *Base = Visit(E->getBase());
839 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000840 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000841 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000842 return Builder.CreateExtractElement(Base, Idx, "vecext");
843}
844
Nate Begeman0533b302009-10-18 20:10:40 +0000845static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000846 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000847 int MV = SVI->getMaskValue(Idx);
848 if (MV == -1)
849 return llvm::UndefValue::get(I32Ty);
850 return llvm::ConstantInt::get(I32Ty, Off+MV);
851}
852
853Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
854 bool Ignore = TestAndClearIgnoreResultAssign();
855 (void)Ignore;
856 assert (Ignore == false && "init list ignored");
857 unsigned NumInitElements = E->getNumInits();
858
859 if (E->hadArrayRangeDesignator())
860 CGF.ErrorUnsupported(E, "GNU array range designator extension");
861
Chris Lattner2acc6e32011-07-18 04:24:23 +0000862 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000863 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
864
Sebastian Redlcea8d962011-09-24 17:48:14 +0000865 if (!VType) {
866 if (NumInitElements == 0) {
867 // C++11 value-initialization for the scalar.
868 return EmitNullValue(E->getType());
869 }
870 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +0000871 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +0000872 }
Nate Begeman0533b302009-10-18 20:10:40 +0000873
874 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000875
876 // Loop over initializers collecting the Value for each, and remembering
877 // whether the source was swizzle (ExtVectorElementExpr). This will allow
878 // us to fold the shuffle for the swizzle into the shuffle for the vector
879 // initializer, since LLVM optimizers generally do not want to touch
880 // shuffles.
881 unsigned CurIdx = 0;
882 bool VIsUndefShuffle = false;
883 llvm::Value *V = llvm::UndefValue::get(VType);
884 for (unsigned i = 0; i != NumInitElements; ++i) {
885 Expr *IE = E->getInit(i);
886 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000887 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000888
Chris Lattner2acc6e32011-07-18 04:24:23 +0000889 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000890
891 // Handle scalar elements. If the scalar initializer is actually one
892 // element of a different vector of the same width, use shuffle instead of
893 // extract+insert.
894 if (!VVT) {
895 if (isa<ExtVectorElementExpr>(IE)) {
896 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
897
898 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
899 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
900 Value *LHS = 0, *RHS = 0;
901 if (CurIdx == 0) {
902 // insert into undef -> shuffle (src, undef)
903 Args.push_back(C);
904 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000905 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000906
907 LHS = EI->getVectorOperand();
908 RHS = V;
909 VIsUndefShuffle = true;
910 } else if (VIsUndefShuffle) {
911 // insert into undefshuffle && size match -> shuffle (v, src)
912 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
913 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000914 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000915 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Nate Begeman0533b302009-10-18 20:10:40 +0000916 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000917 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000918
919 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
920 RHS = EI->getVectorOperand();
921 VIsUndefShuffle = false;
922 }
923 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000924 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000925 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
926 ++CurIdx;
927 continue;
928 }
929 }
930 }
Chris Lattner48431f92011-04-19 22:55:03 +0000931 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
932 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000933 VIsUndefShuffle = false;
934 ++CurIdx;
935 continue;
936 }
937
938 unsigned InitElts = VVT->getNumElements();
939
940 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
941 // input is the same width as the vector being constructed, generate an
942 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000943 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000944 if (isa<ExtVectorElementExpr>(IE)) {
945 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
946 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000947 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000948
949 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000950 for (unsigned j = 0; j != CurIdx; ++j) {
951 // If the current vector initializer is a shuffle with undef, merge
952 // this shuffle directly into it.
953 if (VIsUndefShuffle) {
954 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000955 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000956 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000957 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000958 }
959 }
960 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000961 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000962 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000963 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000964
965 if (VIsUndefShuffle)
966 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
967
968 Init = SVOp;
969 }
970 }
971
972 // Extend init to result vector length, and then shuffle its contribution
973 // to the vector initializer into V.
974 if (Args.empty()) {
975 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000976 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000977 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000978 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000979 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000980 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000981 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000982
983 Args.clear();
984 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000985 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000986 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000987 Args.push_back(Builder.getInt32(j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000988 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000989 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000990 }
991
992 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
993 // merging subsequent shuffles into this one.
994 if (CurIdx == 0)
995 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000996 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000997 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
998 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
999 CurIdx += InitElts;
1000 }
1001
1002 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1003 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001004 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +00001005
1006 // Emit remaining default initializers
1007 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +00001008 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +00001009 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1010 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1011 }
1012 return V;
1013}
1014
Anders Carlssona3697c92009-11-23 17:57:54 +00001015static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1016 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001017
John McCall2de56d12010-08-25 11:45:40 +00001018 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001019 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001020
1021 if (isa<CXXThisExpr>(E)) {
1022 // We always assume that 'this' is never null.
1023 return false;
1024 }
1025
1026 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001027 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001028 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001029 return false;
1030 }
1031
1032 return true;
1033}
1034
Chris Lattner7f02f722007-08-24 05:35:26 +00001035// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1036// have to handle a more broad range of conversions than explicit casts, as they
1037// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001038Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001039 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001040 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001041 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001042
Mike Stump7f79f9b2009-05-29 15:46:01 +00001043 if (!DestTy->isVoidType())
1044 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001045
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001046 // Since almost all cast kinds apply to scalars, this switch doesn't have
1047 // a default case, so the compiler will warn on a missing case. The cases
1048 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001049 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001050 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1051
John McCall2de56d12010-08-25 11:45:40 +00001052 case CK_LValueBitCast:
1053 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001054 Value *V = EmitLValue(E).getAddress();
1055 V = Builder.CreateBitCast(V,
1056 ConvertType(CGF.getContext().getPointerType(DestTy)));
John McCall545d9962011-06-25 02:11:03 +00001057 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001058 }
John McCalldc05b112011-09-10 01:16:55 +00001059
John McCall1d9b3b22011-09-09 05:25:32 +00001060 case CK_CPointerToObjCPointerCast:
1061 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001062 case CK_AnyPointerToBlockPointerCast:
1063 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001064 Value *Src = Visit(const_cast<Expr*>(E));
1065 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1066 }
John McCall2de56d12010-08-25 11:45:40 +00001067 case CK_NoOp:
1068 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001069 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001070
John McCall2de56d12010-08-25 11:45:40 +00001071 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001072 const CXXRecordDecl *DerivedClassDecl =
1073 DestTy->getCXXRecordDeclForPointerType();
1074
Anders Carlssona04efdf2010-04-24 21:23:59 +00001075 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001076 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001077 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001078 }
John McCall2de56d12010-08-25 11:45:40 +00001079 case CK_UncheckedDerivedToBase:
1080 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001081 const RecordType *DerivedClassTy =
1082 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1083 CXXRecordDecl *DerivedClassDecl =
1084 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1085
Anders Carlsson34a2d382010-04-24 21:06:20 +00001086 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001087 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001088 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001089 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001090 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001091 Value *V = Visit(const_cast<Expr*>(E));
1092 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1093 return CGF.EmitDynamicCast(V, DCE);
1094 }
Eli Friedmand8889622009-11-27 04:41:50 +00001095
John McCall2de56d12010-08-25 11:45:40 +00001096 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001097 assert(E->getType()->isArrayType() &&
1098 "Array to pointer decay must have array source type!");
1099
1100 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1101
1102 // Note that VLA pointers are always decayed, so we don't need to do
1103 // anything here.
1104 if (!E->getType()->isVariableArrayType()) {
1105 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1106 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1107 ->getElementType()) &&
1108 "Expected pointer to array");
1109 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1110 }
1111
Chris Lattner410b12e2011-07-20 04:31:01 +00001112 // Make sure the array decay ends up being the right type. This matters if
1113 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001114 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001115 }
John McCall2de56d12010-08-25 11:45:40 +00001116 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001117 return EmitLValue(E).getAddress();
1118
John McCall404cd162010-11-13 01:35:44 +00001119 case CK_NullToPointer:
1120 if (MustVisitNullValue(E))
1121 (void) Visit(E);
1122
1123 return llvm::ConstantPointerNull::get(
1124 cast<llvm::PointerType>(ConvertType(DestTy)));
1125
John McCall2de56d12010-08-25 11:45:40 +00001126 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001127 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001128 (void) Visit(E);
1129
John McCall0bab0cd2010-08-23 01:21:21 +00001130 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1131 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1132 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001133
John McCall2de56d12010-08-25 11:45:40 +00001134 case CK_BaseToDerivedMemberPointer:
1135 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001136 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001137
1138 // Note that the AST doesn't distinguish between checked and
1139 // unchecked member pointer conversions, so we always have to
1140 // implement checked conversions here. This is inefficient when
1141 // actual control flow may be required in order to perform the
1142 // check, which it is for data member pointers (but not member
1143 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001144 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001145 }
John McCallf85e1932011-06-15 23:02:42 +00001146
John McCall33e56f32011-09-10 06:18:15 +00001147 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001148 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001149 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001150 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001151 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001152 llvm::Value *value = Visit(E);
1153 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1154 return CGF.EmitObjCConsumeObject(E->getType(), value);
1155 }
John McCall348f16f2011-10-04 06:23:45 +00001156 case CK_ARCExtendBlockObject:
1157 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001158
John McCall2bb5d002010-11-13 09:02:35 +00001159 case CK_FloatingRealToComplex:
1160 case CK_FloatingComplexCast:
1161 case CK_IntegralRealToComplex:
1162 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001163 case CK_IntegralComplexToFloatingComplex:
1164 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001165 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001166 case CK_ToUnion:
1167 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001168 break;
John McCallf6a16482010-12-04 03:47:34 +00001169
John McCall0ae287a2010-12-01 04:43:34 +00001170 case CK_LValueToRValue:
1171 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001172 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001173 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001174
John McCall2de56d12010-08-25 11:45:40 +00001175 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001176 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001177
Anders Carlsson82debc72009-10-18 18:12:03 +00001178 // First, convert to the correct width so that we control the kind of
1179 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001180 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001181 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001182 llvm::Value* IntResult =
1183 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001184
Anders Carlsson82debc72009-10-18 18:12:03 +00001185 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001186 }
Eli Friedman65949422011-06-25 02:58:47 +00001187 case CK_PointerToIntegral:
1188 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1189 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001190
John McCall2de56d12010-08-25 11:45:40 +00001191 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001192 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001193 return 0;
1194 }
John McCall2de56d12010-08-25 11:45:40 +00001195 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001196 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001197 Value *Elt = Visit(const_cast<Expr*>(E));
1198
1199 // Insert the element in element zero of an undef vector
1200 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001201 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001202 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001203
1204 // Splat the element across to all elements
Chris Lattner5f9e2722011-07-23 10:55:15 +00001205 SmallVector<llvm::Constant*, 16> Args;
Eli Friedmanad35a832009-11-16 21:33:53 +00001206 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001207 llvm::Constant *Zero = Builder.getInt32(0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001208 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001209 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001210
Chris Lattnerfb018d12011-02-15 00:14:06 +00001211 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001212 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1213 return Yay;
1214 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001215
John McCall2de56d12010-08-25 11:45:40 +00001216 case CK_IntegralCast:
1217 case CK_IntegralToFloating:
1218 case CK_FloatingToIntegral:
1219 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001220 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001221 case CK_IntegralToBoolean:
1222 return EmitIntToBoolConversion(Visit(E));
1223 case CK_PointerToBoolean:
1224 return EmitPointerToBoolConversion(Visit(E));
1225 case CK_FloatingToBoolean:
1226 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001227 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001228 llvm::Value *MemPtr = Visit(E);
1229 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1230 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001231 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001232
1233 case CK_FloatingComplexToReal:
1234 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001235 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001236
1237 case CK_FloatingComplexToBoolean:
1238 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001239 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001240
1241 // TODO: kill this function off, inline appropriate case here
1242 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1243 }
1244
John McCall0bab0cd2010-08-23 01:21:21 +00001245 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001246
John McCall61ad0e62010-11-16 06:21:14 +00001247 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001248 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001249}
1250
Chris Lattner33793202007-08-31 22:09:40 +00001251Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001252 CodeGenFunction::StmtExprEvaluation eval(CGF);
1253 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1254 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001255}
1256
Mike Stumpa99038c2009-02-28 09:07:16 +00001257Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
John McCalla5bcb8f2011-03-16 02:53:38 +00001258 LValue LV = CGF.EmitBlockDeclRefLValue(E);
John McCall545d9962011-06-25 02:11:03 +00001259 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Mike Stump4e7a1f72009-02-21 20:00:35 +00001260}
Chris Lattner33793202007-08-31 22:09:40 +00001261
Chris Lattner7f02f722007-08-24 05:35:26 +00001262//===----------------------------------------------------------------------===//
1263// Unary Operators
1264//===----------------------------------------------------------------------===//
1265
Chris Lattner8c11a652010-06-26 22:09:34 +00001266llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001267EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1268 llvm::Value *InVal,
1269 llvm::Value *NextVal, bool IsInc) {
1270 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1271 case LangOptions::SOB_Undefined:
1272 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1273 break;
1274 case LangOptions::SOB_Defined:
1275 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1276 break;
1277 case LangOptions::SOB_Trapping:
1278 BinOpInfo BinOp;
1279 BinOp.LHS = InVal;
1280 BinOp.RHS = NextVal;
1281 BinOp.Ty = E->getType();
1282 BinOp.Opcode = BO_Add;
1283 BinOp.E = E;
1284 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001285 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001286 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001287}
1288
John McCall5936e332011-02-15 09:22:45 +00001289llvm::Value *
1290ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1291 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001292
John McCall5936e332011-02-15 09:22:45 +00001293 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001294 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001295 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001296
John McCall5936e332011-02-15 09:22:45 +00001297 int amount = (isInc ? 1 : -1);
1298
1299 // Special case of integer increment that we have to check first: bool++.
1300 // Due to promotion rules, we get:
1301 // bool++ -> bool = bool + 1
1302 // -> bool = (int)bool + 1
1303 // -> bool = ((int)bool + 1 != 0)
1304 // An interesting aspect of this is that increment is always true.
1305 // Decrement does not have this property.
1306 if (isInc && type->isBooleanType()) {
1307 value = Builder.getTrue();
1308
1309 // Most common case by far: integer increment.
1310 } else if (type->isIntegerType()) {
1311
1312 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1313
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001314 // Note that signed integer inc/dec with width less than int can't
1315 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001316 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001317 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001318 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001319 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001320 else
1321 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1322
1323 // Next most common: pointer increment.
1324 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1325 QualType type = ptr->getPointeeType();
1326
1327 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001328 if (const VariableArrayType *vla
1329 = CGF.getContext().getAsVariableArrayType(type)) {
1330 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001331 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Chris Lattner2cb42222011-03-01 00:03:48 +00001332 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001333 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001334 else
John McCallbc8d40d2011-06-24 21:55:10 +00001335 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001336
1337 // Arithmetic on function pointers (!) is just +-1.
1338 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001339 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001340
1341 value = CGF.EmitCastToVoidPtr(value);
Chris Lattner2cb42222011-03-01 00:03:48 +00001342 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1343 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1344 else
1345 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001346 value = Builder.CreateBitCast(value, input->getType());
1347
1348 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001349 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001350 llvm::Value *amt = Builder.getInt32(amount);
Chris Lattner2cb42222011-03-01 00:03:48 +00001351 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1352 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1353 else
1354 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001355 }
1356
1357 // Vector increment/decrement.
1358 } else if (type->isVectorType()) {
1359 if (type->hasIntegerRepresentation()) {
1360 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1361
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001362 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001363 } else {
1364 value = Builder.CreateFAdd(
1365 value,
1366 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001367 isInc ? "inc" : "dec");
1368 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001369
John McCall5936e332011-02-15 09:22:45 +00001370 // Floating point.
1371 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001372 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001373 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001374
1375 if (type->isHalfType()) {
1376 // Another special case: half FP increment should be done via float
1377 value =
1378 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1379 input);
1380 }
1381
John McCall5936e332011-02-15 09:22:45 +00001382 if (value->getType()->isFloatTy())
1383 amt = llvm::ConstantFP::get(VMContext,
1384 llvm::APFloat(static_cast<float>(amount)));
1385 else if (value->getType()->isDoubleTy())
1386 amt = llvm::ConstantFP::get(VMContext,
1387 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001388 else {
John McCall5936e332011-02-15 09:22:45 +00001389 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001390 bool ignored;
1391 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1392 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001393 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001394 }
John McCall5936e332011-02-15 09:22:45 +00001395 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1396
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001397 if (type->isHalfType())
1398 value =
1399 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1400 value);
1401
John McCall5936e332011-02-15 09:22:45 +00001402 // Objective-C pointer types.
1403 } else {
1404 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1405 value = CGF.EmitCastToVoidPtr(value);
1406
1407 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1408 if (!isInc) size = -size;
1409 llvm::Value *sizeValue =
1410 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1411
Chris Lattner2cb42222011-03-01 00:03:48 +00001412 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1413 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1414 else
1415 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001416 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001417 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001418
Chris Lattner8c11a652010-06-26 22:09:34 +00001419 // Store the updated result through the lvalue.
1420 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001421 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001422 else
John McCall545d9962011-06-25 02:11:03 +00001423 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001424
Chris Lattner8c11a652010-06-26 22:09:34 +00001425 // If this is a postinc, return the value read from memory, otherwise use the
1426 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001427 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001428}
1429
1430
1431
Chris Lattner7f02f722007-08-24 05:35:26 +00001432Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001433 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001434 // Emit unary minus with EmitSub so we handle overflow cases etc.
1435 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001436 BinOp.RHS = Visit(E->getSubExpr());
1437
1438 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1439 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1440 else
1441 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001442 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001443 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001444 BinOp.E = E;
1445 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001446}
1447
1448Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001449 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001450 Value *Op = Visit(E->getSubExpr());
1451 return Builder.CreateNot(Op, "neg");
1452}
1453
1454Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1455 // Compare operand to zero.
1456 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001457
Chris Lattner7f02f722007-08-24 05:35:26 +00001458 // Invert value.
1459 // TODO: Could dynamically modify easy computations here. For example, if
1460 // the operand is an icmp ne, turn into icmp eq.
1461 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001462
Anders Carlsson9f84d882009-05-19 18:44:53 +00001463 // ZExt result to the expr type.
1464 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001465}
1466
Eli Friedman0027d2b2010-08-05 09:58:49 +00001467Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1468 // Try folding the offsetof to a constant.
1469 Expr::EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00001470 if (E->EvaluateAsRValue(EvalResult, CGF.getContext()))
Chris Lattner48431f92011-04-19 22:55:03 +00001471 return Builder.getInt(EvalResult.Val.getInt());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001472
1473 // Loop over the components of the offsetof to compute the value.
1474 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001475 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001476 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1477 QualType CurrentType = E->getTypeSourceInfo()->getType();
1478 for (unsigned i = 0; i != n; ++i) {
1479 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001480 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001481 switch (ON.getKind()) {
1482 case OffsetOfExpr::OffsetOfNode::Array: {
1483 // Compute the index
1484 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1485 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001486 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001487 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1488
1489 // Save the element type
1490 CurrentType =
1491 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1492
1493 // Compute the element size
1494 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1495 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1496
1497 // Multiply out to compute the result
1498 Offset = Builder.CreateMul(Idx, ElemSize);
1499 break;
1500 }
1501
1502 case OffsetOfExpr::OffsetOfNode::Field: {
1503 FieldDecl *MemberDecl = ON.getField();
1504 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1505 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1506
1507 // Compute the index of the field in its parent.
1508 unsigned i = 0;
1509 // FIXME: It would be nice if we didn't have to loop here!
1510 for (RecordDecl::field_iterator Field = RD->field_begin(),
1511 FieldEnd = RD->field_end();
1512 Field != FieldEnd; (void)++Field, ++i) {
1513 if (*Field == MemberDecl)
1514 break;
1515 }
1516 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1517
1518 // Compute the offset to the field
1519 int64_t OffsetInt = RL.getFieldOffset(i) /
1520 CGF.getContext().getCharWidth();
1521 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1522
1523 // Save the element type.
1524 CurrentType = MemberDecl->getType();
1525 break;
1526 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001527
Eli Friedman0027d2b2010-08-05 09:58:49 +00001528 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001529 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001530
Eli Friedman0027d2b2010-08-05 09:58:49 +00001531 case OffsetOfExpr::OffsetOfNode::Base: {
1532 if (ON.getBase()->isVirtual()) {
1533 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1534 continue;
1535 }
1536
1537 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1538 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1539
1540 // Save the element type.
1541 CurrentType = ON.getBase()->getType();
1542
1543 // Compute the offset to the base.
1544 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1545 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001546 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001547 CGF.getContext().getCharWidth();
1548 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1549 break;
1550 }
1551 }
1552 Result = Builder.CreateAdd(Result, Offset);
1553 }
1554 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001555}
1556
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001557/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001558/// argument of the sizeof expression as an integer.
1559Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001560ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1561 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001562 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001563 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001564 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001565 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1566 if (E->isArgumentType()) {
1567 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001568 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001569 } else {
1570 // C99 6.5.3.4p2: If the argument is an expression of type
1571 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001572 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001573 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001574
John McCallbc8d40d2011-06-24 21:55:10 +00001575 QualType eltType;
1576 llvm::Value *numElts;
1577 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1578
1579 llvm::Value *size = numElts;
1580
1581 // Scale the number of non-VLA elements by the non-VLA element size.
1582 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1583 if (!eltSize.isOne())
1584 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1585
1586 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001587 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001588 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001589
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001590 // If this isn't sizeof(vla), the result must be constant; use the constant
1591 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001592 Expr::EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00001593 E->EvaluateAsRValue(Result, CGF.getContext());
Chris Lattner48431f92011-04-19 22:55:03 +00001594 return Builder.getInt(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001595}
1596
Chris Lattner46f93d02007-08-24 21:20:17 +00001597Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1598 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001599 if (Op->getType()->isAnyComplexType()) {
1600 // If it's an l-value, load through the appropriate subobject l-value.
1601 // Note that we have to ask E because Op might be an l-value that
1602 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001603 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001604 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001605
1606 // Otherwise, calculate and project.
1607 return CGF.EmitComplexExpr(Op, false, true).first;
1608 }
1609
Chris Lattner46f93d02007-08-24 21:20:17 +00001610 return Visit(Op);
1611}
John McCallb418d742010-11-16 10:08:07 +00001612
Chris Lattner46f93d02007-08-24 21:20:17 +00001613Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1614 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001615 if (Op->getType()->isAnyComplexType()) {
1616 // If it's an l-value, load through the appropriate subobject l-value.
1617 // Note that we have to ask E because Op might be an l-value that
1618 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001619 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001620 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001621
1622 // Otherwise, calculate and project.
1623 return CGF.EmitComplexExpr(Op, true, false).second;
1624 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001625
Mike Stump7f79f9b2009-05-29 15:46:01 +00001626 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1627 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001628 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001629 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001630}
1631
Chris Lattner7f02f722007-08-24 05:35:26 +00001632//===----------------------------------------------------------------------===//
1633// Binary Operators
1634//===----------------------------------------------------------------------===//
1635
1636BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001637 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001638 BinOpInfo Result;
1639 Result.LHS = Visit(E->getLHS());
1640 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001641 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001642 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001643 Result.E = E;
1644 return Result;
1645}
1646
Douglas Gregor6a03e342010-04-23 04:16:32 +00001647LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1648 const CompoundAssignOperator *E,
1649 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001650 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001651 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001652 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001653
Eli Friedmanab3a8522009-03-28 01:22:36 +00001654 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001655 // This needs to go through the complex expression emitter, but it's a tad
1656 // complicated to do that... I'm leaving it out for now. (Note that we do
1657 // actually need the imaginary part of the RHS for multiplication and
1658 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001659 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001660 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001661 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001662 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001663
Mike Stumpcc0442f2009-05-22 19:07:20 +00001664 // Emit the RHS first. __block variables need to have the rhs evaluated
1665 // first, plus this should improve codegen a little.
1666 OpInfo.RHS = Visit(E->getRHS());
1667 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001668 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001669 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001670 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001671 LValue LHSLV = EmitCheckedLValue(E->getLHS());
John McCall545d9962011-06-25 02:11:03 +00001672 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001673 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1674 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001675
Chris Lattner1f1ded92007-08-24 21:00:35 +00001676 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001677 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001678
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001679 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001680 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001681
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001682 // Store the result value into the LHS lvalue. Bit-fields are handled
1683 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1684 // 'An assignment expression has the value of the left operand after the
1685 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001686 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001687 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001688 else
John McCall545d9962011-06-25 02:11:03 +00001689 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001690
Douglas Gregor6a03e342010-04-23 04:16:32 +00001691 return LHSLV;
1692}
1693
1694Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1695 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1696 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001697 Value *RHS;
1698 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1699
1700 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001701 if (Ignore)
1702 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001703
John McCallb418d742010-11-16 10:08:07 +00001704 // The result of an assignment in C is the assigned r-value.
1705 if (!CGF.getContext().getLangOptions().CPlusPlus)
1706 return RHS;
1707
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001708 // If the lvalue is non-volatile, return the computed value of the assignment.
1709 if (!LHS.isVolatileQualified())
1710 return RHS;
1711
1712 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001713 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001714}
1715
Chris Lattner80230302010-09-11 21:47:09 +00001716void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1717 const BinOpInfo &Ops,
1718 llvm::Value *Zero, bool isDiv) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001719 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
Chris Lattner80230302010-09-11 21:47:09 +00001720 llvm::BasicBlock *contBB =
Bill Wendling14ef3192011-07-07 21:13:10 +00001721 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1722 llvm::next(insertPt));
1723 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001724
Chris Lattner2acc6e32011-07-18 04:24:23 +00001725 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001726
1727 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1728 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001729 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001730 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1731
1732 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1733 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1734 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1735 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1736 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1737 overflowBB, contBB);
1738 } else {
1739 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1740 overflowBB, contBB);
1741 }
1742 EmitOverflowBB(overflowBB);
1743 Builder.SetInsertPoint(contBB);
1744}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001745
Chris Lattner7f02f722007-08-24 05:35:26 +00001746Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001747 if (isTrapvOverflowBehavior()) {
1748 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1749
1750 if (Ops.Ty->isIntegerType())
1751 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1752 else if (Ops.Ty->isRealFloatingType()) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001753 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1754 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1755 llvm::next(insertPt));
Chris Lattner80230302010-09-11 21:47:09 +00001756 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1757 CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001758 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1759 overflowBB, DivCont);
1760 EmitOverflowBB(overflowBB);
1761 Builder.SetInsertPoint(DivCont);
1762 }
1763 }
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001764 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1765 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1766 if (CGF.getContext().getLangOptions().OpenCL) {
1767 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1768 llvm::Type *ValTy = Val->getType();
1769 if (ValTy->isFloatTy() ||
1770 (isa<llvm::VectorType>(ValTy) &&
1771 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
1772 CGF.SetFPAccuracy(Val, 5, 2);
1773 }
1774 return Val;
1775 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001776 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001777 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1778 else
1779 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1780}
1781
1782Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1783 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001784 if (isTrapvOverflowBehavior()) {
1785 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1786
1787 if (Ops.Ty->isIntegerType())
1788 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1789 }
1790
Eli Friedman52d68742011-04-10 04:44:11 +00001791 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001792 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1793 else
1794 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1795}
1796
Mike Stump2add4732009-04-01 20:28:16 +00001797Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1798 unsigned IID;
1799 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001800
Chris Lattner9a207232010-06-26 21:48:21 +00001801 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001802 case BO_Add:
1803 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001804 OpID = 1;
1805 IID = llvm::Intrinsic::sadd_with_overflow;
1806 break;
John McCall2de56d12010-08-25 11:45:40 +00001807 case BO_Sub:
1808 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001809 OpID = 2;
1810 IID = llvm::Intrinsic::ssub_with_overflow;
1811 break;
John McCall2de56d12010-08-25 11:45:40 +00001812 case BO_Mul:
1813 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001814 OpID = 3;
1815 IID = llvm::Intrinsic::smul_with_overflow;
1816 break;
1817 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001818 llvm_unreachable("Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001819 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001820 }
Mike Stump035cf892009-04-02 18:15:54 +00001821 OpID <<= 1;
1822 OpID |= 1;
1823
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001824 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001825
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001826 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001827
1828 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1829 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1830 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1831
1832 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001833 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001834 llvm::Function::iterator insertPt = initialBB;
1835 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1836 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001837 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001838
1839 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1840
Chris Lattner93a00352010-08-07 00:20:46 +00001841 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001842 const std::string *handlerName =
1843 &CGF.getContext().getLangOptions().OverflowHandler;
1844 if (handlerName->empty()) {
1845 EmitOverflowBB(overflowBB);
1846 Builder.SetInsertPoint(continueBB);
1847 return result;
1848 }
1849
1850 // If an overflow handler is set, then we want to call it and then use its
1851 // result, if it returns.
1852 Builder.SetInsertPoint(overflowBB);
1853
1854 // Get the overflow handler.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001855 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1856 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001857 llvm::FunctionType *handlerTy =
1858 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1859 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1860
1861 // Sign extend the args to 64-bit, so that we can use the same handler for
1862 // all types of overflow.
1863 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1864 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1865
1866 // Call the handler with the two arguments, the operation, and the size of
1867 // the result.
1868 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1869 Builder.getInt8(OpID),
1870 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1871
1872 // Truncate the result back to the desired size.
1873 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1874 Builder.CreateBr(continueBB);
1875
Mike Stump2add4732009-04-01 20:28:16 +00001876 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001877 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001878 phi->addIncoming(result, initialBB);
1879 phi->addIncoming(handlerResult, overflowBB);
1880
1881 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001882}
Chris Lattner7f02f722007-08-24 05:35:26 +00001883
John McCall913dab22011-06-25 01:32:37 +00001884/// Emit pointer + index arithmetic.
1885static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1886 const BinOpInfo &op,
1887 bool isSubtraction) {
1888 // Must have binary (not unary) expr here. Unary pointer
1889 // increment/decrement doesn't use this path.
1890 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1891
1892 Value *pointer = op.LHS;
1893 Expr *pointerOperand = expr->getLHS();
1894 Value *index = op.RHS;
1895 Expr *indexOperand = expr->getRHS();
1896
1897 // In a subtraction, the LHS is always the pointer.
1898 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1899 std::swap(pointer, index);
1900 std::swap(pointerOperand, indexOperand);
1901 }
1902
1903 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1904 if (width != CGF.PointerWidthInBits) {
1905 // Zero-extend or sign-extend the pointer value according to
1906 // whether the index is signed or not.
1907 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1908 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1909 "idx.ext");
1910 }
1911
1912 // If this is subtraction, negate the index.
1913 if (isSubtraction)
1914 index = CGF.Builder.CreateNeg(index, "idx.neg");
1915
1916 const PointerType *pointerType
1917 = pointerOperand->getType()->getAs<PointerType>();
1918 if (!pointerType) {
1919 QualType objectType = pointerOperand->getType()
1920 ->castAs<ObjCObjectPointerType>()
1921 ->getPointeeType();
1922 llvm::Value *objectSize
1923 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1924
1925 index = CGF.Builder.CreateMul(index, objectSize);
1926
1927 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1928 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1929 return CGF.Builder.CreateBitCast(result, pointer->getType());
1930 }
1931
1932 QualType elementType = pointerType->getPointeeType();
1933 if (const VariableArrayType *vla
1934 = CGF.getContext().getAsVariableArrayType(elementType)) {
1935 // The element count here is the total number of non-VLA elements.
1936 llvm::Value *numElements = CGF.getVLASize(vla).first;
1937
1938 // Effectively, the multiply by the VLA size is part of the GEP.
1939 // GEP indexes are signed, and scaling an index isn't permitted to
1940 // signed-overflow, so we use the same semantics for our explicit
1941 // multiply. We suppress this if overflow is not undefined behavior.
1942 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1943 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1944 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1945 } else {
1946 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1947 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001948 }
John McCall913dab22011-06-25 01:32:37 +00001949 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001950 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001951
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001952 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1953 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1954 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001955 if (elementType->isVoidType() || elementType->isFunctionType()) {
1956 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1957 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1958 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001959 }
1960
John McCall913dab22011-06-25 01:32:37 +00001961 if (CGF.getLangOptions().isSignedOverflowDefined())
1962 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1963
1964 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001965}
1966
John McCall913dab22011-06-25 01:32:37 +00001967Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1968 if (op.LHS->getType()->isPointerTy() ||
1969 op.RHS->getType()->isPointerTy())
1970 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1971
1972 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1973 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1974 case LangOptions::SOB_Undefined:
1975 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1976 case LangOptions::SOB_Defined:
1977 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1978 case LangOptions::SOB_Trapping:
1979 return EmitOverflowCheckedBinOp(op);
1980 }
1981 }
1982
1983 if (op.LHS->getType()->isFPOrFPVectorTy())
1984 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
1985
1986 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1987}
1988
1989Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
1990 // The LHS is always a pointer if either side is.
1991 if (!op.LHS->getType()->isPointerTy()) {
1992 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001993 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1994 case LangOptions::SOB_Undefined:
John McCall913dab22011-06-25 01:32:37 +00001995 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001996 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00001997 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001998 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00001999 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002000 }
2001 }
2002
John McCall913dab22011-06-25 01:32:37 +00002003 if (op.LHS->getType()->isFPOrFPVectorTy())
2004 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00002005
John McCall913dab22011-06-25 01:32:37 +00002006 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002007 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002008
John McCall913dab22011-06-25 01:32:37 +00002009 // If the RHS is not a pointer, then we have normal pointer
2010 // arithmetic.
2011 if (!op.RHS->getType()->isPointerTy())
2012 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002013
John McCall913dab22011-06-25 01:32:37 +00002014 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002015
John McCall913dab22011-06-25 01:32:37 +00002016 // Do the raw subtraction part.
2017 llvm::Value *LHS
2018 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2019 llvm::Value *RHS
2020 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2021 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002022
John McCall913dab22011-06-25 01:32:37 +00002023 // Okay, figure out the element size.
2024 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2025 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002026
John McCall913dab22011-06-25 01:32:37 +00002027 llvm::Value *divisor = 0;
2028
2029 // For a variable-length array, this is going to be non-constant.
2030 if (const VariableArrayType *vla
2031 = CGF.getContext().getAsVariableArrayType(elementType)) {
2032 llvm::Value *numElements;
2033 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2034
2035 divisor = numElements;
2036
2037 // Scale the number of non-VLA elements by the non-VLA element size.
2038 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2039 if (!eltSize.isOne())
2040 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2041
2042 // For everything elese, we can just compute it, safe in the
2043 // assumption that Sema won't let anything through that we can't
2044 // safely compute the size of.
2045 } else {
2046 CharUnits elementSize;
2047 // Handle GCC extension for pointer arithmetic on void* and
2048 // function pointer types.
2049 if (elementType->isVoidType() || elementType->isFunctionType())
2050 elementSize = CharUnits::One();
2051 else
2052 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2053
2054 // Don't even emit the divide for element size of 1.
2055 if (elementSize.isOne())
2056 return diffInChars;
2057
2058 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002059 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002060
Chris Lattner2cb42222011-03-01 00:03:48 +00002061 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2062 // pointer difference in C is only defined in the case where both operands
2063 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002064 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002065}
2066
2067Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2068 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2069 // RHS to the same size as the LHS.
2070 Value *RHS = Ops.RHS;
2071 if (Ops.LHS->getType() != RHS->getType())
2072 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002073
Mike Stumpbe07f602009-12-14 21:58:14 +00002074 if (CGF.CatchUndefined
2075 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2076 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2077 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2078 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2079 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002080 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002081 CGF.EmitBlock(Cont);
2082 }
2083
Chris Lattner7f02f722007-08-24 05:35:26 +00002084 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2085}
2086
2087Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2088 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2089 // RHS to the same size as the LHS.
2090 Value *RHS = Ops.RHS;
2091 if (Ops.LHS->getType() != RHS->getType())
2092 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002093
Mike Stumpbe07f602009-12-14 21:58:14 +00002094 if (CGF.CatchUndefined
2095 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2096 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2097 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2098 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2099 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002100 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002101 CGF.EmitBlock(Cont);
2102 }
2103
Douglas Gregorf6094622010-07-23 15:58:24 +00002104 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002105 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2106 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2107}
2108
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002109enum IntrinsicType { VCMPEQ, VCMPGT };
2110// return corresponding comparison intrinsic for given vector type
2111static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2112 BuiltinType::Kind ElemKind) {
2113 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002114 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002115 case BuiltinType::Char_U:
2116 case BuiltinType::UChar:
2117 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2118 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2119 break;
2120 case BuiltinType::Char_S:
2121 case BuiltinType::SChar:
2122 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2123 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2124 break;
2125 case BuiltinType::UShort:
2126 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2127 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2128 break;
2129 case BuiltinType::Short:
2130 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2131 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2132 break;
2133 case BuiltinType::UInt:
2134 case BuiltinType::ULong:
2135 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2136 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2137 break;
2138 case BuiltinType::Int:
2139 case BuiltinType::Long:
2140 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2141 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2142 break;
2143 case BuiltinType::Float:
2144 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2145 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2146 break;
2147 }
2148 return llvm::Intrinsic::not_intrinsic;
2149}
2150
Chris Lattner7f02f722007-08-24 05:35:26 +00002151Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2152 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002153 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002154 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002155 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002156 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002157 assert(E->getOpcode() == BO_EQ ||
2158 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002159 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2160 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002161 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002162 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002163 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002164 Value *LHS = Visit(E->getLHS());
2165 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002166
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002167 // If AltiVec, the comparison results in a numeric type, so we use
2168 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002169 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002170 // constants for mapping CR6 register bits to predicate result
2171 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2172
2173 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2174
2175 // in several cases vector arguments order will be reversed
2176 Value *FirstVecArg = LHS,
2177 *SecondVecArg = RHS;
2178
2179 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002180 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002181 BuiltinType::Kind ElementKind = BTy->getKind();
2182
2183 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002184 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002185 case BO_EQ:
2186 CR6 = CR6_LT;
2187 ID = GetIntrinsic(VCMPEQ, ElementKind);
2188 break;
2189 case BO_NE:
2190 CR6 = CR6_EQ;
2191 ID = GetIntrinsic(VCMPEQ, ElementKind);
2192 break;
2193 case BO_LT:
2194 CR6 = CR6_LT;
2195 ID = GetIntrinsic(VCMPGT, ElementKind);
2196 std::swap(FirstVecArg, SecondVecArg);
2197 break;
2198 case BO_GT:
2199 CR6 = CR6_LT;
2200 ID = GetIntrinsic(VCMPGT, ElementKind);
2201 break;
2202 case BO_LE:
2203 if (ElementKind == BuiltinType::Float) {
2204 CR6 = CR6_LT;
2205 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2206 std::swap(FirstVecArg, SecondVecArg);
2207 }
2208 else {
2209 CR6 = CR6_EQ;
2210 ID = GetIntrinsic(VCMPGT, ElementKind);
2211 }
2212 break;
2213 case BO_GE:
2214 if (ElementKind == BuiltinType::Float) {
2215 CR6 = CR6_LT;
2216 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2217 }
2218 else {
2219 CR6 = CR6_EQ;
2220 ID = GetIntrinsic(VCMPGT, ElementKind);
2221 std::swap(FirstVecArg, SecondVecArg);
2222 }
2223 break;
2224 }
2225
Chris Lattner48431f92011-04-19 22:55:03 +00002226 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002227 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2228 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2229 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2230 }
2231
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002232 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002233 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002234 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002235 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002236 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002237 LHS, RHS, "cmp");
2238 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002239 // Unsigned integers and pointers.
2240 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002241 LHS, RHS, "cmp");
2242 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002243
2244 // If this is a vector comparison, sign extend the result to the appropriate
2245 // vector integer type and return it (don't convert to bool).
2246 if (LHSTy->isVectorType())
2247 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002248
Chris Lattner7f02f722007-08-24 05:35:26 +00002249 } else {
2250 // Complex Comparison: can only be an equality comparison.
2251 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2252 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002253
John McCall183700f2009-09-21 23:43:11 +00002254 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002255
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002256 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002257 if (CETy->isRealFloatingType()) {
2258 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2259 LHS.first, RHS.first, "cmp.r");
2260 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2261 LHS.second, RHS.second, "cmp.i");
2262 } else {
2263 // Complex comparisons can only be equality comparisons. As such, signed
2264 // and unsigned opcodes are the same.
2265 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2266 LHS.first, RHS.first, "cmp.r");
2267 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2268 LHS.second, RHS.second, "cmp.i");
2269 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002270
John McCall2de56d12010-08-25 11:45:40 +00002271 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002272 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2273 } else {
John McCall2de56d12010-08-25 11:45:40 +00002274 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002275 "Complex comparison other than == or != ?");
2276 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2277 }
2278 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002279
2280 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002281}
2282
2283Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002284 bool Ignore = TestAndClearIgnoreResultAssign();
2285
John McCallf85e1932011-06-15 23:02:42 +00002286 Value *RHS;
2287 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002288
John McCallf85e1932011-06-15 23:02:42 +00002289 switch (E->getLHS()->getType().getObjCLifetime()) {
2290 case Qualifiers::OCL_Strong:
2291 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2292 break;
2293
2294 case Qualifiers::OCL_Autoreleasing:
2295 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2296 break;
2297
2298 case Qualifiers::OCL_Weak:
2299 RHS = Visit(E->getRHS());
2300 LHS = EmitCheckedLValue(E->getLHS());
2301 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2302 break;
2303
2304 // No reason to do any of these differently.
2305 case Qualifiers::OCL_None:
2306 case Qualifiers::OCL_ExplicitNone:
2307 // __block variables need to have the rhs evaluated first, plus
2308 // this should improve codegen just a little.
2309 RHS = Visit(E->getRHS());
2310 LHS = EmitCheckedLValue(E->getLHS());
2311
2312 // Store the value into the LHS. Bit-fields are handled specially
2313 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2314 // 'An assignment expression has the value of the left operand after
2315 // the assignment...'.
2316 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002317 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002318 else
John McCall545d9962011-06-25 02:11:03 +00002319 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002320 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002321
2322 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002323 if (Ignore)
2324 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002325
John McCallb418d742010-11-16 10:08:07 +00002326 // The result of an assignment in C is the assigned r-value.
2327 if (!CGF.getContext().getLangOptions().CPlusPlus)
2328 return RHS;
2329
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002330 // If the lvalue is non-volatile, return the computed value of the assignment.
2331 if (!LHS.isVolatileQualified())
2332 return RHS;
2333
2334 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002335 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002336}
2337
2338Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002339 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002340
Chris Lattner20eb09d2008-11-12 08:26:50 +00002341 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2342 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002343 bool LHSCondVal;
2344 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2345 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002346 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002347 // ZExt result to int or bool.
2348 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002349 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002350
Chris Lattner7804bcb2009-10-17 04:24:20 +00002351 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002352 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002353 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002354 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002355
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002356 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2357 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002358
John McCall150b4622011-01-26 04:00:11 +00002359 CodeGenFunction::ConditionalEvaluation eval(CGF);
2360
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002361 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2362 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2363
2364 // Any edges into the ContBlock are now from an (indeterminate number of)
2365 // edges from this first condition. All of these values will be false. Start
2366 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002367 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002368 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002369 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2370 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002371 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002372
John McCall150b4622011-01-26 04:00:11 +00002373 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002374 CGF.EmitBlock(RHSBlock);
2375 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002376 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002377
Chris Lattner7f02f722007-08-24 05:35:26 +00002378 // Reaquire the RHS block, as there may be subblocks inserted.
2379 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002380
2381 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2382 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002383 if (CGF.getDebugInfo())
2384 // There is no need to emit line number for unconditional branch.
2385 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002386 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002387 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002388
Chris Lattner7f02f722007-08-24 05:35:26 +00002389 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002390 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002391}
2392
2393Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002394 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002395
Chris Lattner20eb09d2008-11-12 08:26:50 +00002396 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2397 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002398 bool LHSCondVal;
2399 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2400 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002401 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002402 // ZExt result to int or bool.
2403 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002404 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002405
Chris Lattner7804bcb2009-10-17 04:24:20 +00002406 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002407 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002408 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002409 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002410
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002411 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2412 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002413
John McCall150b4622011-01-26 04:00:11 +00002414 CodeGenFunction::ConditionalEvaluation eval(CGF);
2415
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002416 // Branch on the LHS first. If it is true, go to the success (cont) block.
2417 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2418
2419 // Any edges into the ContBlock are now from an (indeterminate number of)
2420 // edges from this first condition. All of these values will be true. Start
2421 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002422 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002423 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002424 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2425 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002426 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002427
John McCall150b4622011-01-26 04:00:11 +00002428 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002429
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002430 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002431 CGF.EmitBlock(RHSBlock);
2432 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002433
John McCall150b4622011-01-26 04:00:11 +00002434 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002435
Chris Lattner7f02f722007-08-24 05:35:26 +00002436 // Reaquire the RHS block, as there may be subblocks inserted.
2437 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002438
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002439 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2440 // into the phi node for the edge with the value of RHSCond.
2441 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002442 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002443
Chris Lattner7f02f722007-08-24 05:35:26 +00002444 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002445 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002446}
2447
2448Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002449 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002450 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002451 return Visit(E->getRHS());
2452}
2453
2454//===----------------------------------------------------------------------===//
2455// Other Operators
2456//===----------------------------------------------------------------------===//
2457
Chris Lattner9802a512008-11-12 08:55:54 +00002458/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2459/// expression is cheap enough and side-effect-free enough to evaluate
2460/// unconditionally instead of conditionally. This is used to convert control
2461/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002462static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2463 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002464 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002465
Chris Lattnerc6bea672011-04-16 23:15:35 +00002466 // Anything that is an integer or floating point constant is fine.
2467 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002468 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002469
Chris Lattner9802a512008-11-12 08:55:54 +00002470 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2471 // X and Y are local variables.
2472 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002474 if (VD->hasLocalStorage() && !(CGF.getContext()
2475 .getCanonicalType(VD->getType())
2476 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002477 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002478
Chris Lattner9802a512008-11-12 08:55:54 +00002479 return false;
2480}
2481
2482
Chris Lattner7f02f722007-08-24 05:35:26 +00002483Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002484VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002485 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002486
2487 // Bind the common expression if necessary.
2488 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2489
2490 Expr *condExpr = E->getCond();
2491 Expr *lhsExpr = E->getTrueExpr();
2492 Expr *rhsExpr = E->getFalseExpr();
2493
Chris Lattner31a09842008-11-12 08:04:58 +00002494 // If the condition constant folds and can be elided, try to avoid emitting
2495 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002496 bool CondExprBool;
2497 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002498 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002499 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002500
Eli Friedmanc8645e32011-10-15 02:10:40 +00002501 // If the dead side doesn't have labels we need, just emit the Live part.
2502 if (!CGF.ContainsLabel(dead)) {
2503 Value *Result = Visit(live);
2504
2505 // If the live part is a throw expression, it acts like it has a void
2506 // type, so evaluating it returns a null Value*. However, a conditional
2507 // with non-void type must return a non-null Value*.
2508 if (!Result && !E->getType()->isVoidType())
2509 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2510
2511 return Result;
2512 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002513 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002514
Nate Begeman6155d732010-09-20 22:41:17 +00002515 // OpenCL: If the condition is a vector, we can treat this condition like
2516 // the select function.
2517 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002518 && condExpr->getType()->isVectorType()) {
2519 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2520 llvm::Value *LHS = Visit(lhsExpr);
2521 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002522
Chris Lattner2acc6e32011-07-18 04:24:23 +00002523 llvm::Type *condType = ConvertType(condExpr->getType());
2524 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002525
2526 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002527 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002528
2529 std::vector<llvm::Constant*> Zvals;
2530 for (unsigned i = 0; i < numElem; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +00002531 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002532
Nate Begeman6155d732010-09-20 22:41:17 +00002533 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2534 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2535 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2536 llvm::VectorType::get(elemType,
2537 numElem),
2538 "sext");
2539 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2540
2541 // Cast float to int to perform ANDs if necessary.
2542 llvm::Value *RHSTmp = RHS;
2543 llvm::Value *LHSTmp = LHS;
2544 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002545 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002546 if (rhsVTy->getElementType()->isFloatTy()) {
2547 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2548 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2549 wasCast = true;
2550 }
2551
2552 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2553 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2554 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2555 if (wasCast)
2556 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2557
2558 return tmp5;
2559 }
2560
Chris Lattner9802a512008-11-12 08:55:54 +00002561 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2562 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002563 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002564 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2565 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2566 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2567 llvm::Value *LHS = Visit(lhsExpr);
2568 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002569 if (!LHS) {
2570 // If the conditional has void type, make sure we return a null Value*.
2571 assert(!RHS && "LHS and RHS types must match");
2572 return 0;
2573 }
Chris Lattner9802a512008-11-12 08:55:54 +00002574 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2575 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002576
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002577 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2578 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002579 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002580
2581 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002582 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002583
Chris Lattner7f02f722007-08-24 05:35:26 +00002584 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002585 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002586 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002587 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002588
Chris Lattner7f02f722007-08-24 05:35:26 +00002589 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002590 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002591
Chris Lattner7f02f722007-08-24 05:35:26 +00002592 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002593 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002594 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002595 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002596
John McCall150b4622011-01-26 04:00:11 +00002597 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002598 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002599
Eli Friedman48daf592009-12-07 20:25:53 +00002600 // If the LHS or RHS is a throw expression, it will be legitimately null.
2601 if (!LHS)
2602 return RHS;
2603 if (!RHS)
2604 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002605
Chris Lattner7f02f722007-08-24 05:35:26 +00002606 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002607 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002608 PN->addIncoming(LHS, LHSBlock);
2609 PN->addIncoming(RHS, RHSBlock);
2610 return PN;
2611}
2612
2613Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002614 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002615}
2616
Chris Lattner2202bce2007-11-30 17:56:23 +00002617Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002618 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002619 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2620
2621 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002622 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002623 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2624
Mike Stump7f79f9b2009-05-29 15:46:01 +00002625 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002626 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002627}
2628
John McCall6b5a61b2011-02-07 10:33:21 +00002629Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2630 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002631}
2632
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002633Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2634 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002635 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002636
2637 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2638 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002639 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002640 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2641 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2642 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2643 if ((numElementsDst == 3 && numElementsSrc == 4)
2644 || (numElementsDst == 4 && numElementsSrc == 3)) {
2645
2646
2647 // In the case of going from int4->float3, a bitcast is needed before
2648 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002649 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002650 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002651 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002652 cast<llvm::VectorType>(DstTy)->getElementType();
2653
2654 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2655 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2656 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002657 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002658 numElementsSrc);
2659
2660 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2661 }
2662
2663 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2664
Chris Lattner5f9e2722011-07-23 10:55:15 +00002665 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002666 Args.push_back(Builder.getInt32(0));
2667 Args.push_back(Builder.getInt32(1));
2668 Args.push_back(Builder.getInt32(2));
2669
2670 if (numElementsDst == 4)
2671 Args.push_back(llvm::UndefValue::get(
2672 llvm::Type::getInt32Ty(CGF.getLLVMContext())));
2673
2674 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2675
2676 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2677 }
2678 }
2679
2680 return Builder.CreateBitCast(Src, DstTy, "astype");
2681}
2682
Eli Friedman276b0612011-10-11 02:20:01 +00002683Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2684 return CGF.EmitAtomicExpr(E).getScalarVal();
2685}
2686
Chris Lattner7f02f722007-08-24 05:35:26 +00002687//===----------------------------------------------------------------------===//
2688// Entry Point into this File
2689//===----------------------------------------------------------------------===//
2690
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002691/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2692/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002693Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002694 assert(E && !hasAggregateLLVMType(E->getType()) &&
2695 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002696
Devang Patel5de7a0e2011-03-07 18:29:53 +00002697 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002698 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002699 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002700 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002701 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002702 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002703 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002704}
Chris Lattner3707b252007-08-26 06:48:56 +00002705
2706/// EmitScalarConversion - Emit a conversion from the specified type to the
2707/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002708Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2709 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002710 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2711 "Invalid scalar expression to emit");
2712 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2713}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002714
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002715/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2716/// type to the specified destination type, where the destination type is an
2717/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002718Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2719 QualType SrcTy,
2720 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002721 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002722 "Invalid complex -> scalar conversion");
2723 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2724 DstTy);
2725}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002726
Chris Lattner8c11a652010-06-26 22:09:34 +00002727
2728llvm::Value *CodeGenFunction::
2729EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2730 bool isInc, bool isPre) {
2731 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2732}
2733
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002734LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2735 llvm::Value *V;
2736 // object->isa or (*object).isa
2737 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002738 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002739 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002740
2741 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002742 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002743 V = CreateTempAlloca(ClassPtrTy, "resval");
2744 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2745 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002746 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
John McCall545d9962011-06-25 02:11:03 +00002747 MakeAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002748 } else {
2749 if (E->isArrow())
2750 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2751 else
2752 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002753 }
2754
2755 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002756 ClassPtrTy = ClassPtrTy->getPointerTo();
2757 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002758 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002759}
2760
Douglas Gregor6a03e342010-04-23 04:16:32 +00002761
John McCall2a416372010-12-05 02:00:02 +00002762LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002763 const CompoundAssignOperator *E) {
2764 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002765 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002766 switch (E->getOpcode()) {
2767#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002768 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002769 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002770 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002771 COMPOUND_OP(Mul);
2772 COMPOUND_OP(Div);
2773 COMPOUND_OP(Rem);
2774 COMPOUND_OP(Add);
2775 COMPOUND_OP(Sub);
2776 COMPOUND_OP(Shl);
2777 COMPOUND_OP(Shr);
2778 COMPOUND_OP(And);
2779 COMPOUND_OP(Xor);
2780 COMPOUND_OP(Or);
2781#undef COMPOUND_OP
2782
John McCall2de56d12010-08-25 11:45:40 +00002783 case BO_PtrMemD:
2784 case BO_PtrMemI:
2785 case BO_Mul:
2786 case BO_Div:
2787 case BO_Rem:
2788 case BO_Add:
2789 case BO_Sub:
2790 case BO_Shl:
2791 case BO_Shr:
2792 case BO_LT:
2793 case BO_GT:
2794 case BO_LE:
2795 case BO_GE:
2796 case BO_EQ:
2797 case BO_NE:
2798 case BO_And:
2799 case BO_Xor:
2800 case BO_Or:
2801 case BO_LAnd:
2802 case BO_LOr:
2803 case BO_Assign:
2804 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00002805 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00002806 }
2807
2808 llvm_unreachable("Unhandled compound assignment operator");
2809}