blob: 524d79e131da8e8a5b164c13d184f31be278287e [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());
Chris Lattner7f02f722007-08-24 05:35:26 +0000156 assert(0 && "Stmt can't have complex result type!");
157 return 0;
158 }
159 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000160
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000161 Value *VisitParenExpr(ParenExpr *PE) {
162 return Visit(PE->getSubExpr());
163 }
John McCall91a57552011-07-15 05:09:51 +0000164 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
165 return Visit(E->getReplacement());
166 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000167 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
168 return Visit(GE->getResultExpr());
169 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000170
171 // Leaves.
172 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000173 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000174 }
175 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000176 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000177 }
178 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000179 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000180 }
Nate Begemane7579b52007-11-15 05:40:03 +0000181 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000182 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000183 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000184 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000185 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000186 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000187 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000188 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000189 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000190 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000191 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000192 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000193 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
194 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000195 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000196
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000197 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000198 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000199 }
John McCalle996ffd2011-02-16 08:02:54 +0000200
201 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000202 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000203 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000204
205 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000206 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000207 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000208
Chris Lattner7f02f722007-08-24 05:35:26 +0000209 // l-values.
210 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000211 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000212 if (!E->Evaluate(Result, CGF.getContext()))
213 return EmitLoadOfLValue(E);
214
215 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
216
217 llvm::Constant *C;
Chris Lattner48431f92011-04-19 22:55:03 +0000218 if (Result.Val.isInt())
219 C = Builder.getInt(Result.Val.getInt());
220 else if (Result.Val.isFloat())
John McCall189d6ef2010-10-09 01:34:31 +0000221 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
Chris Lattner48431f92011-04-19 22:55:03 +0000222 else
John McCall189d6ef2010-10-09 01:34:31 +0000223 return EmitLoadOfLValue(E);
John McCall189d6ef2010-10-09 01:34:31 +0000224
225 // Make sure we emit a debug reference to the global variable.
226 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
227 if (!CGF.getContext().DeclMustBeEmitted(VD))
228 CGF.EmitDeclRefExprDbgValue(E, C);
229 } else if (isa<EnumConstantDecl>(E->getDecl())) {
230 CGF.EmitDeclRefExprDbgValue(E, C);
231 }
232
233 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000234 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000235 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
236 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000237 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000238 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
239 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000240 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000241 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000242 return EmitLoadOfLValue(E);
243 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000244 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000245 assert(E->getObjectKind() == OK_Ordinary &&
246 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000247 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000248 }
249 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000250 if (E->getMethodDecl() &&
251 E->getMethodDecl()->getResultType()->isReferenceType())
252 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000253 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000254 }
255
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000256 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000257 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000258 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000259 return V;
260 }
261
Chris Lattner7f02f722007-08-24 05:35:26 +0000262 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000263 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000264 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000265 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000266 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
267 return EmitLoadOfLValue(E);
268 }
Devang Patel35634f52007-10-24 17:18:43 +0000269
Nate Begeman0533b302009-10-18 20:10:40 +0000270 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000271
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000272 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000273 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000274 }
John McCallbc8d40d2011-06-24 21:55:10 +0000275 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000276 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000277 CGF.EmitVariablyModifiedType(E->getType());
278 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000279 }
John McCallbc8d40d2011-06-24 21:55:10 +0000280 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000281
282 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000283 if (E->getCallReturnType()->isReferenceType())
284 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000285
Chris Lattner9b655512007-08-31 22:49:20 +0000286 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000288
Chris Lattner33793202007-08-31 22:09:40 +0000289 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000290
Mike Stumpa99038c2009-02-28 09:07:16 +0000291 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000292
Chris Lattner7f02f722007-08-24 05:35:26 +0000293 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000295 LValue LV = EmitLValue(E->getSubExpr());
296 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000297 }
298 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000299 LValue LV = EmitLValue(E->getSubExpr());
300 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000301 }
302 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000303 LValue LV = EmitLValue(E->getSubExpr());
304 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000305 }
306 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000307 LValue LV = EmitLValue(E->getSubExpr());
308 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000309 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000310
Anton Yartsev683564a2011-02-07 02:17:30 +0000311 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
312 llvm::Value *InVal,
313 llvm::Value *NextVal,
314 bool IsInc);
315
Chris Lattner8c11a652010-06-26 22:09:34 +0000316 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
317 bool isInc, bool isPre);
318
319
Chris Lattner7f02f722007-08-24 05:35:26 +0000320 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000321 if (isa<MemberPointerType>(E->getType())) // never sugared
322 return CGF.CGM.getMemberPointerConstant(E);
323
Chris Lattner7f02f722007-08-24 05:35:26 +0000324 return EmitLValue(E->getSubExpr()).getAddress();
325 }
John McCallfd569002010-12-04 12:43:24 +0000326 Value *VisitUnaryDeref(const UnaryOperator *E) {
327 if (E->getType()->isVoidType())
328 return Visit(E->getSubExpr()); // the actual value should be unused
329 return EmitLoadOfLValue(E);
330 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000331 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000332 // This differs from gcc, though, most likely due to a bug in gcc.
333 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000334 return Visit(E->getSubExpr());
335 }
336 Value *VisitUnaryMinus (const UnaryOperator *E);
337 Value *VisitUnaryNot (const UnaryOperator *E);
338 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000339 Value *VisitUnaryReal (const UnaryOperator *E);
340 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000341 Value *VisitUnaryExtension(const UnaryOperator *E) {
342 return Visit(E->getSubExpr());
343 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000344
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000345 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000346 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
347 return Visit(DAE->getExpr());
348 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000349 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
350 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000351 }
352
John McCall4765fa02010-12-06 08:20:24 +0000353 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
354 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000355 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000356 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
357 return CGF.EmitCXXNewExpr(E);
358 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000359 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
360 CGF.EmitCXXDeleteExpr(E);
361 return 0;
362 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000363 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000364 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000365 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000366
Francois Pichet6ad6f282010-12-07 00:08:36 +0000367 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000368 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000369 }
370
John Wiegley21ff2e52011-04-28 00:16:57 +0000371 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
372 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
373 }
374
John Wiegley55262202011-04-25 06:54:41 +0000375 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
377 }
378
Douglas Gregora71d8192009-09-04 17:36:40 +0000379 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
380 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000381 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000382 // operator (), and the result of such a call has type void. The only
383 // effect is the evaluation of the postfix-expression before the dot or
384 // arrow.
385 CGF.EmitScalarExpr(E->getBase());
386 return 0;
387 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000388
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000389 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000390 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000391 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000392
393 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
394 CGF.EmitCXXThrowExpr(E);
395 return 0;
396 }
397
Sebastian Redl98294de2010-09-10 21:04:00 +0000398 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000399 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000400 }
401
Chris Lattner7f02f722007-08-24 05:35:26 +0000402 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000403 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000404 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000405 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
406 case LangOptions::SOB_Undefined:
407 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
408 case LangOptions::SOB_Defined:
409 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
410 case LangOptions::SOB_Trapping:
411 return EmitOverflowCheckedBinOp(Ops);
412 }
413 }
414
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000415 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000416 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000417 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
418 }
Chris Lattner80230302010-09-11 21:47:09 +0000419 bool isTrapvOverflowBehavior() {
420 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
421 == LangOptions::SOB_Trapping;
422 }
Mike Stump2add4732009-04-01 20:28:16 +0000423 /// Create a binary op that checks for overflow.
424 /// Currently only supports +, - and *.
425 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000426 // Emit the overflow BB when -ftrapv option is activated.
427 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
428 Builder.SetInsertPoint(overflowBB);
429 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
430 Builder.CreateCall(Trap);
431 Builder.CreateUnreachable();
432 }
433 // Check for undefined division and modulus behaviors.
434 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
435 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000436 Value *EmitDiv(const BinOpInfo &Ops);
437 Value *EmitRem(const BinOpInfo &Ops);
438 Value *EmitAdd(const BinOpInfo &Ops);
439 Value *EmitSub(const BinOpInfo &Ops);
440 Value *EmitShl(const BinOpInfo &Ops);
441 Value *EmitShr(const BinOpInfo &Ops);
442 Value *EmitAnd(const BinOpInfo &Ops) {
443 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
444 }
445 Value *EmitXor(const BinOpInfo &Ops) {
446 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
447 }
448 Value *EmitOr (const BinOpInfo &Ops) {
449 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
450 }
451
Chris Lattner1f1ded92007-08-24 21:00:35 +0000452 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000453 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
454 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000455 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000456
Chris Lattner3ccf7742007-08-26 21:41:21 +0000457 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000458 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
459
460 // Binary operators and binary compound assignment operators.
461#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000462 Value *VisitBin ## OP(const BinaryOperator *E) { \
463 return Emit ## OP(EmitBinOps(E)); \
464 } \
465 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
466 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000467 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000468 HANDLEBINOP(Mul)
469 HANDLEBINOP(Div)
470 HANDLEBINOP(Rem)
471 HANDLEBINOP(Add)
472 HANDLEBINOP(Sub)
473 HANDLEBINOP(Shl)
474 HANDLEBINOP(Shr)
475 HANDLEBINOP(And)
476 HANDLEBINOP(Xor)
477 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000478#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000479
Chris Lattner7f02f722007-08-24 05:35:26 +0000480 // Comparisons.
481 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
482 unsigned SICmpOpc, unsigned FCmpOpc);
483#define VISITCOMP(CODE, UI, SI, FP) \
484 Value *VisitBin##CODE(const BinaryOperator *E) { \
485 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
486 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000487 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
488 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
489 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
490 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
491 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
492 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000493#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000494
Chris Lattner7f02f722007-08-24 05:35:26 +0000495 Value *VisitBinAssign (const BinaryOperator *E);
496
497 Value *VisitBinLAnd (const BinaryOperator *E);
498 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000499 Value *VisitBinComma (const BinaryOperator *E);
500
Eli Friedman25b825d2009-11-18 09:41:26 +0000501 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
502 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
503
Chris Lattner7f02f722007-08-24 05:35:26 +0000504 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000505 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000506 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000507 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000508 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000509 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
510 return CGF.EmitObjCStringLiteral(E);
511 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000512 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000513};
514} // end anonymous namespace.
515
516//===----------------------------------------------------------------------===//
517// Utilities
518//===----------------------------------------------------------------------===//
519
Chris Lattner9abc84e2007-08-26 16:42:57 +0000520/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000521/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000522Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000523 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000524
John McCalldaa8e4e2010-11-15 09:13:47 +0000525 if (SrcType->isRealFloatingType())
526 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527
John McCall0bab0cd2010-08-23 01:21:21 +0000528 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
529 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000530
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000531 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000532 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000533
John McCalldaa8e4e2010-11-15 09:13:47 +0000534 if (isa<llvm::IntegerType>(Src->getType()))
535 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000536
John McCalldaa8e4e2010-11-15 09:13:47 +0000537 assert(isa<llvm::PointerType>(Src->getType()));
538 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000539}
540
Chris Lattner3707b252007-08-26 06:48:56 +0000541/// EmitScalarConversion - Emit a conversion from the specified type to the
542/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000543Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
544 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000545 SrcType = CGF.getContext().getCanonicalType(SrcType);
546 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000547 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000548
Chris Lattnercf289082007-08-26 07:21:11 +0000549 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000550
Chris Lattner3707b252007-08-26 06:48:56 +0000551 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000552 if (DstType->isBooleanType())
553 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000554
Chris Lattner2acc6e32011-07-18 04:24:23 +0000555 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000556
557 // Ignore conversions like int -> uint.
558 if (Src->getType() == DstTy)
559 return Src;
560
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000561 // Handle pointer conversions next: pointers can only be converted to/from
562 // other pointers and integers. Check for pointer types in terms of LLVM, as
563 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000564 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000565 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000566 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000567 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000568
Chris Lattner3707b252007-08-26 06:48:56 +0000569 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000570 // First, convert to the correct width so that we control the kind of
571 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000572 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000573 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000574 llvm::Value* IntResult =
575 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
576 // Then, cast to pointer.
577 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000578 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000579
Daniel Dunbar270cc662008-08-25 09:51:32 +0000580 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000581 // Must be an ptr to int cast.
582 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000583 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000584 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000585
Nate Begeman213541a2008-04-18 23:10:10 +0000586 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000587 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000588 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000589 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000590 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
591
592 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000593 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000594 llvm::Value *Idx = Builder.getInt32(0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000595 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
596
597 // Splat the element across to all elements
Chris Lattner5f9e2722011-07-23 10:55:15 +0000598 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000599 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000600 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +0000601 Args.push_back(Builder.getInt32(0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000602
Chris Lattnerfb018d12011-02-15 00:14:06 +0000603 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000604 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
605 return Yay;
606 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000607
Chris Lattner3b1ae002008-02-02 04:51:41 +0000608 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000609 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000610 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000611 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000612
Chris Lattner3707b252007-08-26 06:48:56 +0000613 // Finally, we have the arithmetic types: real int/float.
614 if (isa<llvm::IntegerType>(Src->getType())) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000615 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000616 if (isa<llvm::IntegerType>(DstTy))
617 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
618 else if (InputSigned)
619 return Builder.CreateSIToFP(Src, DstTy, "conv");
620 else
621 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000622 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000623
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000624 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000625 if (isa<llvm::IntegerType>(DstTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000626 if (DstType->isSignedIntegerOrEnumerationType())
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000627 return Builder.CreateFPToSI(Src, DstTy, "conv");
628 else
629 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000630 }
631
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000632 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000633 if (DstTy->getTypeID() < Src->getType()->getTypeID())
634 return Builder.CreateFPTrunc(Src, DstTy, "conv");
635 else
636 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000637}
638
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000639/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
640/// type to the specified destination type, where the destination type is an
641/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000642Value *ScalarExprEmitter::
643EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
644 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000645 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000646 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000647
Chris Lattnered70f0a2007-08-26 16:52:28 +0000648 // Handle conversions to bool first, they are special: comparisons against 0.
649 if (DstTy->isBooleanType()) {
650 // Complex != 0 -> (Real != 0) | (Imag != 0)
651 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
652 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
653 return Builder.CreateOr(Src.first, Src.second, "tobool");
654 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000655
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000656 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
657 // the imaginary part of the complex value is discarded and the value of the
658 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000659 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000660 return EmitScalarConversion(Src.first, SrcTy, DstTy);
661}
662
Anders Carlssona40a9f32010-05-22 17:45:10 +0000663Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000664 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
665 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
666
667 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000668}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000669
Chris Lattner7f02f722007-08-24 05:35:26 +0000670//===----------------------------------------------------------------------===//
671// Visitor Methods
672//===----------------------------------------------------------------------===//
673
674Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000675 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000676 if (E->getType()->isVoidType())
677 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000678 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000679}
680
Eli Friedmand38617c2008-05-14 19:38:39 +0000681Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000682 // Vector Mask Case
683 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000684 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000685 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
686 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
687 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000688
Chris Lattner2acc6e32011-07-18 04:24:23 +0000689 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000690 unsigned LHSElts = LTy->getNumElements();
691
692 if (E->getNumSubExprs() == 3) {
693 Mask = CGF.EmitScalarExpr(E->getExpr(2));
694
695 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000696 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000697 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000698 concat.push_back(Builder.getInt32(2*i));
699 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000700 }
701
Chris Lattnerfb018d12011-02-15 00:14:06 +0000702 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000703 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
704 LHSElts *= 2;
705 } else {
706 Mask = RHS;
707 }
708
Chris Lattner2acc6e32011-07-18 04:24:23 +0000709 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000710 llvm::Constant* EltMask;
711
712 // Treat vec3 like vec4.
713 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
714 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
715 (1 << llvm::Log2_32(LHSElts+2))-1);
716 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
717 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
718 (1 << llvm::Log2_32(LHSElts+1))-1);
719 else
720 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
721 (1 << llvm::Log2_32(LHSElts))-1);
722
723 // Mask off the high bits of each shuffle index.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000724 SmallVector<llvm::Constant *, 32> MaskV;
Nate Begeman37b6a572010-06-08 00:16:34 +0000725 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
726 MaskV.push_back(EltMask);
727
Chris Lattnerfb018d12011-02-15 00:14:06 +0000728 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000729 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
730
731 // newv = undef
732 // mask = mask & maskbits
733 // for each elt
734 // n = extract mask i
735 // x = extract val n
736 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000737 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000738 MTy->getNumElements());
739 Value* NewV = llvm::UndefValue::get(RTy);
740 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000741 Value *Indx = Builder.getInt32(i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000742 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000743 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000744
745 // Handle vec3 special since the index will be off by one for the RHS.
746 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
747 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000748 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000749 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000750 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000751 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
752 }
753 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
754 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
755 }
756 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000757 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000758
Eli Friedmand38617c2008-05-14 19:38:39 +0000759 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
760 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000761
762 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000763 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000764 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000765 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000766 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
767 if (VTy->getNumElements() == 3 && Idx > 3)
768 Idx -= 1;
769 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000770 }
771
Chris Lattnerfb018d12011-02-15 00:14:06 +0000772 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000773 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
774}
Eli Friedman28665272009-11-26 03:22:21 +0000775Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
776 Expr::EvalResult Result;
777 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
778 if (E->isArrow())
779 CGF.EmitScalarExpr(E->getBase());
780 else
781 EmitLValue(E->getBase());
Chris Lattner48431f92011-04-19 22:55:03 +0000782 return Builder.getInt(Result.Val.getInt());
Eli Friedman28665272009-11-26 03:22:21 +0000783 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000784
785 // Emit debug info for aggregate now, if it was delayed to reduce
786 // debug info size.
787 CGDebugInfo *DI = CGF.getDebugInfo();
788 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
789 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
790 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000791 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000792 DI->getOrCreateRecordType(PTy->getPointeeType(),
793 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000794 }
Eli Friedman28665272009-11-26 03:22:21 +0000795 return EmitLoadOfLValue(E);
796}
Eli Friedmand38617c2008-05-14 19:38:39 +0000797
Chris Lattner7f02f722007-08-24 05:35:26 +0000798Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000799 TestAndClearIgnoreResultAssign();
800
Chris Lattner7f02f722007-08-24 05:35:26 +0000801 // Emit subscript expressions in rvalue context's. For most cases, this just
802 // loads the lvalue formed by the subscript expr. However, we have to be
803 // careful, because the base of a vector subscript is occasionally an rvalue,
804 // so we can't get it as an lvalue.
805 if (!E->getBase()->getType()->isVectorType())
806 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000807
Chris Lattner7f02f722007-08-24 05:35:26 +0000808 // Handle the vector case. The base must be a vector, the index must be an
809 // integer value.
810 Value *Base = Visit(E->getBase());
811 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000812 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000813 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000814 return Builder.CreateExtractElement(Base, Idx, "vecext");
815}
816
Nate Begeman0533b302009-10-18 20:10:40 +0000817static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000818 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000819 int MV = SVI->getMaskValue(Idx);
820 if (MV == -1)
821 return llvm::UndefValue::get(I32Ty);
822 return llvm::ConstantInt::get(I32Ty, Off+MV);
823}
824
825Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
826 bool Ignore = TestAndClearIgnoreResultAssign();
827 (void)Ignore;
828 assert (Ignore == false && "init list ignored");
829 unsigned NumInitElements = E->getNumInits();
830
831 if (E->hadArrayRangeDesignator())
832 CGF.ErrorUnsupported(E, "GNU array range designator extension");
833
Chris Lattner2acc6e32011-07-18 04:24:23 +0000834 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000835 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
836
837 // We have a scalar in braces. Just use the first element.
838 if (!VType)
839 return Visit(E->getInit(0));
840
841 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000842
843 // Loop over initializers collecting the Value for each, and remembering
844 // whether the source was swizzle (ExtVectorElementExpr). This will allow
845 // us to fold the shuffle for the swizzle into the shuffle for the vector
846 // initializer, since LLVM optimizers generally do not want to touch
847 // shuffles.
848 unsigned CurIdx = 0;
849 bool VIsUndefShuffle = false;
850 llvm::Value *V = llvm::UndefValue::get(VType);
851 for (unsigned i = 0; i != NumInitElements; ++i) {
852 Expr *IE = E->getInit(i);
853 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000854 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000855
Chris Lattner2acc6e32011-07-18 04:24:23 +0000856 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000857
858 // Handle scalar elements. If the scalar initializer is actually one
859 // element of a different vector of the same width, use shuffle instead of
860 // extract+insert.
861 if (!VVT) {
862 if (isa<ExtVectorElementExpr>(IE)) {
863 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
864
865 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
866 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
867 Value *LHS = 0, *RHS = 0;
868 if (CurIdx == 0) {
869 // insert into undef -> shuffle (src, undef)
870 Args.push_back(C);
871 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000872 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000873
874 LHS = EI->getVectorOperand();
875 RHS = V;
876 VIsUndefShuffle = true;
877 } else if (VIsUndefShuffle) {
878 // insert into undefshuffle && size match -> shuffle (v, src)
879 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
880 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000881 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000882 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Nate Begeman0533b302009-10-18 20:10:40 +0000883 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000884 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000885
886 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
887 RHS = EI->getVectorOperand();
888 VIsUndefShuffle = false;
889 }
890 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000891 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000892 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
893 ++CurIdx;
894 continue;
895 }
896 }
897 }
Chris Lattner48431f92011-04-19 22:55:03 +0000898 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
899 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000900 VIsUndefShuffle = false;
901 ++CurIdx;
902 continue;
903 }
904
905 unsigned InitElts = VVT->getNumElements();
906
907 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
908 // input is the same width as the vector being constructed, generate an
909 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000910 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000911 if (isa<ExtVectorElementExpr>(IE)) {
912 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
913 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000914 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000915
916 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000917 for (unsigned j = 0; j != CurIdx; ++j) {
918 // If the current vector initializer is a shuffle with undef, merge
919 // this shuffle directly into it.
920 if (VIsUndefShuffle) {
921 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000922 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000923 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000924 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000925 }
926 }
927 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000928 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000929 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000930 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000931
932 if (VIsUndefShuffle)
933 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
934
935 Init = SVOp;
936 }
937 }
938
939 // Extend init to result vector length, and then shuffle its contribution
940 // to the vector initializer into V.
941 if (Args.empty()) {
942 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000943 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000944 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000945 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000946 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000947 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000948 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000949
950 Args.clear();
951 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000952 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000953 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000954 Args.push_back(Builder.getInt32(j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000955 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000956 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000957 }
958
959 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
960 // merging subsequent shuffles into this one.
961 if (CurIdx == 0)
962 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000963 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000964 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
965 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
966 CurIdx += InitElts;
967 }
968
969 // FIXME: evaluate codegen vs. shuffling against constant null vector.
970 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000971 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +0000972
973 // Emit remaining default initializers
974 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000975 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000976 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
977 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
978 }
979 return V;
980}
981
Anders Carlssona3697c92009-11-23 17:57:54 +0000982static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
983 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000984
John McCall2de56d12010-08-25 11:45:40 +0000985 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000986 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000987
988 if (isa<CXXThisExpr>(E)) {
989 // We always assume that 'this' is never null.
990 return false;
991 }
992
993 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000994 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000995 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000996 return false;
997 }
998
999 return true;
1000}
1001
Chris Lattner7f02f722007-08-24 05:35:26 +00001002// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1003// have to handle a more broad range of conversions than explicit casts, as they
1004// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001005Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001006 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001007 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001008 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001009
Mike Stump7f79f9b2009-05-29 15:46:01 +00001010 if (!DestTy->isVoidType())
1011 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001012
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001013 // Since almost all cast kinds apply to scalars, this switch doesn't have
1014 // a default case, so the compiler will warn on a missing case. The cases
1015 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001016 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001017 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1018
John McCall2de56d12010-08-25 11:45:40 +00001019 case CK_LValueBitCast:
1020 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001021 Value *V = EmitLValue(E).getAddress();
1022 V = Builder.CreateBitCast(V,
1023 ConvertType(CGF.getContext().getPointerType(DestTy)));
John McCall545d9962011-06-25 02:11:03 +00001024 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001025 }
1026
John McCall2de56d12010-08-25 11:45:40 +00001027 case CK_AnyPointerToObjCPointerCast:
1028 case CK_AnyPointerToBlockPointerCast:
1029 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001030 Value *Src = Visit(const_cast<Expr*>(E));
1031 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1032 }
John McCall2de56d12010-08-25 11:45:40 +00001033 case CK_NoOp:
1034 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001035 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001036
John McCall2de56d12010-08-25 11:45:40 +00001037 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001038 const CXXRecordDecl *DerivedClassDecl =
1039 DestTy->getCXXRecordDeclForPointerType();
1040
Anders Carlssona04efdf2010-04-24 21:23:59 +00001041 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001042 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001043 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001044 }
John McCall2de56d12010-08-25 11:45:40 +00001045 case CK_UncheckedDerivedToBase:
1046 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001047 const RecordType *DerivedClassTy =
1048 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1049 CXXRecordDecl *DerivedClassDecl =
1050 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1051
Anders Carlsson34a2d382010-04-24 21:06:20 +00001052 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001053 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001054 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001055 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001056 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001057 Value *V = Visit(const_cast<Expr*>(E));
1058 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1059 return CGF.EmitDynamicCast(V, DCE);
1060 }
Eli Friedmand8889622009-11-27 04:41:50 +00001061
John McCall2de56d12010-08-25 11:45:40 +00001062 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001063 assert(E->getType()->isArrayType() &&
1064 "Array to pointer decay must have array source type!");
1065
1066 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1067
1068 // Note that VLA pointers are always decayed, so we don't need to do
1069 // anything here.
1070 if (!E->getType()->isVariableArrayType()) {
1071 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1072 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1073 ->getElementType()) &&
1074 "Expected pointer to array");
1075 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1076 }
1077
Chris Lattner410b12e2011-07-20 04:31:01 +00001078 // Make sure the array decay ends up being the right type. This matters if
1079 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001080 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001081 }
John McCall2de56d12010-08-25 11:45:40 +00001082 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001083 return EmitLValue(E).getAddress();
1084
John McCall404cd162010-11-13 01:35:44 +00001085 case CK_NullToPointer:
1086 if (MustVisitNullValue(E))
1087 (void) Visit(E);
1088
1089 return llvm::ConstantPointerNull::get(
1090 cast<llvm::PointerType>(ConvertType(DestTy)));
1091
John McCall2de56d12010-08-25 11:45:40 +00001092 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001093 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001094 (void) Visit(E);
1095
John McCall0bab0cd2010-08-23 01:21:21 +00001096 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1097 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1098 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001099
John McCall2de56d12010-08-25 11:45:40 +00001100 case CK_BaseToDerivedMemberPointer:
1101 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001102 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001103
1104 // Note that the AST doesn't distinguish between checked and
1105 // unchecked member pointer conversions, so we always have to
1106 // implement checked conversions here. This is inefficient when
1107 // actual control flow may be required in order to perform the
1108 // check, which it is for data member pointers (but not member
1109 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001110 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001111 }
John McCallf85e1932011-06-15 23:02:42 +00001112
1113 case CK_ObjCProduceObject:
1114 return CGF.EmitARCRetainScalarExpr(E);
1115 case CK_ObjCConsumeObject:
1116 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall7e5e5f42011-07-07 06:58:02 +00001117 case CK_ObjCReclaimReturnedObject: {
1118 llvm::Value *value = Visit(E);
1119 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1120 return CGF.EmitObjCConsumeObject(E->getType(), value);
1121 }
John McCallf85e1932011-06-15 23:02:42 +00001122
John McCall2bb5d002010-11-13 09:02:35 +00001123 case CK_FloatingRealToComplex:
1124 case CK_FloatingComplexCast:
1125 case CK_IntegralRealToComplex:
1126 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001127 case CK_IntegralComplexToFloatingComplex:
1128 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001129 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001130 case CK_ToUnion:
1131 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001132 break;
John McCallf6a16482010-12-04 03:47:34 +00001133
1134 case CK_GetObjCProperty: {
1135 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001136 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001137 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
John McCall545d9962011-06-25 02:11:03 +00001138 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E));
John McCallf6a16482010-12-04 03:47:34 +00001139 return RV.getScalarVal();
1140 }
John McCall1de4d4e2011-04-07 08:22:57 +00001141
John McCall0ae287a2010-12-01 04:43:34 +00001142 case CK_LValueToRValue:
1143 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001144 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001145 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001146
John McCall2de56d12010-08-25 11:45:40 +00001147 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001148 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001149
Anders Carlsson82debc72009-10-18 18:12:03 +00001150 // First, convert to the correct width so that we control the kind of
1151 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001152 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001153 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001154 llvm::Value* IntResult =
1155 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001156
Anders Carlsson82debc72009-10-18 18:12:03 +00001157 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001158 }
Eli Friedman65949422011-06-25 02:58:47 +00001159 case CK_PointerToIntegral:
1160 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1161 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001162
John McCall2de56d12010-08-25 11:45:40 +00001163 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001164 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001165 return 0;
1166 }
John McCall2de56d12010-08-25 11:45:40 +00001167 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001168 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001169 Value *Elt = Visit(const_cast<Expr*>(E));
1170
1171 // Insert the element in element zero of an undef vector
1172 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001173 llvm::Value *Idx = Builder.getInt32(0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001174 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1175
1176 // Splat the element across to all elements
Chris Lattner5f9e2722011-07-23 10:55:15 +00001177 SmallVector<llvm::Constant*, 16> Args;
Eli Friedmanad35a832009-11-16 21:33:53 +00001178 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001179 llvm::Constant *Zero = Builder.getInt32(0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001180 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001181 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001182
Chris Lattnerfb018d12011-02-15 00:14:06 +00001183 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001184 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1185 return Yay;
1186 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001187
John McCall2de56d12010-08-25 11:45:40 +00001188 case CK_IntegralCast:
1189 case CK_IntegralToFloating:
1190 case CK_FloatingToIntegral:
1191 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001192 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001193
John McCalldaa8e4e2010-11-15 09:13:47 +00001194 case CK_IntegralToBoolean:
1195 return EmitIntToBoolConversion(Visit(E));
1196 case CK_PointerToBoolean:
1197 return EmitPointerToBoolConversion(Visit(E));
1198 case CK_FloatingToBoolean:
1199 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001200 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001201 llvm::Value *MemPtr = Visit(E);
1202 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1203 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001204 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001205
1206 case CK_FloatingComplexToReal:
1207 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001208 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001209
1210 case CK_FloatingComplexToBoolean:
1211 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001212 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001213
1214 // TODO: kill this function off, inline appropriate case here
1215 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1216 }
1217
John McCall0bab0cd2010-08-23 01:21:21 +00001218 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001219
John McCall61ad0e62010-11-16 06:21:14 +00001220 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001221 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001222}
1223
Chris Lattner33793202007-08-31 22:09:40 +00001224Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001225 CodeGenFunction::StmtExprEvaluation eval(CGF);
1226 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1227 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001228}
1229
Mike Stumpa99038c2009-02-28 09:07:16 +00001230Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
John McCalla5bcb8f2011-03-16 02:53:38 +00001231 LValue LV = CGF.EmitBlockDeclRefLValue(E);
John McCall545d9962011-06-25 02:11:03 +00001232 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Mike Stump4e7a1f72009-02-21 20:00:35 +00001233}
Chris Lattner33793202007-08-31 22:09:40 +00001234
Chris Lattner7f02f722007-08-24 05:35:26 +00001235//===----------------------------------------------------------------------===//
1236// Unary Operators
1237//===----------------------------------------------------------------------===//
1238
Chris Lattner8c11a652010-06-26 22:09:34 +00001239llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001240EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1241 llvm::Value *InVal,
1242 llvm::Value *NextVal, bool IsInc) {
1243 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1244 case LangOptions::SOB_Undefined:
1245 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1246 break;
1247 case LangOptions::SOB_Defined:
1248 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1249 break;
1250 case LangOptions::SOB_Trapping:
1251 BinOpInfo BinOp;
1252 BinOp.LHS = InVal;
1253 BinOp.RHS = NextVal;
1254 BinOp.Ty = E->getType();
1255 BinOp.Opcode = BO_Add;
1256 BinOp.E = E;
1257 return EmitOverflowCheckedBinOp(BinOp);
1258 break;
1259 }
1260 assert(false && "Unknown SignedOverflowBehaviorTy");
1261 return 0;
1262}
1263
John McCall5936e332011-02-15 09:22:45 +00001264llvm::Value *
1265ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1266 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001267
John McCall5936e332011-02-15 09:22:45 +00001268 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001269 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001270 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001271
John McCall5936e332011-02-15 09:22:45 +00001272 int amount = (isInc ? 1 : -1);
1273
1274 // Special case of integer increment that we have to check first: bool++.
1275 // Due to promotion rules, we get:
1276 // bool++ -> bool = bool + 1
1277 // -> bool = (int)bool + 1
1278 // -> bool = ((int)bool + 1 != 0)
1279 // An interesting aspect of this is that increment is always true.
1280 // Decrement does not have this property.
1281 if (isInc && type->isBooleanType()) {
1282 value = Builder.getTrue();
1283
1284 // Most common case by far: integer increment.
1285 } else if (type->isIntegerType()) {
1286
1287 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1288
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001289 // Note that signed integer inc/dec with width less than int can't
1290 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001291 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001292 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001293 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001294 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001295 else
1296 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1297
1298 // Next most common: pointer increment.
1299 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1300 QualType type = ptr->getPointeeType();
1301
1302 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001303 if (const VariableArrayType *vla
1304 = CGF.getContext().getAsVariableArrayType(type)) {
1305 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001306 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Chris Lattner2cb42222011-03-01 00:03:48 +00001307 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001308 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001309 else
John McCallbc8d40d2011-06-24 21:55:10 +00001310 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001311
1312 // Arithmetic on function pointers (!) is just +-1.
1313 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001314 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001315
1316 value = CGF.EmitCastToVoidPtr(value);
Chris Lattner2cb42222011-03-01 00:03:48 +00001317 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1318 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1319 else
1320 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001321 value = Builder.CreateBitCast(value, input->getType());
1322
1323 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001324 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001325 llvm::Value *amt = Builder.getInt32(amount);
Chris Lattner2cb42222011-03-01 00:03:48 +00001326 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1327 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1328 else
1329 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001330 }
1331
1332 // Vector increment/decrement.
1333 } else if (type->isVectorType()) {
1334 if (type->hasIntegerRepresentation()) {
1335 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1336
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001337 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001338 } else {
1339 value = Builder.CreateFAdd(
1340 value,
1341 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001342 isInc ? "inc" : "dec");
1343 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001344
John McCall5936e332011-02-15 09:22:45 +00001345 // Floating point.
1346 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001347 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001348 llvm::Value *amt;
1349 if (value->getType()->isFloatTy())
1350 amt = llvm::ConstantFP::get(VMContext,
1351 llvm::APFloat(static_cast<float>(amount)));
1352 else if (value->getType()->isDoubleTy())
1353 amt = llvm::ConstantFP::get(VMContext,
1354 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001355 else {
John McCall5936e332011-02-15 09:22:45 +00001356 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001357 bool ignored;
1358 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1359 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001360 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001361 }
John McCall5936e332011-02-15 09:22:45 +00001362 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1363
1364 // Objective-C pointer types.
1365 } else {
1366 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1367 value = CGF.EmitCastToVoidPtr(value);
1368
1369 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1370 if (!isInc) size = -size;
1371 llvm::Value *sizeValue =
1372 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1373
Chris Lattner2cb42222011-03-01 00:03:48 +00001374 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1375 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1376 else
1377 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001378 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001379 }
1380
1381 // Store the updated result through the lvalue.
1382 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001383 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001384 else
John McCall545d9962011-06-25 02:11:03 +00001385 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Chris Lattner8c11a652010-06-26 22:09:34 +00001386
1387 // If this is a postinc, return the value read from memory, otherwise use the
1388 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001389 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001390}
1391
1392
1393
Chris Lattner7f02f722007-08-24 05:35:26 +00001394Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001395 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001396 // Emit unary minus with EmitSub so we handle overflow cases etc.
1397 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001398 BinOp.RHS = Visit(E->getSubExpr());
1399
1400 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1401 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1402 else
1403 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001404 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001405 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001406 BinOp.E = E;
1407 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001408}
1409
1410Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001411 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001412 Value *Op = Visit(E->getSubExpr());
1413 return Builder.CreateNot(Op, "neg");
1414}
1415
1416Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1417 // Compare operand to zero.
1418 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001419
Chris Lattner7f02f722007-08-24 05:35:26 +00001420 // Invert value.
1421 // TODO: Could dynamically modify easy computations here. For example, if
1422 // the operand is an icmp ne, turn into icmp eq.
1423 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001424
Anders Carlsson9f84d882009-05-19 18:44:53 +00001425 // ZExt result to the expr type.
1426 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001427}
1428
Eli Friedman0027d2b2010-08-05 09:58:49 +00001429Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1430 // Try folding the offsetof to a constant.
1431 Expr::EvalResult EvalResult;
1432 if (E->Evaluate(EvalResult, CGF.getContext()))
Chris Lattner48431f92011-04-19 22:55:03 +00001433 return Builder.getInt(EvalResult.Val.getInt());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001434
1435 // Loop over the components of the offsetof to compute the value.
1436 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001437 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001438 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1439 QualType CurrentType = E->getTypeSourceInfo()->getType();
1440 for (unsigned i = 0; i != n; ++i) {
1441 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001442 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001443 switch (ON.getKind()) {
1444 case OffsetOfExpr::OffsetOfNode::Array: {
1445 // Compute the index
1446 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1447 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001448 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001449 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1450
1451 // Save the element type
1452 CurrentType =
1453 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1454
1455 // Compute the element size
1456 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1457 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1458
1459 // Multiply out to compute the result
1460 Offset = Builder.CreateMul(Idx, ElemSize);
1461 break;
1462 }
1463
1464 case OffsetOfExpr::OffsetOfNode::Field: {
1465 FieldDecl *MemberDecl = ON.getField();
1466 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1467 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1468
1469 // Compute the index of the field in its parent.
1470 unsigned i = 0;
1471 // FIXME: It would be nice if we didn't have to loop here!
1472 for (RecordDecl::field_iterator Field = RD->field_begin(),
1473 FieldEnd = RD->field_end();
1474 Field != FieldEnd; (void)++Field, ++i) {
1475 if (*Field == MemberDecl)
1476 break;
1477 }
1478 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1479
1480 // Compute the offset to the field
1481 int64_t OffsetInt = RL.getFieldOffset(i) /
1482 CGF.getContext().getCharWidth();
1483 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1484
1485 // Save the element type.
1486 CurrentType = MemberDecl->getType();
1487 break;
1488 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001489
Eli Friedman0027d2b2010-08-05 09:58:49 +00001490 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001491 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001492
Eli Friedman0027d2b2010-08-05 09:58:49 +00001493 case OffsetOfExpr::OffsetOfNode::Base: {
1494 if (ON.getBase()->isVirtual()) {
1495 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1496 continue;
1497 }
1498
1499 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1500 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1501
1502 // Save the element type.
1503 CurrentType = ON.getBase()->getType();
1504
1505 // Compute the offset to the base.
1506 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1507 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001508 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001509 CGF.getContext().getCharWidth();
1510 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1511 break;
1512 }
1513 }
1514 Result = Builder.CreateAdd(Result, Offset);
1515 }
1516 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001517}
1518
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001519/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001520/// argument of the sizeof expression as an integer.
1521Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001522ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1523 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001524 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001525 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001526 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001527 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1528 if (E->isArgumentType()) {
1529 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001530 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001531 } else {
1532 // C99 6.5.3.4p2: If the argument is an expression of type
1533 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001534 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001535 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001536
John McCallbc8d40d2011-06-24 21:55:10 +00001537 QualType eltType;
1538 llvm::Value *numElts;
1539 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1540
1541 llvm::Value *size = numElts;
1542
1543 // Scale the number of non-VLA elements by the non-VLA element size.
1544 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1545 if (!eltSize.isOne())
1546 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1547
1548 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001549 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001550 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001551
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001552 // If this isn't sizeof(vla), the result must be constant; use the constant
1553 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001554 Expr::EvalResult Result;
1555 E->Evaluate(Result, CGF.getContext());
Chris Lattner48431f92011-04-19 22:55:03 +00001556 return Builder.getInt(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001557}
1558
Chris Lattner46f93d02007-08-24 21:20:17 +00001559Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1560 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001561 if (Op->getType()->isAnyComplexType()) {
1562 // If it's an l-value, load through the appropriate subobject l-value.
1563 // Note that we have to ask E because Op might be an l-value that
1564 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001565 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001566 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001567
1568 // Otherwise, calculate and project.
1569 return CGF.EmitComplexExpr(Op, false, true).first;
1570 }
1571
Chris Lattner46f93d02007-08-24 21:20:17 +00001572 return Visit(Op);
1573}
John McCallb418d742010-11-16 10:08:07 +00001574
Chris Lattner46f93d02007-08-24 21:20:17 +00001575Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1576 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001577 if (Op->getType()->isAnyComplexType()) {
1578 // If it's an l-value, load through the appropriate subobject l-value.
1579 // Note that we have to ask E because Op might be an l-value that
1580 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001581 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001582 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001583
1584 // Otherwise, calculate and project.
1585 return CGF.EmitComplexExpr(Op, true, false).second;
1586 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001587
Mike Stump7f79f9b2009-05-29 15:46:01 +00001588 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1589 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001590 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001591 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001592}
1593
Chris Lattner7f02f722007-08-24 05:35:26 +00001594//===----------------------------------------------------------------------===//
1595// Binary Operators
1596//===----------------------------------------------------------------------===//
1597
1598BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001599 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001600 BinOpInfo Result;
1601 Result.LHS = Visit(E->getLHS());
1602 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001603 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001604 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001605 Result.E = E;
1606 return Result;
1607}
1608
Douglas Gregor6a03e342010-04-23 04:16:32 +00001609LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1610 const CompoundAssignOperator *E,
1611 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001612 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001613 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001614 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001615
Eli Friedmanab3a8522009-03-28 01:22:36 +00001616 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001617 // This needs to go through the complex expression emitter, but it's a tad
1618 // complicated to do that... I'm leaving it out for now. (Note that we do
1619 // actually need the imaginary part of the RHS for multiplication and
1620 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001621 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001622 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001623 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001624 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001625
Mike Stumpcc0442f2009-05-22 19:07:20 +00001626 // Emit the RHS first. __block variables need to have the rhs evaluated
1627 // first, plus this should improve codegen a little.
1628 OpInfo.RHS = Visit(E->getRHS());
1629 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001630 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001631 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001632 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001633 LValue LHSLV = EmitCheckedLValue(E->getLHS());
John McCall545d9962011-06-25 02:11:03 +00001634 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001635 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1636 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001637
Chris Lattner1f1ded92007-08-24 21:00:35 +00001638 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001639 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001640
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001641 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001642 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001643
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001644 // Store the result value into the LHS lvalue. Bit-fields are handled
1645 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1646 // 'An assignment expression has the value of the left operand after the
1647 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001648 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001649 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001650 else
John McCall545d9962011-06-25 02:11:03 +00001651 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001652
Douglas Gregor6a03e342010-04-23 04:16:32 +00001653 return LHSLV;
1654}
1655
1656Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1657 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1658 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001659 Value *RHS;
1660 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1661
1662 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001663 if (Ignore)
1664 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001665
John McCallb418d742010-11-16 10:08:07 +00001666 // The result of an assignment in C is the assigned r-value.
1667 if (!CGF.getContext().getLangOptions().CPlusPlus)
1668 return RHS;
1669
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001670 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001671 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001672 return RHS;
1673
1674 // If the lvalue is non-volatile, return the computed value of the assignment.
1675 if (!LHS.isVolatileQualified())
1676 return RHS;
1677
1678 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001679 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001680}
1681
Chris Lattner80230302010-09-11 21:47:09 +00001682void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1683 const BinOpInfo &Ops,
1684 llvm::Value *Zero, bool isDiv) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001685 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
Chris Lattner80230302010-09-11 21:47:09 +00001686 llvm::BasicBlock *contBB =
Bill Wendling14ef3192011-07-07 21:13:10 +00001687 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1688 llvm::next(insertPt));
1689 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001690
Chris Lattner2acc6e32011-07-18 04:24:23 +00001691 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001692
1693 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1694 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001695 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001696 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1697
1698 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1699 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1700 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1701 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1702 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1703 overflowBB, contBB);
1704 } else {
1705 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1706 overflowBB, contBB);
1707 }
1708 EmitOverflowBB(overflowBB);
1709 Builder.SetInsertPoint(contBB);
1710}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001711
Chris Lattner7f02f722007-08-24 05:35:26 +00001712Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001713 if (isTrapvOverflowBehavior()) {
1714 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1715
1716 if (Ops.Ty->isIntegerType())
1717 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1718 else if (Ops.Ty->isRealFloatingType()) {
Bill Wendling14ef3192011-07-07 21:13:10 +00001719 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1720 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1721 llvm::next(insertPt));
Chris Lattner80230302010-09-11 21:47:09 +00001722 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1723 CGF.CurFn);
Chris Lattner80230302010-09-11 21:47:09 +00001724 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1725 overflowBB, DivCont);
1726 EmitOverflowBB(overflowBB);
1727 Builder.SetInsertPoint(DivCont);
1728 }
1729 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001730 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001731 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001732 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001733 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1734 else
1735 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1736}
1737
1738Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1739 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001740 if (isTrapvOverflowBehavior()) {
1741 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1742
1743 if (Ops.Ty->isIntegerType())
1744 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1745 }
1746
Eli Friedman52d68742011-04-10 04:44:11 +00001747 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001748 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1749 else
1750 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1751}
1752
Mike Stump2add4732009-04-01 20:28:16 +00001753Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1754 unsigned IID;
1755 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001756
Chris Lattner9a207232010-06-26 21:48:21 +00001757 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001758 case BO_Add:
1759 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001760 OpID = 1;
1761 IID = llvm::Intrinsic::sadd_with_overflow;
1762 break;
John McCall2de56d12010-08-25 11:45:40 +00001763 case BO_Sub:
1764 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001765 OpID = 2;
1766 IID = llvm::Intrinsic::ssub_with_overflow;
1767 break;
John McCall2de56d12010-08-25 11:45:40 +00001768 case BO_Mul:
1769 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001770 OpID = 3;
1771 IID = llvm::Intrinsic::smul_with_overflow;
1772 break;
1773 default:
1774 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001775 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001776 }
Mike Stump035cf892009-04-02 18:15:54 +00001777 OpID <<= 1;
1778 OpID |= 1;
1779
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001780 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001781
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001782 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001783
1784 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1785 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1786 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1787
1788 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001789 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001790 llvm::Function::iterator insertPt = initialBB;
1791 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1792 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001793 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001794
1795 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1796
Chris Lattner93a00352010-08-07 00:20:46 +00001797 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001798 const std::string *handlerName =
1799 &CGF.getContext().getLangOptions().OverflowHandler;
1800 if (handlerName->empty()) {
1801 EmitOverflowBB(overflowBB);
1802 Builder.SetInsertPoint(continueBB);
1803 return result;
1804 }
1805
1806 // If an overflow handler is set, then we want to call it and then use its
1807 // result, if it returns.
1808 Builder.SetInsertPoint(overflowBB);
1809
1810 // Get the overflow handler.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001811 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1812 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001813 llvm::FunctionType *handlerTy =
1814 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1815 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1816
1817 // Sign extend the args to 64-bit, so that we can use the same handler for
1818 // all types of overflow.
1819 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1820 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1821
1822 // Call the handler with the two arguments, the operation, and the size of
1823 // the result.
1824 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1825 Builder.getInt8(OpID),
1826 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1827
1828 // Truncate the result back to the desired size.
1829 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1830 Builder.CreateBr(continueBB);
1831
Mike Stump2add4732009-04-01 20:28:16 +00001832 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001833 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001834 phi->addIncoming(result, initialBB);
1835 phi->addIncoming(handlerResult, overflowBB);
1836
1837 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001838}
Chris Lattner7f02f722007-08-24 05:35:26 +00001839
John McCall913dab22011-06-25 01:32:37 +00001840/// Emit pointer + index arithmetic.
1841static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1842 const BinOpInfo &op,
1843 bool isSubtraction) {
1844 // Must have binary (not unary) expr here. Unary pointer
1845 // increment/decrement doesn't use this path.
1846 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1847
1848 Value *pointer = op.LHS;
1849 Expr *pointerOperand = expr->getLHS();
1850 Value *index = op.RHS;
1851 Expr *indexOperand = expr->getRHS();
1852
1853 // In a subtraction, the LHS is always the pointer.
1854 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1855 std::swap(pointer, index);
1856 std::swap(pointerOperand, indexOperand);
1857 }
1858
1859 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1860 if (width != CGF.PointerWidthInBits) {
1861 // Zero-extend or sign-extend the pointer value according to
1862 // whether the index is signed or not.
1863 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1864 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1865 "idx.ext");
1866 }
1867
1868 // If this is subtraction, negate the index.
1869 if (isSubtraction)
1870 index = CGF.Builder.CreateNeg(index, "idx.neg");
1871
1872 const PointerType *pointerType
1873 = pointerOperand->getType()->getAs<PointerType>();
1874 if (!pointerType) {
1875 QualType objectType = pointerOperand->getType()
1876 ->castAs<ObjCObjectPointerType>()
1877 ->getPointeeType();
1878 llvm::Value *objectSize
1879 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1880
1881 index = CGF.Builder.CreateMul(index, objectSize);
1882
1883 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1884 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1885 return CGF.Builder.CreateBitCast(result, pointer->getType());
1886 }
1887
1888 QualType elementType = pointerType->getPointeeType();
1889 if (const VariableArrayType *vla
1890 = CGF.getContext().getAsVariableArrayType(elementType)) {
1891 // The element count here is the total number of non-VLA elements.
1892 llvm::Value *numElements = CGF.getVLASize(vla).first;
1893
1894 // Effectively, the multiply by the VLA size is part of the GEP.
1895 // GEP indexes are signed, and scaling an index isn't permitted to
1896 // signed-overflow, so we use the same semantics for our explicit
1897 // multiply. We suppress this if overflow is not undefined behavior.
1898 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1899 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1900 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1901 } else {
1902 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1903 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001904 }
John McCall913dab22011-06-25 01:32:37 +00001905 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001906 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001907
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001908 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1909 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1910 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001911 if (elementType->isVoidType() || elementType->isFunctionType()) {
1912 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1913 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1914 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001915 }
1916
John McCall913dab22011-06-25 01:32:37 +00001917 if (CGF.getLangOptions().isSignedOverflowDefined())
1918 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1919
1920 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001921}
1922
John McCall913dab22011-06-25 01:32:37 +00001923Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1924 if (op.LHS->getType()->isPointerTy() ||
1925 op.RHS->getType()->isPointerTy())
1926 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1927
1928 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1929 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1930 case LangOptions::SOB_Undefined:
1931 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1932 case LangOptions::SOB_Defined:
1933 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1934 case LangOptions::SOB_Trapping:
1935 return EmitOverflowCheckedBinOp(op);
1936 }
1937 }
1938
1939 if (op.LHS->getType()->isFPOrFPVectorTy())
1940 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
1941
1942 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1943}
1944
1945Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
1946 // The LHS is always a pointer if either side is.
1947 if (!op.LHS->getType()->isPointerTy()) {
1948 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001949 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1950 case LangOptions::SOB_Undefined:
John McCall913dab22011-06-25 01:32:37 +00001951 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001952 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00001953 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Chris Lattnera4d71452010-06-26 21:25:03 +00001954 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00001955 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00001956 }
1957 }
1958
John McCall913dab22011-06-25 01:32:37 +00001959 if (op.LHS->getType()->isFPOrFPVectorTy())
1960 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001961
John McCall913dab22011-06-25 01:32:37 +00001962 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001963 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001964
John McCall913dab22011-06-25 01:32:37 +00001965 // If the RHS is not a pointer, then we have normal pointer
1966 // arithmetic.
1967 if (!op.RHS->getType()->isPointerTy())
1968 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00001969
John McCall913dab22011-06-25 01:32:37 +00001970 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001971
John McCall913dab22011-06-25 01:32:37 +00001972 // Do the raw subtraction part.
1973 llvm::Value *LHS
1974 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
1975 llvm::Value *RHS
1976 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
1977 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00001978
John McCall913dab22011-06-25 01:32:37 +00001979 // Okay, figure out the element size.
1980 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1981 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001982
John McCall913dab22011-06-25 01:32:37 +00001983 llvm::Value *divisor = 0;
1984
1985 // For a variable-length array, this is going to be non-constant.
1986 if (const VariableArrayType *vla
1987 = CGF.getContext().getAsVariableArrayType(elementType)) {
1988 llvm::Value *numElements;
1989 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
1990
1991 divisor = numElements;
1992
1993 // Scale the number of non-VLA elements by the non-VLA element size.
1994 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
1995 if (!eltSize.isOne())
1996 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
1997
1998 // For everything elese, we can just compute it, safe in the
1999 // assumption that Sema won't let anything through that we can't
2000 // safely compute the size of.
2001 } else {
2002 CharUnits elementSize;
2003 // Handle GCC extension for pointer arithmetic on void* and
2004 // function pointer types.
2005 if (elementType->isVoidType() || elementType->isFunctionType())
2006 elementSize = CharUnits::One();
2007 else
2008 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2009
2010 // Don't even emit the divide for element size of 1.
2011 if (elementSize.isOne())
2012 return diffInChars;
2013
2014 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002015 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002016
Chris Lattner2cb42222011-03-01 00:03:48 +00002017 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2018 // pointer difference in C is only defined in the case where both operands
2019 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002020 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002021}
2022
2023Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2024 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2025 // RHS to the same size as the LHS.
2026 Value *RHS = Ops.RHS;
2027 if (Ops.LHS->getType() != RHS->getType())
2028 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002029
Mike Stumpbe07f602009-12-14 21:58:14 +00002030 if (CGF.CatchUndefined
2031 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2032 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2033 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2034 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2035 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002036 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002037 CGF.EmitBlock(Cont);
2038 }
2039
Chris Lattner7f02f722007-08-24 05:35:26 +00002040 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2041}
2042
2043Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2044 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2045 // RHS to the same size as the LHS.
2046 Value *RHS = Ops.RHS;
2047 if (Ops.LHS->getType() != RHS->getType())
2048 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002049
Mike Stumpbe07f602009-12-14 21:58:14 +00002050 if (CGF.CatchUndefined
2051 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2052 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2053 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2054 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2055 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002056 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002057 CGF.EmitBlock(Cont);
2058 }
2059
Douglas Gregorf6094622010-07-23 15:58:24 +00002060 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002061 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2062 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2063}
2064
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002065enum IntrinsicType { VCMPEQ, VCMPGT };
2066// return corresponding comparison intrinsic for given vector type
2067static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2068 BuiltinType::Kind ElemKind) {
2069 switch (ElemKind) {
2070 default: assert(0 && "unexpected element type");
2071 case BuiltinType::Char_U:
2072 case BuiltinType::UChar:
2073 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2074 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2075 break;
2076 case BuiltinType::Char_S:
2077 case BuiltinType::SChar:
2078 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2079 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2080 break;
2081 case BuiltinType::UShort:
2082 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2083 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2084 break;
2085 case BuiltinType::Short:
2086 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2087 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2088 break;
2089 case BuiltinType::UInt:
2090 case BuiltinType::ULong:
2091 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2092 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2093 break;
2094 case BuiltinType::Int:
2095 case BuiltinType::Long:
2096 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2097 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2098 break;
2099 case BuiltinType::Float:
2100 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2101 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2102 break;
2103 }
2104 return llvm::Intrinsic::not_intrinsic;
2105}
2106
Chris Lattner7f02f722007-08-24 05:35:26 +00002107Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2108 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002109 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002110 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002111 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002112 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002113 assert(E->getOpcode() == BO_EQ ||
2114 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002115 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2116 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002117 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002118 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002119 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002120 Value *LHS = Visit(E->getLHS());
2121 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002122
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002123 // If AltiVec, the comparison results in a numeric type, so we use
2124 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002125 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002126 // constants for mapping CR6 register bits to predicate result
2127 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2128
2129 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2130
2131 // in several cases vector arguments order will be reversed
2132 Value *FirstVecArg = LHS,
2133 *SecondVecArg = RHS;
2134
2135 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002136 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002137 BuiltinType::Kind ElementKind = BTy->getKind();
2138
2139 switch(E->getOpcode()) {
2140 default: assert(0 && "is not a comparison operation");
2141 case BO_EQ:
2142 CR6 = CR6_LT;
2143 ID = GetIntrinsic(VCMPEQ, ElementKind);
2144 break;
2145 case BO_NE:
2146 CR6 = CR6_EQ;
2147 ID = GetIntrinsic(VCMPEQ, ElementKind);
2148 break;
2149 case BO_LT:
2150 CR6 = CR6_LT;
2151 ID = GetIntrinsic(VCMPGT, ElementKind);
2152 std::swap(FirstVecArg, SecondVecArg);
2153 break;
2154 case BO_GT:
2155 CR6 = CR6_LT;
2156 ID = GetIntrinsic(VCMPGT, ElementKind);
2157 break;
2158 case BO_LE:
2159 if (ElementKind == BuiltinType::Float) {
2160 CR6 = CR6_LT;
2161 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2162 std::swap(FirstVecArg, SecondVecArg);
2163 }
2164 else {
2165 CR6 = CR6_EQ;
2166 ID = GetIntrinsic(VCMPGT, ElementKind);
2167 }
2168 break;
2169 case BO_GE:
2170 if (ElementKind == BuiltinType::Float) {
2171 CR6 = CR6_LT;
2172 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2173 }
2174 else {
2175 CR6 = CR6_EQ;
2176 ID = GetIntrinsic(VCMPGT, ElementKind);
2177 std::swap(FirstVecArg, SecondVecArg);
2178 }
2179 break;
2180 }
2181
Chris Lattner48431f92011-04-19 22:55:03 +00002182 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002183 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2184 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2185 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2186 }
2187
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002188 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002189 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002190 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002191 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002192 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002193 LHS, RHS, "cmp");
2194 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002195 // Unsigned integers and pointers.
2196 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002197 LHS, RHS, "cmp");
2198 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002199
2200 // If this is a vector comparison, sign extend the result to the appropriate
2201 // vector integer type and return it (don't convert to bool).
2202 if (LHSTy->isVectorType())
2203 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002204
Chris Lattner7f02f722007-08-24 05:35:26 +00002205 } else {
2206 // Complex Comparison: can only be an equality comparison.
2207 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2208 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002209
John McCall183700f2009-09-21 23:43:11 +00002210 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002211
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002212 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002213 if (CETy->isRealFloatingType()) {
2214 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2215 LHS.first, RHS.first, "cmp.r");
2216 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2217 LHS.second, RHS.second, "cmp.i");
2218 } else {
2219 // Complex comparisons can only be equality comparisons. As such, signed
2220 // and unsigned opcodes are the same.
2221 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2222 LHS.first, RHS.first, "cmp.r");
2223 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2224 LHS.second, RHS.second, "cmp.i");
2225 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002226
John McCall2de56d12010-08-25 11:45:40 +00002227 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002228 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2229 } else {
John McCall2de56d12010-08-25 11:45:40 +00002230 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002231 "Complex comparison other than == or != ?");
2232 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2233 }
2234 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002235
2236 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002237}
2238
2239Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002240 bool Ignore = TestAndClearIgnoreResultAssign();
2241
John McCallf85e1932011-06-15 23:02:42 +00002242 Value *RHS;
2243 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002244
John McCallf85e1932011-06-15 23:02:42 +00002245 switch (E->getLHS()->getType().getObjCLifetime()) {
2246 case Qualifiers::OCL_Strong:
2247 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2248 break;
2249
2250 case Qualifiers::OCL_Autoreleasing:
2251 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2252 break;
2253
2254 case Qualifiers::OCL_Weak:
2255 RHS = Visit(E->getRHS());
2256 LHS = EmitCheckedLValue(E->getLHS());
2257 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2258 break;
2259
2260 // No reason to do any of these differently.
2261 case Qualifiers::OCL_None:
2262 case Qualifiers::OCL_ExplicitNone:
2263 // __block variables need to have the rhs evaluated first, plus
2264 // this should improve codegen just a little.
2265 RHS = Visit(E->getRHS());
2266 LHS = EmitCheckedLValue(E->getLHS());
2267
2268 // Store the value into the LHS. Bit-fields are handled specially
2269 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2270 // 'An assignment expression has the value of the left operand after
2271 // the assignment...'.
2272 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002273 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002274 else
John McCall545d9962011-06-25 02:11:03 +00002275 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002276 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002277
2278 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002279 if (Ignore)
2280 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002281
John McCallb418d742010-11-16 10:08:07 +00002282 // The result of an assignment in C is the assigned r-value.
2283 if (!CGF.getContext().getLangOptions().CPlusPlus)
2284 return RHS;
2285
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002286 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002287 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002288 return RHS;
2289
2290 // If the lvalue is non-volatile, return the computed value of the assignment.
2291 if (!LHS.isVolatileQualified())
2292 return RHS;
2293
2294 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002295 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002296}
2297
2298Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002299 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002300
Chris Lattner20eb09d2008-11-12 08:26:50 +00002301 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2302 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002303 bool LHSCondVal;
2304 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2305 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002306 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002307 // ZExt result to int or bool.
2308 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002309 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002310
Chris Lattner7804bcb2009-10-17 04:24:20 +00002311 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002312 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002313 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002314 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002315
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002316 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2317 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002318
John McCall150b4622011-01-26 04:00:11 +00002319 CodeGenFunction::ConditionalEvaluation eval(CGF);
2320
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002321 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2322 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2323
2324 // Any edges into the ContBlock are now from an (indeterminate number of)
2325 // edges from this first condition. All of these values will be false. Start
2326 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002327 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002328 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002329 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2330 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002331 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002332
John McCall150b4622011-01-26 04:00:11 +00002333 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002334 CGF.EmitBlock(RHSBlock);
2335 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002336 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002337
Chris Lattner7f02f722007-08-24 05:35:26 +00002338 // Reaquire the RHS block, as there may be subblocks inserted.
2339 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002340
2341 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2342 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002343 if (CGF.getDebugInfo())
2344 // There is no need to emit line number for unconditional branch.
2345 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002346 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002347 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002348
Chris Lattner7f02f722007-08-24 05:35:26 +00002349 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002350 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002351}
2352
2353Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002354 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002355
Chris Lattner20eb09d2008-11-12 08:26:50 +00002356 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2357 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002358 bool LHSCondVal;
2359 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2360 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002361 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002362 // ZExt result to int or bool.
2363 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002364 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002365
Chris Lattner7804bcb2009-10-17 04:24:20 +00002366 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002367 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002368 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002369 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002370
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002371 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2372 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002373
John McCall150b4622011-01-26 04:00:11 +00002374 CodeGenFunction::ConditionalEvaluation eval(CGF);
2375
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002376 // Branch on the LHS first. If it is true, go to the success (cont) block.
2377 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2378
2379 // Any edges into the ContBlock are now from an (indeterminate number of)
2380 // edges from this first condition. All of these values will be true. Start
2381 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002382 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002383 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002384 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2385 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002386 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002387
John McCall150b4622011-01-26 04:00:11 +00002388 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002389
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002390 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002391 CGF.EmitBlock(RHSBlock);
2392 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002393
John McCall150b4622011-01-26 04:00:11 +00002394 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002395
Chris Lattner7f02f722007-08-24 05:35:26 +00002396 // Reaquire the RHS block, as there may be subblocks inserted.
2397 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002398
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002399 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2400 // into the phi node for the edge with the value of RHSCond.
2401 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002402 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002403
Chris Lattner7f02f722007-08-24 05:35:26 +00002404 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002405 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002406}
2407
2408Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002409 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002410 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002411 return Visit(E->getRHS());
2412}
2413
2414//===----------------------------------------------------------------------===//
2415// Other Operators
2416//===----------------------------------------------------------------------===//
2417
Chris Lattner9802a512008-11-12 08:55:54 +00002418/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2419/// expression is cheap enough and side-effect-free enough to evaluate
2420/// unconditionally instead of conditionally. This is used to convert control
2421/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002422static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2423 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002424 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002425
Chris Lattnerc6bea672011-04-16 23:15:35 +00002426 // Anything that is an integer or floating point constant is fine.
2427 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002428 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002429
Chris Lattner9802a512008-11-12 08:55:54 +00002430 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2431 // X and Y are local variables.
2432 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2433 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002434 if (VD->hasLocalStorage() && !(CGF.getContext()
2435 .getCanonicalType(VD->getType())
2436 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002437 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002438
Chris Lattner9802a512008-11-12 08:55:54 +00002439 return false;
2440}
2441
2442
Chris Lattner7f02f722007-08-24 05:35:26 +00002443Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002444VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002445 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002446
2447 // Bind the common expression if necessary.
2448 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2449
2450 Expr *condExpr = E->getCond();
2451 Expr *lhsExpr = E->getTrueExpr();
2452 Expr *rhsExpr = E->getFalseExpr();
2453
Chris Lattner31a09842008-11-12 08:04:58 +00002454 // If the condition constant folds and can be elided, try to avoid emitting
2455 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002456 bool CondExprBool;
2457 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002458 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002459 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002460
Chris Lattner31a09842008-11-12 08:04:58 +00002461 // If the dead side doesn't have labels we need, and if the Live side isn't
2462 // the gnu missing ?: extension (which we could handle, but don't bother
2463 // to), just emit the Live part.
John McCall56ca35d2011-02-17 10:25:35 +00002464 if (!CGF.ContainsLabel(dead))
2465 return Visit(live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002466 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002467
Nate Begeman6155d732010-09-20 22:41:17 +00002468 // OpenCL: If the condition is a vector, we can treat this condition like
2469 // the select function.
2470 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002471 && condExpr->getType()->isVectorType()) {
2472 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2473 llvm::Value *LHS = Visit(lhsExpr);
2474 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002475
Chris Lattner2acc6e32011-07-18 04:24:23 +00002476 llvm::Type *condType = ConvertType(condExpr->getType());
2477 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002478
2479 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002480 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002481
2482 std::vector<llvm::Constant*> Zvals;
2483 for (unsigned i = 0; i < numElem; ++i)
Chris Lattner48431f92011-04-19 22:55:03 +00002484 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002485
Nate Begeman6155d732010-09-20 22:41:17 +00002486 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2487 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2488 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2489 llvm::VectorType::get(elemType,
2490 numElem),
2491 "sext");
2492 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2493
2494 // Cast float to int to perform ANDs if necessary.
2495 llvm::Value *RHSTmp = RHS;
2496 llvm::Value *LHSTmp = LHS;
2497 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002498 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002499 if (rhsVTy->getElementType()->isFloatTy()) {
2500 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2501 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2502 wasCast = true;
2503 }
2504
2505 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2506 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2507 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2508 if (wasCast)
2509 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2510
2511 return tmp5;
2512 }
2513
Chris Lattner9802a512008-11-12 08:55:54 +00002514 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2515 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002516 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002517 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2518 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2519 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2520 llvm::Value *LHS = Visit(lhsExpr);
2521 llvm::Value *RHS = Visit(rhsExpr);
Chris Lattner9802a512008-11-12 08:55:54 +00002522 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2523 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002524
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002525 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2526 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002527 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002528
2529 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002530 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002531
Chris Lattner7f02f722007-08-24 05:35:26 +00002532 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002533 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002534 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002535 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002536
Chris Lattner7f02f722007-08-24 05:35:26 +00002537 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002538 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002539
Chris Lattner7f02f722007-08-24 05:35:26 +00002540 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002541 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002542 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002543 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002544
John McCall150b4622011-01-26 04:00:11 +00002545 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002546 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002547
Eli Friedman48daf592009-12-07 20:25:53 +00002548 // If the LHS or RHS is a throw expression, it will be legitimately null.
2549 if (!LHS)
2550 return RHS;
2551 if (!RHS)
2552 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002553
Chris Lattner7f02f722007-08-24 05:35:26 +00002554 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002555 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002556 PN->addIncoming(LHS, LHSBlock);
2557 PN->addIncoming(RHS, RHSBlock);
2558 return PN;
2559}
2560
2561Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002562 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002563}
2564
Chris Lattner2202bce2007-11-30 17:56:23 +00002565Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002566 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002567 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2568
2569 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002570 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002571 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2572
Mike Stump7f79f9b2009-05-29 15:46:01 +00002573 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002574 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002575}
2576
John McCall6b5a61b2011-02-07 10:33:21 +00002577Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2578 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002579}
2580
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002581Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2582 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002583 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002584
2585 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2586 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002587 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002588 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2589 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2590 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2591 if ((numElementsDst == 3 && numElementsSrc == 4)
2592 || (numElementsDst == 4 && numElementsSrc == 3)) {
2593
2594
2595 // In the case of going from int4->float3, a bitcast is needed before
2596 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002597 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002598 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002599 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002600 cast<llvm::VectorType>(DstTy)->getElementType();
2601
2602 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2603 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2604 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002605 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002606 numElementsSrc);
2607
2608 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2609 }
2610
2611 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2612
Chris Lattner5f9e2722011-07-23 10:55:15 +00002613 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002614 Args.push_back(Builder.getInt32(0));
2615 Args.push_back(Builder.getInt32(1));
2616 Args.push_back(Builder.getInt32(2));
2617
2618 if (numElementsDst == 4)
2619 Args.push_back(llvm::UndefValue::get(
2620 llvm::Type::getInt32Ty(CGF.getLLVMContext())));
2621
2622 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2623
2624 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2625 }
2626 }
2627
2628 return Builder.CreateBitCast(Src, DstTy, "astype");
2629}
2630
Chris Lattner7f02f722007-08-24 05:35:26 +00002631//===----------------------------------------------------------------------===//
2632// Entry Point into this File
2633//===----------------------------------------------------------------------===//
2634
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002635/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2636/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002637Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002638 assert(E && !hasAggregateLLVMType(E->getType()) &&
2639 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002640
Devang Patel5de7a0e2011-03-07 18:29:53 +00002641 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002642 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002643 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002644 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002645 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002646 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002647 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002648}
Chris Lattner3707b252007-08-26 06:48:56 +00002649
2650/// EmitScalarConversion - Emit a conversion from the specified type to the
2651/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002652Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2653 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002654 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2655 "Invalid scalar expression to emit");
2656 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2657}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002658
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002659/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2660/// type to the specified destination type, where the destination type is an
2661/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002662Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2663 QualType SrcTy,
2664 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002665 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002666 "Invalid complex -> scalar conversion");
2667 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2668 DstTy);
2669}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002670
Chris Lattner8c11a652010-06-26 22:09:34 +00002671
2672llvm::Value *CodeGenFunction::
2673EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2674 bool isInc, bool isPre) {
2675 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2676}
2677
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002678LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2679 llvm::Value *V;
2680 // object->isa or (*object).isa
2681 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002682 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002683 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002684
2685 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002686 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002687 V = CreateTempAlloca(ClassPtrTy, "resval");
2688 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2689 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002690 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
John McCall545d9962011-06-25 02:11:03 +00002691 MakeAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002692 } else {
2693 if (E->isArrow())
2694 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2695 else
2696 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002697 }
2698
2699 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002700 ClassPtrTy = ClassPtrTy->getPointerTo();
2701 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002702 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002703}
2704
Douglas Gregor6a03e342010-04-23 04:16:32 +00002705
John McCall2a416372010-12-05 02:00:02 +00002706LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002707 const CompoundAssignOperator *E) {
2708 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002709 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002710 switch (E->getOpcode()) {
2711#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002712 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002713 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002714 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002715 COMPOUND_OP(Mul);
2716 COMPOUND_OP(Div);
2717 COMPOUND_OP(Rem);
2718 COMPOUND_OP(Add);
2719 COMPOUND_OP(Sub);
2720 COMPOUND_OP(Shl);
2721 COMPOUND_OP(Shr);
2722 COMPOUND_OP(And);
2723 COMPOUND_OP(Xor);
2724 COMPOUND_OP(Or);
2725#undef COMPOUND_OP
2726
John McCall2de56d12010-08-25 11:45:40 +00002727 case BO_PtrMemD:
2728 case BO_PtrMemI:
2729 case BO_Mul:
2730 case BO_Div:
2731 case BO_Rem:
2732 case BO_Add:
2733 case BO_Sub:
2734 case BO_Shl:
2735 case BO_Shr:
2736 case BO_LT:
2737 case BO_GT:
2738 case BO_LE:
2739 case BO_GE:
2740 case BO_EQ:
2741 case BO_NE:
2742 case BO_And:
2743 case BO_Xor:
2744 case BO_Or:
2745 case BO_LAnd:
2746 case BO_LOr:
2747 case BO_Assign:
2748 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002749 assert(false && "Not valid compound assignment operators");
2750 break;
2751 }
2752
2753 llvm_unreachable("Unhandled compound assignment operator");
2754}