blob: d5ed233a978e2383bb812bf7095010460e07fde8 [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattner2da04b32007-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 Patel44b8bf02010-10-04 21:46:04 +000014#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000015#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian07ca7272009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Devang Patel44b8bf02010-10-04 21:46:04 +000019#include "CGDebugInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000025#include "llvm/Constants.h"
26#include "llvm/Function.h"
Anders Carlssond8499822007-10-29 05:01:08 +000027#include "llvm/GlobalVariable.h"
Anders Carlsson7e13ab82007-10-15 20:28:48 +000028#include "llvm/Intrinsics.h"
Mike Stump0c61b732009-04-01 20:28:16 +000029#include "llvm/Module.h"
Chris Lattner35710d182008-11-12 08:38:24 +000030#include "llvm/Support/CFG.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000031#include "llvm/Target/TargetData.h"
Chris Lattner1800c182008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000033
Chris Lattner2da04b32007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000042namespace {
Chris Lattner2da04b32007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-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 Lattner2da04b32007-08-24 05:35:26 +000049};
50
John McCalle84af4e2010-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 Kramer337e3a52009-11-28 19:45:26 +000058class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +000059 : public StmtVisitor<ScalarExprEmitter, Value*> {
60 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +000061 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +000062 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +000063 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +000064public:
65
Mike Stumpdf0fe272009-05-29 15:46:01 +000066 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +000067 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +000068 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +000069 }
Mike Stump4a3999f2009-09-09 13:00:44 +000070
Chris Lattner2da04b32007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Utilities
73 //===--------------------------------------------------------------------===//
74
Mike Stumpdf0fe272009-05-29 15:46:01 +000075 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +000076 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
78 return I;
79 }
Mike Stumpdf0fe272009-05-29 15:46:01 +000080
Chris Lattner2192fe52011-07-18 04:24:23 +000081 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +000082 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith69d0d262012-08-24 00:54:33 +000083 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::CheckType CT) {
84 return CGF.EmitCheckedLValue(E, CT);
85 }
Chris Lattner2da04b32007-08-24 05:35:26 +000086
John McCall55e1fbc2011-06-25 02:11:03 +000087 Value *EmitLoadOfLValue(LValue LV) {
88 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +000089 }
Mike Stump4a3999f2009-09-09 13:00:44 +000090
Chris Lattner2da04b32007-08-24 05:35:26 +000091 /// EmitLoadOfLValue - Given an expression with complex type that represents a
92 /// value l-value, this method emits the address of the l-value, then loads
93 /// and returns the result.
94 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith69d0d262012-08-24 00:54:33 +000095 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::CT_Load));
Chris Lattner2da04b32007-08-24 05:35:26 +000096 }
Mike Stump4a3999f2009-09-09 13:00:44 +000097
Chris Lattnere0044382007-08-26 16:42:57 +000098 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +000099 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000100 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000101
Chris Lattner3474c202007-08-26 06:48:56 +0000102 /// EmitScalarConversion - Emit a conversion from the specified type to the
103 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000104 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
105
106 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stump4a3999f2009-09-09 13:00:44 +0000107 /// complex type to the specified destination type, where the destination type
108 /// is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000109 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
110 QualType SrcTy, QualType DstTy);
Mike Stumpab3afd82009-02-12 18:29:15 +0000111
Anders Carlsson5b944432010-05-22 17:45:10 +0000112 /// EmitNullValue - Emit a value that corresponds to null for the given type.
113 Value *EmitNullValue(QualType Ty);
114
John McCall8cb679e2010-11-15 09:13:47 +0000115 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
116 Value *EmitFloatToBoolConversion(Value *V) {
117 // Compare against 0.0 for fp scalars.
118 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
119 return Builder.CreateFCmpUNE(V, Zero, "tobool");
120 }
121
122 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
123 Value *EmitPointerToBoolConversion(Value *V) {
124 Value *Zero = llvm::ConstantPointerNull::get(
125 cast<llvm::PointerType>(V->getType()));
126 return Builder.CreateICmpNE(V, Zero, "tobool");
127 }
128
129 Value *EmitIntToBoolConversion(Value *V) {
130 // Because of the type rules of C, we often end up computing a
131 // logical value, then zero extending it to int, then wanting it
132 // as a logical value again. Optimize this common case.
133 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
134 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
135 Value *Result = ZI->getOperand(0);
136 // If there aren't any more uses, zap the instruction to save space.
137 // Note that there can be more uses, for example if this
138 // is the result of an assignment.
139 if (ZI->use_empty())
140 ZI->eraseFromParent();
141 return Result;
142 }
143 }
144
Chris Lattner2531eb42011-04-19 22:55:03 +0000145 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000146 }
147
Chris Lattner2da04b32007-08-24 05:35:26 +0000148 //===--------------------------------------------------------------------===//
149 // Visitor Methods
150 //===--------------------------------------------------------------------===//
151
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000152 Value *Visit(Expr *E) {
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000153 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 }
155
Chris Lattner2da04b32007-08-24 05:35:26 +0000156 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000157 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000158 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000159 }
160 Value *VisitExpr(Expr *S);
Fariborz Jahanian52987dc2009-10-21 23:45:42 +0000161
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000162 Value *VisitParenExpr(ParenExpr *PE) {
163 return Visit(PE->getSubExpr());
164 }
John McCall7c454bb2011-07-15 05:09:51 +0000165 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
166 return Visit(E->getReplacement());
167 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000168 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
169 return Visit(GE->getResultExpr());
170 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000171
172 // Leaves.
173 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000174 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000175 }
176 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000177 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000178 }
179 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000180 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000181 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000182 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
183 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
184 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000185 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000186 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000187 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000188 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000189 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000190 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000191 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000192 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000193 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000194 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000195 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000196 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000197 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
198 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000199 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000200
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000201 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000202 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000203 }
John McCall1bf58462011-02-16 08:02:54 +0000204
John McCallfe96e0b2011-11-06 09:01:30 +0000205 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
206 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
207 }
208
John McCall1bf58462011-02-16 08:02:54 +0000209 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000210 if (E->isGLValue())
John McCall55e1fbc2011-06-25 02:11:03 +0000211 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCall1bf58462011-02-16 08:02:54 +0000212
213 // Otherwise, assume the mapping is the scalar directly.
John McCallc07a0c72011-02-17 10:25:35 +0000214 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000215 }
John McCall71335052012-03-10 03:05:10 +0000216
Chris Lattner2da04b32007-08-24 05:35:26 +0000217 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000218 Value *VisitDeclRefExpr(DeclRefExpr *E) {
219 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCall71335052012-03-10 03:05:10 +0000220 if (result.isReference())
John McCall113bee02012-03-10 09:33:50 +0000221 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCall71335052012-03-10 03:05:10 +0000222 return result.getValue();
Richard Smithbc6387672012-03-02 23:27:11 +0000223 }
John McCall113bee02012-03-10 09:33:50 +0000224 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000225 }
226
Mike Stump4a3999f2009-09-09 13:00:44 +0000227 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
228 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000229 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000230 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
231 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000232 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000233 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000234 return EmitLoadOfLValue(E);
235 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000236 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanianff989032011-03-02 20:09:49 +0000237 if (E->getMethodDecl() &&
238 E->getMethodDecl()->getResultType()->isReferenceType())
239 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000240 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000241 }
242
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000243 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000244 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall55e1fbc2011-06-25 02:11:03 +0000245 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000246 return V;
247 }
248
Chris Lattner2da04b32007-08-24 05:35:26 +0000249 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000250 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000251 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000252 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000253 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
254 return EmitLoadOfLValue(E);
255 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000256
Nate Begeman19351632009-10-18 20:10:40 +0000257 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000258
Douglas Gregor0202cb42009-01-29 17:44:32 +0000259 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson65c6d542010-05-14 15:05:19 +0000260 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000261 }
John McCall23c29fe2011-06-24 21:55:10 +0000262 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 if (E->getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000264 CGF.EmitVariablyModifiedType(E->getType());
265 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000266 }
John McCall23c29fe2011-06-24 21:55:10 +0000267 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000268
269 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000270 if (E->getCallReturnType()->isReferenceType())
271 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000272
Chris Lattner4647a212007-08-31 22:49:20 +0000273 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000274 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000275
Chris Lattner04a913b2007-08-31 22:09:40 +0000276 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000277
Chris Lattner2da04b32007-08-24 05:35:26 +0000278 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000279 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000280 LValue LV = EmitLValue(E->getSubExpr());
281 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000282 }
283 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000284 LValue LV = EmitLValue(E->getSubExpr());
285 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000286 }
287 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000288 LValue LV = EmitLValue(E->getSubExpr());
289 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000290 }
291 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000292 LValue LV = EmitLValue(E->getSubExpr());
293 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000294 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000295
Anton Yartsev85129b82011-02-07 02:17:30 +0000296 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
297 llvm::Value *InVal,
298 llvm::Value *NextVal,
299 bool IsInc);
300
Chris Lattner05dc78c2010-06-26 22:09:34 +0000301 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
302 bool isInc, bool isPre);
303
304
Chris Lattner2da04b32007-08-24 05:35:26 +0000305 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000306 if (isa<MemberPointerType>(E->getType())) // never sugared
307 return CGF.CGM.getMemberPointerConstant(E);
308
Chris Lattner2da04b32007-08-24 05:35:26 +0000309 return EmitLValue(E->getSubExpr()).getAddress();
310 }
John McCall59482722010-12-04 12:43:24 +0000311 Value *VisitUnaryDeref(const UnaryOperator *E) {
312 if (E->getType()->isVoidType())
313 return Visit(E->getSubExpr()); // the actual value should be unused
314 return EmitLoadOfLValue(E);
315 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000316 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000317 // This differs from gcc, though, most likely due to a bug in gcc.
318 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000319 return Visit(E->getSubExpr());
320 }
321 Value *VisitUnaryMinus (const UnaryOperator *E);
322 Value *VisitUnaryNot (const UnaryOperator *E);
323 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000324 Value *VisitUnaryReal (const UnaryOperator *E);
325 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000326 Value *VisitUnaryExtension(const UnaryOperator *E) {
327 return Visit(E->getSubExpr());
328 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000329
Anders Carlssona5d077d2009-04-14 16:58:56 +0000330 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000331 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000332 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000333 }
334
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000335 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
336 return Visit(DAE->getExpr());
337 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000338 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
339 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000340 }
341
John McCall5d413782010-12-06 08:20:24 +0000342 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +0000343 CGF.enterFullExpression(E);
344 CodeGenFunction::RunCleanupsScope Scope(CGF);
345 return Visit(E->getSubExpr());
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000346 }
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000347 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
348 return CGF.EmitCXXNewExpr(E);
349 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000350 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
351 CGF.EmitCXXDeleteExpr(E);
352 return 0;
353 }
Eli Friedmand70bbfd2009-12-10 22:40:32 +0000354 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000355 return Builder.getInt1(E->getValue());
Eli Friedmand70bbfd2009-12-10 22:40:32 +0000356 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000357
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000358 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000359 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000360 }
361
John Wiegley6242b6a2011-04-28 00:16:57 +0000362 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
363 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
364 }
365
John Wiegleyf9f65842011-04-25 06:54:41 +0000366 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
367 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
368 }
369
Douglas Gregorad8a3362009-09-04 17:36:40 +0000370 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
371 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000372 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000373 // operator (), and the result of such a call has type void. The only
374 // effect is the evaluation of the postfix-expression before the dot or
375 // arrow.
376 CGF.EmitScalarExpr(E->getBase());
377 return 0;
378 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000379
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000380 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000381 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000382 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000383
384 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
385 CGF.EmitCXXThrowExpr(E);
386 return 0;
387 }
388
Sebastian Redlb67655f2010-09-10 21:04:00 +0000389 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000390 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000391 }
392
Chris Lattner2da04b32007-08-24 05:35:26 +0000393 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000394 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000395 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000396 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000397 case LangOptions::SOB_Defined:
398 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000399 case LangOptions::SOB_Undefined:
400 if (!CGF.CatchUndefined)
401 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
402 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +0000403 case LangOptions::SOB_Trapping:
404 return EmitOverflowCheckedBinOp(Ops);
405 }
406 }
407
Duncan Sands998f9d92010-02-15 16:14:01 +0000408 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner94dfae22009-06-17 06:36:24 +0000409 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner2da04b32007-08-24 05:35:26 +0000410 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
411 }
Chris Lattner8ee6a412010-09-11 21:47:09 +0000412 bool isTrapvOverflowBehavior() {
Richard Smith3e056de2012-08-25 00:32:28 +0000413 return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
414 == LangOptions::SOB_Trapping || CGF.CatchUndefined;
Chris Lattner8ee6a412010-09-11 21:47:09 +0000415 }
Mike Stump0c61b732009-04-01 20:28:16 +0000416 /// Create a binary op that checks for overflow.
417 /// Currently only supports +, - and *.
418 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +0000419 // Emit the overflow BB when -ftrapv option is activated.
420 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
421 Builder.SetInsertPoint(overflowBB);
422 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
423 Builder.CreateCall(Trap);
424 Builder.CreateUnreachable();
425 }
426 // Check for undefined division and modulus behaviors.
427 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
428 llvm::Value *Zero,bool isDiv);
Chris Lattner2da04b32007-08-24 05:35:26 +0000429 Value *EmitDiv(const BinOpInfo &Ops);
430 Value *EmitRem(const BinOpInfo &Ops);
431 Value *EmitAdd(const BinOpInfo &Ops);
432 Value *EmitSub(const BinOpInfo &Ops);
433 Value *EmitShl(const BinOpInfo &Ops);
434 Value *EmitShr(const BinOpInfo &Ops);
435 Value *EmitAnd(const BinOpInfo &Ops) {
436 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
437 }
438 Value *EmitXor(const BinOpInfo &Ops) {
439 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
440 }
441 Value *EmitOr (const BinOpInfo &Ops) {
442 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
443 }
444
Chris Lattner3d966d62007-08-24 21:00:35 +0000445 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000446 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
447 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000448 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000449
Chris Lattnerb6334692007-08-26 21:41:21 +0000450 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000451 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
452
453 // Binary operators and binary compound assignment operators.
454#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000455 Value *VisitBin ## OP(const BinaryOperator *E) { \
456 return Emit ## OP(EmitBinOps(E)); \
457 } \
458 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
459 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000460 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000461 HANDLEBINOP(Mul)
462 HANDLEBINOP(Div)
463 HANDLEBINOP(Rem)
464 HANDLEBINOP(Add)
465 HANDLEBINOP(Sub)
466 HANDLEBINOP(Shl)
467 HANDLEBINOP(Shr)
468 HANDLEBINOP(And)
469 HANDLEBINOP(Xor)
470 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000471#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000472
Chris Lattner2da04b32007-08-24 05:35:26 +0000473 // Comparisons.
474 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
475 unsigned SICmpOpc, unsigned FCmpOpc);
476#define VISITCOMP(CODE, UI, SI, FP) \
477 Value *VisitBin##CODE(const BinaryOperator *E) { \
478 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
479 llvm::FCmpInst::FP); }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000480 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
481 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
482 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
483 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
484 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
485 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner2da04b32007-08-24 05:35:26 +0000486#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000487
Chris Lattner2da04b32007-08-24 05:35:26 +0000488 Value *VisitBinAssign (const BinaryOperator *E);
489
490 Value *VisitBinLAnd (const BinaryOperator *E);
491 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000492 Value *VisitBinComma (const BinaryOperator *E);
493
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000494 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
495 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
496
Chris Lattner2da04b32007-08-24 05:35:26 +0000497 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000498 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000499 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000500 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000501 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000502 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
503 return CGF.EmitObjCStringLiteral(E);
504 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000505 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
506 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000507 }
508 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
509 return CGF.EmitObjCArrayLiteral(E);
510 }
511 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
512 return CGF.EmitObjCDictionaryLiteral(E);
513 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000514 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000515 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000516};
517} // end anonymous namespace.
518
519//===----------------------------------------------------------------------===//
520// Utilities
521//===----------------------------------------------------------------------===//
522
Chris Lattnere0044382007-08-26 16:42:57 +0000523/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000524/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000525Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000526 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000527
John McCall8cb679e2010-11-15 09:13:47 +0000528 if (SrcType->isRealFloatingType())
529 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000530
John McCall7a9aac22010-08-23 01:21:21 +0000531 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
532 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000533
Daniel Dunbaref957f32008-08-25 10:38:11 +0000534 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000535 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000536
John McCall8cb679e2010-11-15 09:13:47 +0000537 if (isa<llvm::IntegerType>(Src->getType()))
538 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000539
John McCall8cb679e2010-11-15 09:13:47 +0000540 assert(isa<llvm::PointerType>(Src->getType()));
541 return EmitPointerToBoolConversion(Src);
Chris Lattnere0044382007-08-26 16:42:57 +0000542}
543
Chris Lattner3474c202007-08-26 06:48:56 +0000544/// EmitScalarConversion - Emit a conversion from the specified type to the
545/// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000546Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
547 QualType DstType) {
Chris Lattner0f398c42008-07-26 22:37:01 +0000548 SrcType = CGF.getContext().getCanonicalType(SrcType);
549 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +0000550 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +0000551
Chris Lattner08c611e2007-08-26 07:21:11 +0000552 if (DstType->isVoidType()) return 0;
Mike Stump4a3999f2009-09-09 13:00:44 +0000553
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000554 llvm::Type *SrcTy = Src->getType();
555
556 // Floating casts might be a bit special: if we're doing casts to / from half
557 // FP, we should go via special intrinsics.
558 if (SrcType->isHalfType()) {
559 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
560 SrcType = CGF.getContext().FloatTy;
Chris Lattnerece04092012-02-07 00:39:47 +0000561 SrcTy = CGF.FloatTy;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000562 }
563
Chris Lattner3474c202007-08-26 06:48:56 +0000564 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000565 if (DstType->isBooleanType())
566 return EmitConversionToBool(Src, SrcType);
Mike Stump4a3999f2009-09-09 13:00:44 +0000567
Chris Lattner2192fe52011-07-18 04:24:23 +0000568 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +0000569
570 // Ignore conversions like int -> uint.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000571 if (SrcTy == DstTy)
Chris Lattner3474c202007-08-26 06:48:56 +0000572 return Src;
573
Mike Stump4a3999f2009-09-09 13:00:44 +0000574 // Handle pointer conversions next: pointers can only be converted to/from
575 // other pointers and integers. Check for pointer types in terms of LLVM, as
576 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar427f8732008-08-25 09:51:32 +0000577 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000578 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000579 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +0000580 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +0000581
Chris Lattner3474c202007-08-26 06:48:56 +0000582 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000583 // First, convert to the correct width so that we control the kind of
584 // extension.
Chris Lattner2192fe52011-07-18 04:24:23 +0000585 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000586 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000587 llvm::Value* IntResult =
588 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
589 // Then, cast to pointer.
590 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000591 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000592
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000593 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000594 // Must be an ptr to int cast.
595 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +0000596 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000597 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000598
Nate Begemance4d7fc2008-04-18 23:10:10 +0000599 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +0000600 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begemanb699c9b2009-01-18 06:42:49 +0000601 // Cast the scalar to element type
John McCall9dd450b2009-09-21 23:43:11 +0000602 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begemanb699c9b2009-01-18 06:42:49 +0000603 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
604
605 // Insert the element in element zero of an undef vector
Owen Anderson7ec07a52009-07-30 23:11:26 +0000606 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner2531eb42011-04-19 22:55:03 +0000607 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000608 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begemanb699c9b2009-01-18 06:42:49 +0000609
610 // Splat the element across to all elements
Nate Begemanb699c9b2009-01-18 06:42:49 +0000611 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2d6b7b92012-01-25 05:34:41 +0000612 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
613 Builder.getInt32(0));
Nate Begemanb699c9b2009-01-18 06:42:49 +0000614 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
615 return Yay;
616 }
Nate Begeman330aaa72007-12-30 02:59:45 +0000617
Chris Lattner6cba8e92008-02-02 04:51:41 +0000618 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000619 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner6cba8e92008-02-02 04:51:41 +0000620 isa<llvm::VectorType>(DstTy))
Anders Carlssona297e7a2007-12-05 07:36:10 +0000621 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stump4a3999f2009-09-09 13:00:44 +0000622
Chris Lattner3474c202007-08-26 06:48:56 +0000623 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000624 Value *Res = NULL;
625 llvm::Type *ResTy = DstTy;
626
627 // Cast to half via float
628 if (DstType->isHalfType())
Chris Lattnerece04092012-02-07 00:39:47 +0000629 DstTy = CGF.FloatTy;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000630
631 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000632 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000633 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000634 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000635 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000636 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000637 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000638 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
639 } else if (isa<llvm::IntegerType>(DstTy)) {
640 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000641 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000642 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000643 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000644 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
645 } else {
646 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
647 "Unknown real conversion");
648 if (DstTy->getTypeID() < SrcTy->getTypeID())
649 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
650 else
651 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000652 }
653
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000654 if (DstTy != ResTy) {
655 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
656 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
657 }
658
659 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +0000660}
661
Mike Stump4a3999f2009-09-09 13:00:44 +0000662/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
663/// type to the specified destination type, where the destination type is an
664/// LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000665Value *ScalarExprEmitter::
666EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
667 QualType SrcTy, QualType DstTy) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000668 // Get the source element type.
John McCall9dd450b2009-09-21 23:43:11 +0000669 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +0000670
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000671 // Handle conversions to bool first, they are special: comparisons against 0.
672 if (DstTy->isBooleanType()) {
673 // Complex != 0 -> (Real != 0) | (Imag != 0)
674 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
675 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
676 return Builder.CreateOr(Src.first, Src.second, "tobool");
677 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000678
Chris Lattner42e6b812007-08-26 16:34:22 +0000679 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
680 // the imaginary part of the complex value is discarded and the value of the
681 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +0000682 // corresponding real type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000683 return EmitScalarConversion(Src.first, SrcTy, DstTy);
684}
685
Anders Carlsson5b944432010-05-22 17:45:10 +0000686Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall7a9aac22010-08-23 01:21:21 +0000687 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
688 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
689
690 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlsson5b944432010-05-22 17:45:10 +0000691}
Chris Lattner42e6b812007-08-26 16:34:22 +0000692
Chris Lattner2da04b32007-08-24 05:35:26 +0000693//===----------------------------------------------------------------------===//
694// Visitor Methods
695//===----------------------------------------------------------------------===//
696
697Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000698 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +0000699 if (E->getType()->isVoidType())
700 return 0;
Owen Anderson7ec07a52009-07-30 23:11:26 +0000701 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +0000702}
703
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000704Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +0000705 // Vector Mask Case
706 if (E->getNumSubExprs() == 2 ||
Rafael Espindola9cdbd9d2010-06-09 02:17:08 +0000707 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner5e016ae2010-06-27 07:15:29 +0000708 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
709 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
710 Value *Mask;
Nate Begemana0110022010-06-08 00:16:34 +0000711
Chris Lattner2192fe52011-07-18 04:24:23 +0000712 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +0000713 unsigned LHSElts = LTy->getNumElements();
714
715 if (E->getNumSubExprs() == 3) {
716 Mask = CGF.EmitScalarExpr(E->getExpr(2));
717
718 // Shuffle LHS & RHS into one input vector.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000719 SmallVector<llvm::Constant*, 32> concat;
Nate Begemana0110022010-06-08 00:16:34 +0000720 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000721 concat.push_back(Builder.getInt32(2*i));
722 concat.push_back(Builder.getInt32(2*i+1));
Nate Begemana0110022010-06-08 00:16:34 +0000723 }
724
Chris Lattner91c08ad2011-02-15 00:14:06 +0000725 Value* CV = llvm::ConstantVector::get(concat);
Nate Begemana0110022010-06-08 00:16:34 +0000726 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
727 LHSElts *= 2;
728 } else {
729 Mask = RHS;
730 }
731
Chris Lattner2192fe52011-07-18 04:24:23 +0000732 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begemana0110022010-06-08 00:16:34 +0000733 llvm::Constant* EltMask;
734
735 // Treat vec3 like vec4.
736 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
737 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
738 (1 << llvm::Log2_32(LHSElts+2))-1);
739 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
740 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
741 (1 << llvm::Log2_32(LHSElts+1))-1);
742 else
743 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
744 (1 << llvm::Log2_32(LHSElts))-1);
745
746 // Mask off the high bits of each shuffle index.
Chris Lattner2d6b7b92012-01-25 05:34:41 +0000747 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
748 EltMask);
Nate Begemana0110022010-06-08 00:16:34 +0000749 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
750
751 // newv = undef
752 // mask = mask & maskbits
753 // for each elt
754 // n = extract mask i
755 // x = extract val n
756 // newv = insert newv, x, i
Chris Lattner2192fe52011-07-18 04:24:23 +0000757 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begemana0110022010-06-08 00:16:34 +0000758 MTy->getNumElements());
759 Value* NewV = llvm::UndefValue::get(RTy);
760 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman1fa36052012-04-05 21:48:40 +0000761 Value *IIndx = Builder.getInt32(i);
762 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner5e016ae2010-06-27 07:15:29 +0000763 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begemana0110022010-06-08 00:16:34 +0000764
765 // Handle vec3 special since the index will be off by one for the RHS.
766 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
767 Value *cmpIndx, *newIndx;
Chris Lattner2531eb42011-04-19 22:55:03 +0000768 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begemana0110022010-06-08 00:16:34 +0000769 "cmp_shuf_idx");
Chris Lattner2531eb42011-04-19 22:55:03 +0000770 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begemana0110022010-06-08 00:16:34 +0000771 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
772 }
773 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +0000774 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +0000775 }
776 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000777 }
Nate Begemana0110022010-06-08 00:16:34 +0000778
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000779 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
780 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begemana0110022010-06-08 00:16:34 +0000781
782 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2192fe52011-07-18 04:24:23 +0000783 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000784 SmallVector<llvm::Constant*, 32> indices;
Nate Begemana0110022010-06-08 00:16:34 +0000785 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman2f1e9e62011-05-19 00:37:32 +0000786 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
787 if (VTy->getNumElements() == 3 && Idx > 3)
788 Idx -= 1;
789 indices.push_back(Builder.getInt32(Idx));
Nate Begemana0110022010-06-08 00:16:34 +0000790 }
791
Chris Lattner91c08ad2011-02-15 00:14:06 +0000792 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000793 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
794}
Eli Friedmancb422f12009-11-26 03:22:21 +0000795Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith5fab0c92011-12-28 19:48:30 +0000796 llvm::APSInt Value;
797 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedmancb422f12009-11-26 03:22:21 +0000798 if (E->isArrow())
799 CGF.EmitScalarExpr(E->getBase());
800 else
801 EmitLValue(E->getBase());
Richard Smith5fab0c92011-12-28 19:48:30 +0000802 return Builder.getInt(Value);
Eli Friedmancb422f12009-11-26 03:22:21 +0000803 }
Devang Patel44b8bf02010-10-04 21:46:04 +0000804
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000805 // Emit debug info for aggregate now, if it was delayed to reduce
Devang Patel44b8bf02010-10-04 21:46:04 +0000806 // debug info size.
807 CGDebugInfo *DI = CGF.getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000808 if (DI &&
809 CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
Devang Patel44b8bf02010-10-04 21:46:04 +0000810 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
811 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel3703ff42010-10-04 22:28:23 +0000812 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000813 DI->getOrCreateRecordType(PTy->getPointeeType(),
Devang Patel44b8bf02010-10-04 21:46:04 +0000814 M->getParent()->getLocation());
Devang Patel95eea452010-10-04 22:13:18 +0000815 }
Eli Friedmancb422f12009-11-26 03:22:21 +0000816 return EmitLoadOfLValue(E);
817}
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000818
Chris Lattner2da04b32007-08-24 05:35:26 +0000819Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000820 TestAndClearIgnoreResultAssign();
821
Chris Lattner2da04b32007-08-24 05:35:26 +0000822 // Emit subscript expressions in rvalue context's. For most cases, this just
823 // loads the lvalue formed by the subscript expr. However, we have to be
824 // careful, because the base of a vector subscript is occasionally an rvalue,
825 // so we can't get it as an lvalue.
826 if (!E->getBase()->getType()->isVectorType())
827 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000828
Chris Lattner2da04b32007-08-24 05:35:26 +0000829 // Handle the vector case. The base must be a vector, the index must be an
830 // integer value.
831 Value *Base = Visit(E->getBase());
832 Value *Idx = Visit(E->getIdx());
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000833 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner5e016ae2010-06-27 07:15:29 +0000834 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner2da04b32007-08-24 05:35:26 +0000835 return Builder.CreateExtractElement(Base, Idx, "vecext");
836}
837
Nate Begeman19351632009-10-18 20:10:40 +0000838static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +0000839 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +0000840 int MV = SVI->getMaskValue(Idx);
841 if (MV == -1)
842 return llvm::UndefValue::get(I32Ty);
843 return llvm::ConstantInt::get(I32Ty, Off+MV);
844}
845
846Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
847 bool Ignore = TestAndClearIgnoreResultAssign();
848 (void)Ignore;
849 assert (Ignore == false && "init list ignored");
850 unsigned NumInitElements = E->getNumInits();
851
852 if (E->hadArrayRangeDesignator())
853 CGF.ErrorUnsupported(E, "GNU array range designator extension");
854
Chris Lattner2192fe52011-07-18 04:24:23 +0000855 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +0000856 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
857
Sebastian Redl12757ab2011-09-24 17:48:14 +0000858 if (!VType) {
859 if (NumInitElements == 0) {
860 // C++11 value-initialization for the scalar.
861 return EmitNullValue(E->getType());
862 }
863 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +0000864 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +0000865 }
Nate Begeman19351632009-10-18 20:10:40 +0000866
867 unsigned ResElts = VType->getNumElements();
Nate Begeman19351632009-10-18 20:10:40 +0000868
869 // Loop over initializers collecting the Value for each, and remembering
870 // whether the source was swizzle (ExtVectorElementExpr). This will allow
871 // us to fold the shuffle for the swizzle into the shuffle for the vector
872 // initializer, since LLVM optimizers generally do not want to touch
873 // shuffles.
874 unsigned CurIdx = 0;
875 bool VIsUndefShuffle = false;
876 llvm::Value *V = llvm::UndefValue::get(VType);
877 for (unsigned i = 0; i != NumInitElements; ++i) {
878 Expr *IE = E->getInit(i);
879 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000880 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman19351632009-10-18 20:10:40 +0000881
Chris Lattner2192fe52011-07-18 04:24:23 +0000882 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman19351632009-10-18 20:10:40 +0000883
884 // Handle scalar elements. If the scalar initializer is actually one
885 // element of a different vector of the same width, use shuffle instead of
886 // extract+insert.
887 if (!VVT) {
888 if (isa<ExtVectorElementExpr>(IE)) {
889 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
890
891 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
892 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
893 Value *LHS = 0, *RHS = 0;
894 if (CurIdx == 0) {
895 // insert into undef -> shuffle (src, undef)
896 Args.push_back(C);
Benjamin Kramer8001f742012-02-14 12:06:21 +0000897 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +0000898
899 LHS = EI->getVectorOperand();
900 RHS = V;
901 VIsUndefShuffle = true;
902 } else if (VIsUndefShuffle) {
903 // insert into undefshuffle && size match -> shuffle (v, src)
904 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
905 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +0000906 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +0000907 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +0000908 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
909
Nate Begeman19351632009-10-18 20:10:40 +0000910 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
911 RHS = EI->getVectorOperand();
912 VIsUndefShuffle = false;
913 }
914 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +0000915 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +0000916 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
917 ++CurIdx;
918 continue;
919 }
920 }
921 }
Chris Lattner2531eb42011-04-19 22:55:03 +0000922 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
923 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +0000924 VIsUndefShuffle = false;
925 ++CurIdx;
926 continue;
927 }
928
929 unsigned InitElts = VVT->getNumElements();
930
931 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
932 // input is the same width as the vector being constructed, generate an
933 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +0000934 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +0000935 if (isa<ExtVectorElementExpr>(IE)) {
936 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
937 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +0000938 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman19351632009-10-18 20:10:40 +0000939
940 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +0000941 for (unsigned j = 0; j != CurIdx; ++j) {
942 // If the current vector initializer is a shuffle with undef, merge
943 // this shuffle directly into it.
944 if (VIsUndefShuffle) {
945 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +0000946 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +0000947 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +0000948 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +0000949 }
950 }
951 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +0000952 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +0000953 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +0000954
955 if (VIsUndefShuffle)
956 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
957
958 Init = SVOp;
959 }
960 }
961
962 // Extend init to result vector length, and then shuffle its contribution
963 // to the vector initializer into V.
964 if (Args.empty()) {
965 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +0000966 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +0000967 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +0000968 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +0000969 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +0000970 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +0000971
972 Args.clear();
973 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +0000974 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +0000975 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +0000976 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +0000977 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +0000978 }
979
980 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
981 // merging subsequent shuffles into this one.
982 if (CurIdx == 0)
983 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +0000984 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +0000985 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
986 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
987 CurIdx += InitElts;
988 }
989
990 // FIXME: evaluate codegen vs. shuffling against constant null vector.
991 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +0000992 llvm::Type *EltTy = VType->getElementType();
Nate Begeman19351632009-10-18 20:10:40 +0000993
994 // Emit remaining default initializers
995 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000996 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +0000997 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
998 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
999 }
1000 return V;
1001}
1002
Anders Carlsson8c793172009-11-23 17:57:54 +00001003static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1004 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001005
John McCalle3027922010-08-25 11:45:40 +00001006 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001007 return false;
Anders Carlsson8c793172009-11-23 17:57:54 +00001008
1009 if (isa<CXXThisExpr>(E)) {
1010 // We always assume that 'this' is never null.
1011 return false;
1012 }
1013
1014 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001015 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001016 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001017 return false;
1018 }
1019
1020 return true;
1021}
1022
Chris Lattner2da04b32007-08-24 05:35:26 +00001023// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1024// have to handle a more broad range of conversions than explicit casts, as they
1025// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001026Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001027 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001028 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001029 CastKind Kind = CE->getCastKind();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001030
Mike Stumpdf0fe272009-05-29 15:46:01 +00001031 if (!DestTy->isVoidType())
1032 TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001033
Eli Friedman0dfc6802009-11-27 02:07:44 +00001034 // Since almost all cast kinds apply to scalars, this switch doesn't have
1035 // a default case, so the compiler will warn on a missing case. The cases
1036 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001037 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001038 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001039 case CK_BuiltinFnToFnPtr:
1040 llvm_unreachable("builtin functions are handled elsewhere");
1041
John McCalle3027922010-08-25 11:45:40 +00001042 case CK_LValueBitCast:
1043 case CK_ObjCObjectLValueCast: {
Douglas Gregor51954272010-07-13 23:17:26 +00001044 Value *V = EmitLValue(E).getAddress();
1045 V = Builder.CreateBitCast(V,
1046 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedman3184a5e2011-12-19 23:03:09 +00001047 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregor51954272010-07-13 23:17:26 +00001048 }
John McCallcd78e802011-09-10 01:16:55 +00001049
John McCall9320b872011-09-09 05:25:32 +00001050 case CK_CPointerToObjCPointerCast:
1051 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001052 case CK_AnyPointerToBlockPointerCast:
1053 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001054 Value *Src = Visit(const_cast<Expr*>(E));
1055 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1056 }
David Chisnallfa35df62012-01-16 17:27:18 +00001057 case CK_AtomicToNonAtomic:
1058 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00001059 case CK_NoOp:
1060 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001061 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001062
John McCalle3027922010-08-25 11:45:40 +00001063 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00001064 const CXXRecordDecl *DerivedClassDecl =
1065 DestTy->getCXXRecordDeclForPointerType();
1066
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00001067 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00001068 CE->path_begin(), CE->path_end(),
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00001069 ShouldNullCheckClassCastValue(CE));
Anders Carlsson8c793172009-11-23 17:57:54 +00001070 }
John McCalle3027922010-08-25 11:45:40 +00001071 case CK_UncheckedDerivedToBase:
1072 case CK_DerivedToBase: {
Anders Carlsson12f5a252009-09-12 04:57:16 +00001073 const RecordType *DerivedClassTy =
1074 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1075 CXXRecordDecl *DerivedClassDecl =
1076 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1077
Anders Carlssond829a022010-04-24 21:06:20 +00001078 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00001079 CE->path_begin(), CE->path_end(),
Anders Carlssond829a022010-04-24 21:06:20 +00001080 ShouldNullCheckClassCastValue(CE));
Anders Carlsson12f5a252009-09-12 04:57:16 +00001081 }
Anders Carlsson8a01a752011-04-11 02:03:26 +00001082 case CK_Dynamic: {
Eli Friedman0dfc6802009-11-27 02:07:44 +00001083 Value *V = Visit(const_cast<Expr*>(E));
1084 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1085 return CGF.EmitDynamicCast(V, DCE);
1086 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00001087
John McCalle3027922010-08-25 11:45:40 +00001088 case CK_ArrayToPointerDecay: {
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001089 assert(E->getType()->isArrayType() &&
1090 "Array to pointer decay must have array source type!");
1091
1092 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1093
1094 // Note that VLA pointers are always decayed, so we don't need to do
1095 // anything here.
1096 if (!E->getType()->isVariableArrayType()) {
1097 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1098 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1099 ->getElementType()) &&
1100 "Expected pointer to array");
1101 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1102 }
1103
Chris Lattner71bd0c32011-07-20 04:31:01 +00001104 // Make sure the array decay ends up being the right type. This matters if
1105 // the array type was of an incomplete type.
Chris Lattner24516962011-07-20 04:59:57 +00001106 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001107 }
John McCalle3027922010-08-25 11:45:40 +00001108 case CK_FunctionToPointerDecay:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001109 return EmitLValue(E).getAddress();
1110
John McCalle84af4e2010-11-13 01:35:44 +00001111 case CK_NullToPointer:
1112 if (MustVisitNullValue(E))
1113 (void) Visit(E);
1114
1115 return llvm::ConstantPointerNull::get(
1116 cast<llvm::PointerType>(ConvertType(DestTy)));
1117
John McCalle3027922010-08-25 11:45:40 +00001118 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00001119 if (MustVisitNullValue(E))
John McCalla1dee5302010-08-22 10:59:02 +00001120 (void) Visit(E);
1121
John McCall7a9aac22010-08-23 01:21:21 +00001122 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1123 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1124 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00001125
John McCallc62bb392012-02-15 01:22:51 +00001126 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00001127 case CK_BaseToDerivedMemberPointer:
1128 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001129 Value *Src = Visit(E);
John McCalla1dee5302010-08-22 10:59:02 +00001130
1131 // Note that the AST doesn't distinguish between checked and
1132 // unchecked member pointer conversions, so we always have to
1133 // implement checked conversions here. This is inefficient when
1134 // actual control flow may be required in order to perform the
1135 // check, which it is for data member pointers (but not member
1136 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00001137 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00001138 }
John McCall31168b02011-06-15 23:02:42 +00001139
John McCall2d637d22011-09-10 06:18:15 +00001140 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00001141 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00001142 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00001143 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall2d637d22011-09-10 06:18:15 +00001144 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00001145 llvm::Value *value = Visit(E);
1146 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1147 return CGF.EmitObjCConsumeObject(E->getType(), value);
1148 }
John McCallff613032011-10-04 06:23:45 +00001149 case CK_ARCExtendBlockObject:
1150 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00001151
Douglas Gregored90df32012-02-22 05:02:47 +00001152 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00001153 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregored90df32012-02-22 05:02:47 +00001154
John McCallc5e62b42010-11-13 09:02:35 +00001155 case CK_FloatingRealToComplex:
1156 case CK_FloatingComplexCast:
1157 case CK_IntegralRealToComplex:
1158 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00001159 case CK_IntegralComplexToFloatingComplex:
1160 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00001161 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00001162 case CK_ToUnion:
1163 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00001164
John McCallf3735e02010-12-01 04:43:34 +00001165 case CK_LValueToRValue:
1166 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00001167 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00001168 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00001169
John McCalle3027922010-08-25 11:45:40 +00001170 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001171 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001172
Anders Carlsson094c4592009-10-18 18:12:03 +00001173 // First, convert to the correct width so that we control the kind of
1174 // extension.
Chris Lattner2192fe52011-07-18 04:24:23 +00001175 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001176 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00001177 llvm::Value* IntResult =
1178 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001179
Anders Carlsson094c4592009-10-18 18:12:03 +00001180 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001181 }
Eli Friedman58368522011-06-25 02:58:47 +00001182 case CK_PointerToIntegral:
1183 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1184 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001185
John McCalle3027922010-08-25 11:45:40 +00001186 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00001187 CGF.EmitIgnoredExpr(E);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001188 return 0;
1189 }
John McCalle3027922010-08-25 11:45:40 +00001190 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00001191 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001192 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5b5935d2012-02-06 05:05:50 +00001193 Elt = EmitScalarConversion(Elt, E->getType(),
1194 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001195
1196 // Insert the element in element zero of an undef vector
1197 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner2531eb42011-04-19 22:55:03 +00001198 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001199 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001200
1201 // Splat the element across to all elements
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001202 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2531eb42011-04-19 22:55:03 +00001203 llvm::Constant *Zero = Builder.getInt32(0);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001204 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001205 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1206 return Yay;
1207 }
John McCall8cb679e2010-11-15 09:13:47 +00001208
John McCalle3027922010-08-25 11:45:40 +00001209 case CK_IntegralCast:
1210 case CK_IntegralToFloating:
1211 case CK_FloatingToIntegral:
1212 case CK_FloatingCast:
Eli Friedmane96f1d32009-11-27 04:41:50 +00001213 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCall8cb679e2010-11-15 09:13:47 +00001214 case CK_IntegralToBoolean:
1215 return EmitIntToBoolConversion(Visit(E));
1216 case CK_PointerToBoolean:
1217 return EmitPointerToBoolConversion(Visit(E));
1218 case CK_FloatingToBoolean:
1219 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00001220 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00001221 llvm::Value *MemPtr = Visit(E);
1222 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1223 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001224 }
John McCalld7646252010-11-14 08:17:51 +00001225
1226 case CK_FloatingComplexToReal:
1227 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00001228 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00001229
1230 case CK_FloatingComplexToBoolean:
1231 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00001232 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00001233
1234 // TODO: kill this function off, inline appropriate case here
1235 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1236 }
1237
John McCall7a9aac22010-08-23 01:21:21 +00001238 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001239
John McCall3eba6e62010-11-16 06:21:14 +00001240 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00001241}
1242
Chris Lattner04a913b2007-08-31 22:09:40 +00001243Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00001244 CodeGenFunction::StmtExprEvaluation eval(CGF);
1245 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1246 .getScalarVal();
Chris Lattner04a913b2007-08-31 22:09:40 +00001247}
1248
Chris Lattner2da04b32007-08-24 05:35:26 +00001249//===----------------------------------------------------------------------===//
1250// Unary Operators
1251//===----------------------------------------------------------------------===//
1252
Chris Lattner05dc78c2010-06-26 22:09:34 +00001253llvm::Value *ScalarExprEmitter::
Anton Yartsev85129b82011-02-07 02:17:30 +00001254EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1255 llvm::Value *InVal,
1256 llvm::Value *NextVal, bool IsInc) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001257 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00001258 case LangOptions::SOB_Defined:
1259 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith3e056de2012-08-25 00:32:28 +00001260 case LangOptions::SOB_Undefined:
1261 if (!CGF.CatchUndefined)
1262 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1263 // Fall through.
Anton Yartsev85129b82011-02-07 02:17:30 +00001264 case LangOptions::SOB_Trapping:
1265 BinOpInfo BinOp;
1266 BinOp.LHS = InVal;
1267 BinOp.RHS = NextVal;
1268 BinOp.Ty = E->getType();
1269 BinOp.Opcode = BO_Add;
1270 BinOp.E = E;
1271 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev85129b82011-02-07 02:17:30 +00001272 }
David Blaikie83d382b2011-09-23 05:06:16 +00001273 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00001274}
1275
John McCalle3dc1702011-02-15 09:22:45 +00001276llvm::Value *
1277ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1278 bool isInc, bool isPre) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00001279
John McCalle3dc1702011-02-15 09:22:45 +00001280 QualType type = E->getSubExpr()->getType();
John McCall55e1fbc2011-06-25 02:11:03 +00001281 llvm::Value *value = EmitLoadOfLValue(LV);
John McCalle3dc1702011-02-15 09:22:45 +00001282 llvm::Value *input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00001283 llvm::PHINode *atomicPHI = 0;
Anton Yartsev85129b82011-02-07 02:17:30 +00001284
John McCalle3dc1702011-02-15 09:22:45 +00001285 int amount = (isInc ? 1 : -1);
1286
David Chisnallfa35df62012-01-16 17:27:18 +00001287 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1288 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1289 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1290 Builder.CreateBr(opBB);
1291 Builder.SetInsertPoint(opBB);
1292 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1293 atomicPHI->addIncoming(value, startBB);
1294 type = atomicTy->getValueType();
1295 value = atomicPHI;
1296 }
1297
John McCalle3dc1702011-02-15 09:22:45 +00001298 // Special case of integer increment that we have to check first: bool++.
1299 // Due to promotion rules, we get:
1300 // bool++ -> bool = bool + 1
1301 // -> bool = (int)bool + 1
1302 // -> bool = ((int)bool + 1 != 0)
1303 // An interesting aspect of this is that increment is always true.
1304 // Decrement does not have this property.
1305 if (isInc && type->isBooleanType()) {
1306 value = Builder.getTrue();
1307
1308 // Most common case by far: integer increment.
1309 } else if (type->isIntegerType()) {
1310
Michael Liao48f498f2012-08-28 16:55:13 +00001311 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00001312
Eli Friedman846ded22011-03-02 01:49:12 +00001313 // Note that signed integer inc/dec with width less than int can't
1314 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001315 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedman846ded22011-03-02 01:49:12 +00001316 value->getType()->getPrimitiveSizeInBits() >=
John McCall77527a82011-06-25 01:32:37 +00001317 CGF.IntTy->getBitWidth())
John McCalle3dc1702011-02-15 09:22:45 +00001318 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCalle3dc1702011-02-15 09:22:45 +00001319 else
1320 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1321
1322 // Next most common: pointer increment.
1323 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1324 QualType type = ptr->getPointeeType();
1325
1326 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00001327 if (const VariableArrayType *vla
1328 = CGF.getContext().getAsVariableArrayType(type)) {
1329 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCall23c29fe2011-06-24 21:55:10 +00001330 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00001332 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00001333 else
John McCall23c29fe2011-06-24 21:55:10 +00001334 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCalle3dc1702011-02-15 09:22:45 +00001335
1336 // Arithmetic on function pointers (!) is just +-1.
1337 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001338 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00001339
1340 value = CGF.EmitCastToVoidPtr(value);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001341 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001342 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1343 else
1344 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00001345 value = Builder.CreateBitCast(value, input->getType());
1346
1347 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00001348 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001349 llvm::Value *amt = Builder.getInt32(amount);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001350 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001351 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1352 else
1353 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00001354 }
1355
1356 // Vector increment/decrement.
1357 } else if (type->isVectorType()) {
1358 if (type->hasIntegerRepresentation()) {
1359 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1360
Eli Friedman409943e2011-05-06 18:04:18 +00001361 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00001362 } else {
1363 value = Builder.CreateFAdd(
1364 value,
1365 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00001366 isInc ? "inc" : "dec");
1367 }
Anton Yartsev85129b82011-02-07 02:17:30 +00001368
John McCalle3dc1702011-02-15 09:22:45 +00001369 // Floating point.
1370 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00001371 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00001372 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001373
1374 if (type->isHalfType()) {
1375 // Another special case: half FP increment should be done via float
1376 value =
1377 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1378 input);
1379 }
1380
John McCalle3dc1702011-02-15 09:22:45 +00001381 if (value->getType()->isFloatTy())
1382 amt = llvm::ConstantFP::get(VMContext,
1383 llvm::APFloat(static_cast<float>(amount)));
1384 else if (value->getType()->isDoubleTy())
1385 amt = llvm::ConstantFP::get(VMContext,
1386 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001387 else {
John McCalle3dc1702011-02-15 09:22:45 +00001388 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001389 bool ignored;
1390 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1391 &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00001392 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001393 }
John McCalle3dc1702011-02-15 09:22:45 +00001394 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1395
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001396 if (type->isHalfType())
1397 value =
1398 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1399 value);
1400
John McCalle3dc1702011-02-15 09:22:45 +00001401 // Objective-C pointer types.
1402 } else {
1403 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1404 value = CGF.EmitCastToVoidPtr(value);
1405
1406 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1407 if (!isInc) size = -size;
1408 llvm::Value *sizeValue =
1409 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1410
David Blaikiebbafb8a2012-03-11 07:00:24 +00001411 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001412 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1413 else
1414 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00001415 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00001416 }
David Chisnallfa35df62012-01-16 17:27:18 +00001417
1418 if (atomicPHI) {
1419 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1420 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1421 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1422 value, llvm::SequentiallyConsistent);
1423 atomicPHI->addIncoming(old, opBB);
1424 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1425 Builder.CreateCondBr(success, contBB, opBB);
1426 Builder.SetInsertPoint(contBB);
1427 return isPre ? value : input;
1428 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001429
Chris Lattner05dc78c2010-06-26 22:09:34 +00001430 // Store the updated result through the lvalue.
1431 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00001432 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001433 else
John McCall55e1fbc2011-06-25 02:11:03 +00001434 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001435
Chris Lattner05dc78c2010-06-26 22:09:34 +00001436 // If this is a postinc, return the value read from memory, otherwise use the
1437 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00001438 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00001439}
1440
1441
1442
Chris Lattner2da04b32007-08-24 05:35:26 +00001443Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001444 TestAndClearIgnoreResultAssign();
Chris Lattner0bf27622010-06-26 21:48:21 +00001445 // Emit unary minus with EmitSub so we handle overflow cases etc.
1446 BinOpInfo BinOp;
Chris Lattnerc1028f62010-06-28 17:12:37 +00001447 BinOp.RHS = Visit(E->getSubExpr());
1448
1449 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1450 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1451 else
1452 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00001453 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00001454 BinOp.Opcode = BO_Sub;
Chris Lattner0bf27622010-06-26 21:48:21 +00001455 BinOp.E = E;
1456 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00001457}
1458
1459Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001460 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00001461 Value *Op = Visit(E->getSubExpr());
1462 return Builder.CreateNot(Op, "neg");
1463}
1464
1465Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00001466
1467 // Perform vector logical not on comparison with zero vector.
1468 if (E->getType()->isExtVectorType()) {
1469 Value *Oper = Visit(E->getSubExpr());
1470 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1471 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1472 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1473 }
1474
Chris Lattner2da04b32007-08-24 05:35:26 +00001475 // Compare operand to zero.
1476 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001477
Chris Lattner2da04b32007-08-24 05:35:26 +00001478 // Invert value.
1479 // TODO: Could dynamically modify easy computations here. For example, if
1480 // the operand is an icmp ne, turn into icmp eq.
1481 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00001482
Anders Carlsson775640d2009-05-19 18:44:53 +00001483 // ZExt result to the expr type.
1484 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00001485}
1486
Eli Friedmand7c72322010-08-05 09:58:49 +00001487Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1488 // Try folding the offsetof to a constant.
Richard Smith5fab0c92011-12-28 19:48:30 +00001489 llvm::APSInt Value;
1490 if (E->EvaluateAsInt(Value, CGF.getContext()))
1491 return Builder.getInt(Value);
Eli Friedmand7c72322010-08-05 09:58:49 +00001492
1493 // Loop over the components of the offsetof to compute the value.
1494 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00001495 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00001496 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1497 QualType CurrentType = E->getTypeSourceInfo()->getType();
1498 for (unsigned i = 0; i != n; ++i) {
1499 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman165301d2010-08-06 16:37:05 +00001500 llvm::Value *Offset = 0;
Eli Friedmand7c72322010-08-05 09:58:49 +00001501 switch (ON.getKind()) {
1502 case OffsetOfExpr::OffsetOfNode::Array: {
1503 // Compute the index
1504 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1505 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001506 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00001507 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1508
1509 // Save the element type
1510 CurrentType =
1511 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1512
1513 // Compute the element size
1514 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1515 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1516
1517 // Multiply out to compute the result
1518 Offset = Builder.CreateMul(Idx, ElemSize);
1519 break;
1520 }
1521
1522 case OffsetOfExpr::OffsetOfNode::Field: {
1523 FieldDecl *MemberDecl = ON.getField();
1524 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1525 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1526
1527 // Compute the index of the field in its parent.
1528 unsigned i = 0;
1529 // FIXME: It would be nice if we didn't have to loop here!
1530 for (RecordDecl::field_iterator Field = RD->field_begin(),
1531 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00001532 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00001533 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00001534 break;
1535 }
1536 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1537
1538 // Compute the offset to the field
1539 int64_t OffsetInt = RL.getFieldOffset(i) /
1540 CGF.getContext().getCharWidth();
1541 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1542
1543 // Save the element type.
1544 CurrentType = MemberDecl->getType();
1545 break;
1546 }
Eli Friedman165301d2010-08-06 16:37:05 +00001547
Eli Friedmand7c72322010-08-05 09:58:49 +00001548 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00001549 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00001550
Eli Friedmand7c72322010-08-05 09:58:49 +00001551 case OffsetOfExpr::OffsetOfNode::Base: {
1552 if (ON.getBase()->isVirtual()) {
1553 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1554 continue;
1555 }
1556
1557 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1558 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1559
1560 // Save the element type.
1561 CurrentType = ON.getBase()->getType();
1562
1563 // Compute the offset to the base.
1564 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1565 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001566 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1567 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00001568 break;
1569 }
1570 }
1571 Result = Builder.CreateAdd(Result, Offset);
1572 }
1573 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00001574}
1575
Peter Collingbournee190dee2011-03-11 19:24:49 +00001576/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00001577/// argument of the sizeof expression as an integer.
1578Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00001579ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1580 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00001581 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00001582 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001583 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001584 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1585 if (E->isArgumentType()) {
1586 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00001587 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00001588 } else {
1589 // C99 6.5.3.4p2: If the argument is an expression of type
1590 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00001591 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001592 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001593
John McCall23c29fe2011-06-24 21:55:10 +00001594 QualType eltType;
1595 llvm::Value *numElts;
1596 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1597
1598 llvm::Value *size = numElts;
1599
1600 // Scale the number of non-VLA elements by the non-VLA element size.
1601 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1602 if (!eltSize.isOne())
1603 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1604
1605 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00001606 }
Anders Carlsson30032882008-12-12 07:38:43 +00001607 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001608
Mike Stump4a3999f2009-09-09 13:00:44 +00001609 // If this isn't sizeof(vla), the result must be constant; use the constant
1610 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00001611 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00001612}
1613
Chris Lattner9f0ad962007-08-24 21:20:17 +00001614Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1615 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00001616 if (Op->getType()->isAnyComplexType()) {
1617 // If it's an l-value, load through the appropriate subobject l-value.
1618 // Note that we have to ask E because Op might be an l-value that
1619 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00001620 if (E->isGLValue())
John McCall55e1fbc2011-06-25 02:11:03 +00001621 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00001622
1623 // Otherwise, calculate and project.
1624 return CGF.EmitComplexExpr(Op, false, true).first;
1625 }
1626
Chris Lattner9f0ad962007-08-24 21:20:17 +00001627 return Visit(Op);
1628}
John McCall07bb1962010-11-16 10:08:07 +00001629
Chris Lattner9f0ad962007-08-24 21:20:17 +00001630Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1631 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00001632 if (Op->getType()->isAnyComplexType()) {
1633 // If it's an l-value, load through the appropriate subobject l-value.
1634 // Note that we have to ask E because Op might be an l-value that
1635 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00001636 if (Op->isGLValue())
John McCall55e1fbc2011-06-25 02:11:03 +00001637 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00001638
1639 // Otherwise, calculate and project.
1640 return CGF.EmitComplexExpr(Op, true, false).second;
1641 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001642
Mike Stumpdf0fe272009-05-29 15:46:01 +00001643 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1644 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00001645 if (Op->isGLValue())
1646 CGF.EmitLValue(Op);
1647 else
1648 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00001649 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00001650}
1651
Chris Lattner2da04b32007-08-24 05:35:26 +00001652//===----------------------------------------------------------------------===//
1653// Binary Operators
1654//===----------------------------------------------------------------------===//
1655
1656BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001657 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00001658 BinOpInfo Result;
1659 Result.LHS = Visit(E->getLHS());
1660 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00001661 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00001662 Result.Opcode = E->getOpcode();
Chris Lattner2da04b32007-08-24 05:35:26 +00001663 Result.E = E;
1664 return Result;
1665}
1666
Douglas Gregor914af212010-04-23 04:16:32 +00001667LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1668 const CompoundAssignOperator *E,
1669 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001670 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00001671 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00001672 BinOpInfo OpInfo;
Douglas Gregor914af212010-04-23 04:16:32 +00001673
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001674 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001675 // This needs to go through the complex expression emitter, but it's a tad
1676 // complicated to do that... I'm leaving it out for now. (Note that we do
1677 // actually need the imaginary part of the RHS for multiplication and
1678 // division.)
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001679 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001680 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor914af212010-04-23 04:16:32 +00001681 return LValue();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001682 }
Douglas Gregor914af212010-04-23 04:16:32 +00001683
Mike Stumpc63428b2009-05-22 19:07:20 +00001684 // Emit the RHS first. __block variables need to have the rhs evaluated
1685 // first, plus this should improve codegen a little.
1686 OpInfo.RHS = Visit(E->getRHS());
1687 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00001688 OpInfo.Opcode = E->getOpcode();
Mike Stumpc63428b2009-05-22 19:07:20 +00001689 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001690 // Load/convert the LHS.
Richard Smith69d0d262012-08-24 00:54:33 +00001691 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::CT_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00001692 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
David Chisnallfa35df62012-01-16 17:27:18 +00001693
1694 llvm::PHINode *atomicPHI = 0;
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001695 if (LHSTy->isAtomicType()) {
David Chisnallfa35df62012-01-16 17:27:18 +00001696 // FIXME: For floating point types, we should be saving and restoring the
1697 // floating point environment in the loop.
1698 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1699 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1700 Builder.CreateBr(opBB);
1701 Builder.SetInsertPoint(opBB);
1702 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1703 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001704 OpInfo.LHS = atomicPHI;
1705 }
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001706
1707 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1708 E->getComputationLHSType());
1709
Chris Lattner3d966d62007-08-24 21:00:35 +00001710 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001711 Result = (this->*Func)(OpInfo);
Douglas Gregor914af212010-04-23 04:16:32 +00001712
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00001713 // Convert the result back to the LHS type.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001714 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnallfa35df62012-01-16 17:27:18 +00001715
1716 if (atomicPHI) {
1717 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1718 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1719 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1720 Result, llvm::SequentiallyConsistent);
1721 atomicPHI->addIncoming(old, opBB);
1722 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1723 Builder.CreateCondBr(success, contBB, opBB);
1724 Builder.SetInsertPoint(contBB);
1725 return LHSLV;
1726 }
Douglas Gregor914af212010-04-23 04:16:32 +00001727
Mike Stump4a3999f2009-09-09 13:00:44 +00001728 // Store the result value into the LHS lvalue. Bit-fields are handled
1729 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1730 // 'An assignment expression has the value of the left operand after the
1731 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001732 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00001733 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001734 else
John McCall55e1fbc2011-06-25 02:11:03 +00001735 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001736
Douglas Gregor914af212010-04-23 04:16:32 +00001737 return LHSLV;
1738}
1739
1740Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1741 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1742 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001743 Value *RHS;
1744 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1745
1746 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00001747 if (Ignore)
1748 return 0;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001749
John McCall07bb1962010-11-16 10:08:07 +00001750 // The result of an assignment in C is the assigned r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001751 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00001752 return RHS;
1753
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00001754 // If the lvalue is non-volatile, return the computed value of the assignment.
1755 if (!LHS.isVolatileQualified())
1756 return RHS;
1757
1758 // Otherwise, reload the value.
John McCall55e1fbc2011-06-25 02:11:03 +00001759 return EmitLoadOfLValue(LHS);
Chris Lattner3d966d62007-08-24 21:00:35 +00001760}
1761
Chris Lattner8ee6a412010-09-11 21:47:09 +00001762void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1763 const BinOpInfo &Ops,
1764 llvm::Value *Zero, bool isDiv) {
Bill Wendlinge367f382011-07-07 21:13:10 +00001765 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
Chris Lattner8ee6a412010-09-11 21:47:09 +00001766 llvm::BasicBlock *contBB =
Bill Wendlinge367f382011-07-07 21:13:10 +00001767 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1768 llvm::next(insertPt));
1769 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Chris Lattner8ee6a412010-09-11 21:47:09 +00001770
Chris Lattner2192fe52011-07-18 04:24:23 +00001771 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner8ee6a412010-09-11 21:47:09 +00001772
1773 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1774 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00001775 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00001776 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1777
1778 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1779 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1780 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1781 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1782 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1783 overflowBB, contBB);
1784 } else {
1785 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1786 overflowBB, contBB);
1787 }
1788 EmitOverflowBB(overflowBB);
1789 Builder.SetInsertPoint(contBB);
1790}
Chris Lattner3d966d62007-08-24 21:00:35 +00001791
Chris Lattner2da04b32007-08-24 05:35:26 +00001792Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner8ee6a412010-09-11 21:47:09 +00001793 if (isTrapvOverflowBehavior()) {
1794 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1795
1796 if (Ops.Ty->isIntegerType())
1797 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1798 else if (Ops.Ty->isRealFloatingType()) {
Bill Wendlinge367f382011-07-07 21:13:10 +00001799 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1800 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1801 llvm::next(insertPt));
Chris Lattner8ee6a412010-09-11 21:47:09 +00001802 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1803 CGF.CurFn);
Chris Lattner8ee6a412010-09-11 21:47:09 +00001804 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1805 overflowBB, DivCont);
1806 EmitOverflowBB(overflowBB);
1807 Builder.SetInsertPoint(DivCont);
1808 }
1809 }
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00001810 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1811 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
David Blaikiebbafb8a2012-03-11 07:00:24 +00001812 if (CGF.getContext().getLangOpts().OpenCL) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00001813 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1814 llvm::Type *ValTy = Val->getType();
1815 if (ValTy->isFloatTy() ||
1816 (isa<llvm::VectorType>(ValTy) &&
1817 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00001818 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00001819 }
1820 return Val;
1821 }
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00001822 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00001823 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1824 else
1825 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1826}
1827
1828Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1829 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner8ee6a412010-09-11 21:47:09 +00001830 if (isTrapvOverflowBehavior()) {
1831 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1832
1833 if (Ops.Ty->isIntegerType())
1834 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1835 }
1836
Eli Friedman493c34a2011-04-10 04:44:11 +00001837 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00001838 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1839 else
1840 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1841}
1842
Mike Stump0c61b732009-04-01 20:28:16 +00001843Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1844 unsigned IID;
1845 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00001846
Chris Lattner0bf27622010-06-26 21:48:21 +00001847 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00001848 case BO_Add:
1849 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00001850 OpID = 1;
1851 IID = llvm::Intrinsic::sadd_with_overflow;
1852 break;
John McCalle3027922010-08-25 11:45:40 +00001853 case BO_Sub:
1854 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00001855 OpID = 2;
1856 IID = llvm::Intrinsic::ssub_with_overflow;
1857 break;
John McCalle3027922010-08-25 11:45:40 +00001858 case BO_Mul:
1859 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00001860 OpID = 3;
1861 IID = llvm::Intrinsic::smul_with_overflow;
1862 break;
1863 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001864 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00001865 }
Mike Stumpd3e38852009-04-02 18:15:54 +00001866 OpID <<= 1;
1867 OpID |= 1;
1868
Chris Lattnera5f58b02011-07-09 17:41:47 +00001869 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00001870
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00001871 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00001872
1873 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1874 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1875 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1876
1877 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00001878 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendlinge367f382011-07-07 21:13:10 +00001879 llvm::Function::iterator insertPt = initialBB;
1880 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1881 llvm::next(insertPt));
Chris Lattner8139c982010-08-07 00:20:46 +00001882 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00001883
1884 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1885
Chris Lattner8139c982010-08-07 00:20:46 +00001886 // Handle overflow with llvm.trap.
David Chisnalldd84ef12010-09-17 18:29:54 +00001887 const std::string *handlerName =
David Blaikiebbafb8a2012-03-11 07:00:24 +00001888 &CGF.getContext().getLangOpts().OverflowHandler;
David Chisnalldd84ef12010-09-17 18:29:54 +00001889 if (handlerName->empty()) {
1890 EmitOverflowBB(overflowBB);
1891 Builder.SetInsertPoint(continueBB);
1892 return result;
1893 }
1894
1895 // If an overflow handler is set, then we want to call it and then use its
1896 // result, if it returns.
1897 Builder.SetInsertPoint(overflowBB);
1898
1899 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00001900 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001901 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00001902 llvm::FunctionType *handlerTy =
1903 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1904 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1905
1906 // Sign extend the args to 64-bit, so that we can use the same handler for
1907 // all types of overflow.
1908 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1909 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1910
1911 // Call the handler with the two arguments, the operation, and the size of
1912 // the result.
1913 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1914 Builder.getInt8(OpID),
1915 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1916
1917 // Truncate the result back to the desired size.
1918 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1919 Builder.CreateBr(continueBB);
1920
Mike Stump0c61b732009-04-01 20:28:16 +00001921 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001922 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00001923 phi->addIncoming(result, initialBB);
1924 phi->addIncoming(handlerResult, overflowBB);
1925
1926 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00001927}
Chris Lattner2da04b32007-08-24 05:35:26 +00001928
John McCall77527a82011-06-25 01:32:37 +00001929/// Emit pointer + index arithmetic.
1930static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1931 const BinOpInfo &op,
1932 bool isSubtraction) {
1933 // Must have binary (not unary) expr here. Unary pointer
1934 // increment/decrement doesn't use this path.
1935 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1936
1937 Value *pointer = op.LHS;
1938 Expr *pointerOperand = expr->getLHS();
1939 Value *index = op.RHS;
1940 Expr *indexOperand = expr->getRHS();
1941
1942 // In a subtraction, the LHS is always the pointer.
1943 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1944 std::swap(pointer, index);
1945 std::swap(pointerOperand, indexOperand);
1946 }
1947
1948 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1949 if (width != CGF.PointerWidthInBits) {
1950 // Zero-extend or sign-extend the pointer value according to
1951 // whether the index is signed or not.
1952 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1953 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1954 "idx.ext");
1955 }
1956
1957 // If this is subtraction, negate the index.
1958 if (isSubtraction)
1959 index = CGF.Builder.CreateNeg(index, "idx.neg");
1960
1961 const PointerType *pointerType
1962 = pointerOperand->getType()->getAs<PointerType>();
1963 if (!pointerType) {
1964 QualType objectType = pointerOperand->getType()
1965 ->castAs<ObjCObjectPointerType>()
1966 ->getPointeeType();
1967 llvm::Value *objectSize
1968 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1969
1970 index = CGF.Builder.CreateMul(index, objectSize);
1971
1972 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1973 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1974 return CGF.Builder.CreateBitCast(result, pointer->getType());
1975 }
1976
1977 QualType elementType = pointerType->getPointeeType();
1978 if (const VariableArrayType *vla
1979 = CGF.getContext().getAsVariableArrayType(elementType)) {
1980 // The element count here is the total number of non-VLA elements.
1981 llvm::Value *numElements = CGF.getVLASize(vla).first;
1982
1983 // Effectively, the multiply by the VLA size is part of the GEP.
1984 // GEP indexes are signed, and scaling an index isn't permitted to
1985 // signed-overflow, so we use the same semantics for our explicit
1986 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001987 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00001988 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1989 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1990 } else {
1991 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1992 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00001993 }
John McCall77527a82011-06-25 01:32:37 +00001994 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00001995 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001996
Mike Stump4a3999f2009-09-09 13:00:44 +00001997 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1998 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1999 // future proof.
John McCall77527a82011-06-25 01:32:37 +00002000 if (elementType->isVoidType() || elementType->isFunctionType()) {
2001 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2002 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2003 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00002004 }
2005
David Blaikiebbafb8a2012-03-11 07:00:24 +00002006 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00002007 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2008
2009 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00002010}
2011
John McCall77527a82011-06-25 01:32:37 +00002012Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2013 if (op.LHS->getType()->isPointerTy() ||
2014 op.RHS->getType()->isPointerTy())
2015 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2016
2017 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002018 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00002019 case LangOptions::SOB_Defined:
2020 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00002021 case LangOptions::SOB_Undefined:
2022 if (!CGF.CatchUndefined)
2023 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2024 // Fall through.
John McCall77527a82011-06-25 01:32:37 +00002025 case LangOptions::SOB_Trapping:
2026 return EmitOverflowCheckedBinOp(op);
2027 }
2028 }
2029
2030 if (op.LHS->getType()->isFPOrFPVectorTy())
2031 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2032
2033 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2034}
2035
2036Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2037 // The LHS is always a pointer if either side is.
2038 if (!op.LHS->getType()->isPointerTy()) {
2039 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002040 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00002041 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00002042 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00002043 case LangOptions::SOB_Undefined:
2044 if (!CGF.CatchUndefined)
2045 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2046 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +00002047 case LangOptions::SOB_Trapping:
John McCall77527a82011-06-25 01:32:37 +00002048 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00002049 }
2050 }
2051
John McCall77527a82011-06-25 01:32:37 +00002052 if (op.LHS->getType()->isFPOrFPVectorTy())
2053 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Chris Lattner5902e7b2010-03-29 17:28:16 +00002054
John McCall77527a82011-06-25 01:32:37 +00002055 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00002056 }
Chris Lattner3d966d62007-08-24 21:00:35 +00002057
John McCall77527a82011-06-25 01:32:37 +00002058 // If the RHS is not a pointer, then we have normal pointer
2059 // arithmetic.
2060 if (!op.RHS->getType()->isPointerTy())
2061 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmane381f7e2009-03-28 02:45:41 +00002062
John McCall77527a82011-06-25 01:32:37 +00002063 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00002064
John McCall77527a82011-06-25 01:32:37 +00002065 // Do the raw subtraction part.
2066 llvm::Value *LHS
2067 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2068 llvm::Value *RHS
2069 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2070 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002071
John McCall77527a82011-06-25 01:32:37 +00002072 // Okay, figure out the element size.
2073 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2074 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002075
John McCall77527a82011-06-25 01:32:37 +00002076 llvm::Value *divisor = 0;
2077
2078 // For a variable-length array, this is going to be non-constant.
2079 if (const VariableArrayType *vla
2080 = CGF.getContext().getAsVariableArrayType(elementType)) {
2081 llvm::Value *numElements;
2082 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2083
2084 divisor = numElements;
2085
2086 // Scale the number of non-VLA elements by the non-VLA element size.
2087 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2088 if (!eltSize.isOne())
2089 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2090
2091 // For everything elese, we can just compute it, safe in the
2092 // assumption that Sema won't let anything through that we can't
2093 // safely compute the size of.
2094 } else {
2095 CharUnits elementSize;
2096 // Handle GCC extension for pointer arithmetic on void* and
2097 // function pointer types.
2098 if (elementType->isVoidType() || elementType->isFunctionType())
2099 elementSize = CharUnits::One();
2100 else
2101 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2102
2103 // Don't even emit the divide for element size of 1.
2104 if (elementSize.isOne())
2105 return diffInChars;
2106
2107 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00002108 }
Chris Lattner2e72da942011-03-01 00:03:48 +00002109
Chris Lattner2e72da942011-03-01 00:03:48 +00002110 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2111 // pointer difference in C is only defined in the case where both operands
2112 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00002113 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00002114}
2115
2116Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2117 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2118 // RHS to the same size as the LHS.
2119 Value *RHS = Ops.RHS;
2120 if (Ops.LHS->getType() != RHS->getType())
2121 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002122
Richard Smith3e056de2012-08-25 00:32:28 +00002123 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpba6a0c42009-12-14 21:58:14 +00002124 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith3e056de2012-08-25 00:32:28 +00002125 llvm::BasicBlock *Cont = CGF.createBasicBlock("shl.cont");
2126 llvm::BasicBlock *Trap = CGF.getTrapBB();
2127 llvm::Value *WidthMinusOne =
Richard Smitha374bf02012-08-25 05:43:00 +00002128 llvm::ConstantInt::get(RHS->getType(), Width - 1);
Richard Smith3e056de2012-08-25 00:32:28 +00002129 CGF.Builder.CreateCondBr(Builder.CreateICmpULE(RHS, WidthMinusOne),
2130 Cont, Trap);
Mike Stumpba6a0c42009-12-14 21:58:14 +00002131 CGF.EmitBlock(Cont);
Richard Smith3e056de2012-08-25 00:32:28 +00002132
2133 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2134 // Check whether we are shifting any non-zero bits off the top of the
2135 // integer.
2136 Cont = CGF.createBasicBlock("shl.ok");
2137 llvm::Value *BitsShiftedOff =
2138 Builder.CreateLShr(Ops.LHS,
2139 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2140 /*NUW*/true, /*NSW*/true),
2141 "shl.check");
2142 if (CGF.getLangOpts().CPlusPlus) {
2143 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2144 // Under C++11's rules, shifting a 1 bit into the sign bit is
2145 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2146 // define signed left shifts, so we use the C99 and C++11 rules there).
2147 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2148 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2149 }
2150 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2151 Builder.CreateCondBr(Builder.CreateICmpEQ(BitsShiftedOff, Zero),
2152 Cont, Trap);
2153 CGF.EmitBlock(Cont);
2154 }
Mike Stumpba6a0c42009-12-14 21:58:14 +00002155 }
2156
Chris Lattner2da04b32007-08-24 05:35:26 +00002157 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2158}
2159
2160Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2161 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2162 // RHS to the same size as the LHS.
2163 Value *RHS = Ops.RHS;
2164 if (Ops.LHS->getType() != RHS->getType())
2165 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002166
Richard Smith3e056de2012-08-25 00:32:28 +00002167 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpba6a0c42009-12-14 21:58:14 +00002168 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2169 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2170 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2171 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00002172 Cont, CGF.getTrapBB());
Mike Stumpba6a0c42009-12-14 21:58:14 +00002173 CGF.EmitBlock(Cont);
2174 }
2175
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002176 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002177 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2178 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2179}
2180
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002181enum IntrinsicType { VCMPEQ, VCMPGT };
2182// return corresponding comparison intrinsic for given vector type
2183static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2184 BuiltinType::Kind ElemKind) {
2185 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002186 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002187 case BuiltinType::Char_U:
2188 case BuiltinType::UChar:
2189 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2190 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002191 case BuiltinType::Char_S:
2192 case BuiltinType::SChar:
2193 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2194 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002195 case BuiltinType::UShort:
2196 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2197 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002198 case BuiltinType::Short:
2199 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2200 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002201 case BuiltinType::UInt:
2202 case BuiltinType::ULong:
2203 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2204 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002205 case BuiltinType::Int:
2206 case BuiltinType::Long:
2207 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2208 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002209 case BuiltinType::Float:
2210 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2211 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002212 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002213}
2214
Chris Lattner2da04b32007-08-24 05:35:26 +00002215Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2216 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002217 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00002218 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00002219 QualType LHSTy = E->getLHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00002220 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00002221 assert(E->getOpcode() == BO_EQ ||
2222 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00002223 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2224 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00002225 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00002226 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedman1762cf22009-12-11 07:36:43 +00002227 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002228 Value *LHS = Visit(E->getLHS());
2229 Value *RHS = Visit(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00002230
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002231 // If AltiVec, the comparison results in a numeric type, so we use
2232 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00002233 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002234 // constants for mapping CR6 register bits to predicate result
2235 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2236
2237 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2238
2239 // in several cases vector arguments order will be reversed
2240 Value *FirstVecArg = LHS,
2241 *SecondVecArg = RHS;
2242
2243 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCall424cec92011-01-19 06:33:43 +00002244 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002245 BuiltinType::Kind ElementKind = BTy->getKind();
2246
2247 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002248 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002249 case BO_EQ:
2250 CR6 = CR6_LT;
2251 ID = GetIntrinsic(VCMPEQ, ElementKind);
2252 break;
2253 case BO_NE:
2254 CR6 = CR6_EQ;
2255 ID = GetIntrinsic(VCMPEQ, ElementKind);
2256 break;
2257 case BO_LT:
2258 CR6 = CR6_LT;
2259 ID = GetIntrinsic(VCMPGT, ElementKind);
2260 std::swap(FirstVecArg, SecondVecArg);
2261 break;
2262 case BO_GT:
2263 CR6 = CR6_LT;
2264 ID = GetIntrinsic(VCMPGT, ElementKind);
2265 break;
2266 case BO_LE:
2267 if (ElementKind == BuiltinType::Float) {
2268 CR6 = CR6_LT;
2269 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2270 std::swap(FirstVecArg, SecondVecArg);
2271 }
2272 else {
2273 CR6 = CR6_EQ;
2274 ID = GetIntrinsic(VCMPGT, ElementKind);
2275 }
2276 break;
2277 case BO_GE:
2278 if (ElementKind == BuiltinType::Float) {
2279 CR6 = CR6_LT;
2280 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2281 }
2282 else {
2283 CR6 = CR6_EQ;
2284 ID = GetIntrinsic(VCMPGT, ElementKind);
2285 std::swap(FirstVecArg, SecondVecArg);
2286 }
2287 break;
2288 }
2289
Chris Lattner2531eb42011-04-19 22:55:03 +00002290 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002291 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2292 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2293 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2294 }
2295
Duncan Sands998f9d92010-02-15 16:14:01 +00002296 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begemanfe79ca22008-07-25 20:16:05 +00002297 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002298 LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002299 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedman3c285242008-05-29 15:09:15 +00002300 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002301 LHS, RHS, "cmp");
2302 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00002303 // Unsigned integers and pointers.
2304 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002305 LHS, RHS, "cmp");
2306 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00002307
2308 // If this is a vector comparison, sign extend the result to the appropriate
2309 // vector integer type and return it (don't convert to bool).
2310 if (LHSTy->isVectorType())
2311 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00002312
Chris Lattner2da04b32007-08-24 05:35:26 +00002313 } else {
2314 // Complex Comparison: can only be an equality comparison.
2315 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2316 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00002317
John McCall9dd450b2009-09-21 23:43:11 +00002318 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002319
Chris Lattner42e6b812007-08-26 16:34:22 +00002320 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00002321 if (CETy->isRealFloatingType()) {
2322 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2323 LHS.first, RHS.first, "cmp.r");
2324 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2325 LHS.second, RHS.second, "cmp.i");
2326 } else {
2327 // Complex comparisons can only be equality comparisons. As such, signed
2328 // and unsigned opcodes are the same.
2329 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2330 LHS.first, RHS.first, "cmp.r");
2331 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2332 LHS.second, RHS.second, "cmp.i");
2333 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002334
John McCalle3027922010-08-25 11:45:40 +00002335 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002336 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2337 } else {
John McCalle3027922010-08-25 11:45:40 +00002338 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00002339 "Complex comparison other than == or != ?");
2340 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2341 }
2342 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00002343
2344 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner2da04b32007-08-24 05:35:26 +00002345}
2346
2347Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002348 bool Ignore = TestAndClearIgnoreResultAssign();
2349
John McCall31168b02011-06-15 23:02:42 +00002350 Value *RHS;
2351 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00002352
John McCall31168b02011-06-15 23:02:42 +00002353 switch (E->getLHS()->getType().getObjCLifetime()) {
2354 case Qualifiers::OCL_Strong:
2355 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2356 break;
2357
2358 case Qualifiers::OCL_Autoreleasing:
2359 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2360 break;
2361
2362 case Qualifiers::OCL_Weak:
2363 RHS = Visit(E->getRHS());
Richard Smith69d0d262012-08-24 00:54:33 +00002364 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::CT_Store);
John McCall31168b02011-06-15 23:02:42 +00002365 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2366 break;
2367
2368 // No reason to do any of these differently.
2369 case Qualifiers::OCL_None:
2370 case Qualifiers::OCL_ExplicitNone:
2371 // __block variables need to have the rhs evaluated first, plus
2372 // this should improve codegen just a little.
2373 RHS = Visit(E->getRHS());
Richard Smith69d0d262012-08-24 00:54:33 +00002374 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::CT_Store);
John McCall31168b02011-06-15 23:02:42 +00002375
2376 // Store the value into the LHS. Bit-fields are handled specially
2377 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2378 // 'An assignment expression has the value of the left operand after
2379 // the assignment...'.
2380 if (LHS.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002381 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCall31168b02011-06-15 23:02:42 +00002382 else
John McCall55e1fbc2011-06-25 02:11:03 +00002383 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCall31168b02011-06-15 23:02:42 +00002384 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002385
2386 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002387 if (Ignore)
2388 return 0;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002389
John McCall07bb1962010-11-16 10:08:07 +00002390 // The result of an assignment in C is the assigned r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002391 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00002392 return RHS;
2393
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002394 // If the lvalue is non-volatile, return the computed value of the assignment.
2395 if (!LHS.isVolatileQualified())
2396 return RHS;
2397
2398 // Otherwise, reload the value.
John McCall55e1fbc2011-06-25 02:11:03 +00002399 return EmitLoadOfLValue(LHS);
Chris Lattner2da04b32007-08-24 05:35:26 +00002400}
2401
2402Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00002403
2404 // Perform vector logical and on comparisons with zero vectors.
2405 if (E->getType()->isVectorType()) {
2406 Value *LHS = Visit(E->getLHS());
2407 Value *RHS = Visit(E->getRHS());
2408 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2409 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2410 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2411 Value *And = Builder.CreateAnd(LHS, RHS);
2412 return Builder.CreateSExt(And, Zero->getType(), "sext");
2413 }
2414
Chris Lattner2192fe52011-07-18 04:24:23 +00002415 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner671fec82009-10-17 04:24:20 +00002416
Chris Lattner8b084582008-11-12 08:26:50 +00002417 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2418 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00002419 bool LHSCondVal;
2420 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2421 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner5b1964b2008-11-11 07:41:27 +00002422 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00002423 // ZExt result to int or bool.
2424 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00002425 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002426
Chris Lattner671fec82009-10-17 04:24:20 +00002427 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00002428 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00002429 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00002430 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002431
Daniel Dunbara612e792008-11-13 01:38:36 +00002432 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2433 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00002434
John McCallce1de612011-01-26 04:00:11 +00002435 CodeGenFunction::ConditionalEvaluation eval(CGF);
2436
Chris Lattner35710d182008-11-12 08:38:24 +00002437 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2438 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2439
2440 // Any edges into the ContBlock are now from an (indeterminate number of)
2441 // edges from this first condition. All of these values will be false. Start
2442 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00002443 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00002444 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00002445 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2446 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00002447 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00002448
John McCallce1de612011-01-26 04:00:11 +00002449 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00002450 CGF.EmitBlock(RHSBlock);
2451 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00002452 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00002453
Chris Lattner2da04b32007-08-24 05:35:26 +00002454 // Reaquire the RHS block, as there may be subblocks inserted.
2455 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00002456
2457 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2458 // into the phi node for the edge with the value of RHSCond.
Devang Patel4d761272011-03-30 00:08:31 +00002459 if (CGF.getDebugInfo())
2460 // There is no need to emit line number for unconditional branch.
2461 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00002462 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00002463 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00002464
Chris Lattner2da04b32007-08-24 05:35:26 +00002465 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00002466 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002467}
2468
2469Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00002470
2471 // Perform vector logical or on comparisons with zero vectors.
2472 if (E->getType()->isVectorType()) {
2473 Value *LHS = Visit(E->getLHS());
2474 Value *RHS = Visit(E->getRHS());
2475 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2476 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2477 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2478 Value *Or = Builder.CreateOr(LHS, RHS);
2479 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2480 }
2481
Chris Lattner2192fe52011-07-18 04:24:23 +00002482 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner671fec82009-10-17 04:24:20 +00002483
Chris Lattner8b084582008-11-12 08:26:50 +00002484 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2485 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00002486 bool LHSCondVal;
2487 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2488 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner5b1964b2008-11-11 07:41:27 +00002489 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00002490 // ZExt result to int or bool.
2491 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00002492 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002493
Chris Lattner671fec82009-10-17 04:24:20 +00002494 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00002495 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00002496 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00002497 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002498
Daniel Dunbara612e792008-11-13 01:38:36 +00002499 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2500 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00002501
John McCallce1de612011-01-26 04:00:11 +00002502 CodeGenFunction::ConditionalEvaluation eval(CGF);
2503
Chris Lattner35710d182008-11-12 08:38:24 +00002504 // Branch on the LHS first. If it is true, go to the success (cont) block.
2505 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2506
2507 // Any edges into the ContBlock are now from an (indeterminate number of)
2508 // edges from this first condition. All of these values will be true. Start
2509 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00002510 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00002511 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00002512 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2513 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00002514 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00002515
John McCallce1de612011-01-26 04:00:11 +00002516 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00002517
Chris Lattner35710d182008-11-12 08:38:24 +00002518 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00002519 CGF.EmitBlock(RHSBlock);
2520 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00002521
John McCallce1de612011-01-26 04:00:11 +00002522 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00002523
Chris Lattner2da04b32007-08-24 05:35:26 +00002524 // Reaquire the RHS block, as there may be subblocks inserted.
2525 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00002526
Chris Lattner35710d182008-11-12 08:38:24 +00002527 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2528 // into the phi node for the edge with the value of RHSCond.
2529 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00002530 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00002531
Chris Lattner2da04b32007-08-24 05:35:26 +00002532 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00002533 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002534}
2535
2536Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00002537 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00002538 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00002539 return Visit(E->getRHS());
2540}
2541
2542//===----------------------------------------------------------------------===//
2543// Other Operators
2544//===----------------------------------------------------------------------===//
2545
Chris Lattner3fd91f832008-11-12 08:55:54 +00002546/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2547/// expression is cheap enough and side-effect-free enough to evaluate
2548/// unconditionally instead of conditionally. This is used to convert control
2549/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00002550static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2551 CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002552 E = E->IgnoreParens();
Mike Stump4a3999f2009-09-09 13:00:44 +00002553
Chris Lattner56784f92011-04-16 23:15:35 +00002554 // Anything that is an integer or floating point constant is fine.
2555 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner3fd91f832008-11-12 08:55:54 +00002556 return true;
Mike Stump4a3999f2009-09-09 13:00:44 +00002557
Chris Lattner3fd91f832008-11-12 08:55:54 +00002558 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2559 // X and Y are local variables.
2560 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2561 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stump53f9ded2009-11-03 23:25:48 +00002562 if (VD->hasLocalStorage() && !(CGF.getContext()
2563 .getCanonicalType(VD->getType())
2564 .isVolatileQualified()))
Chris Lattner3fd91f832008-11-12 08:55:54 +00002565 return true;
Mike Stump4a3999f2009-09-09 13:00:44 +00002566
Chris Lattner3fd91f832008-11-12 08:55:54 +00002567 return false;
2568}
2569
2570
Chris Lattner2da04b32007-08-24 05:35:26 +00002571Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00002572VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002573 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00002574
2575 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00002576 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00002577
2578 Expr *condExpr = E->getCond();
2579 Expr *lhsExpr = E->getTrueExpr();
2580 Expr *rhsExpr = E->getFalseExpr();
2581
Chris Lattnercd439292008-11-12 08:04:58 +00002582 // If the condition constant folds and can be elided, try to avoid emitting
2583 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00002584 bool CondExprBool;
2585 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002586 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00002587 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00002588
Eli Friedman27ef75b2011-10-15 02:10:40 +00002589 // If the dead side doesn't have labels we need, just emit the Live part.
2590 if (!CGF.ContainsLabel(dead)) {
2591 Value *Result = Visit(live);
2592
2593 // If the live part is a throw expression, it acts like it has a void
2594 // type, so evaluating it returns a null Value*. However, a conditional
2595 // with non-void type must return a non-null Value*.
2596 if (!Result && !E->getType()->isVoidType())
2597 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2598
2599 return Result;
2600 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00002601 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002602
Nate Begemanabb5a732010-09-20 22:41:17 +00002603 // OpenCL: If the condition is a vector, we can treat this condition like
2604 // the select function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002605 if (CGF.getContext().getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00002606 && condExpr->getType()->isVectorType()) {
2607 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2608 llvm::Value *LHS = Visit(lhsExpr);
2609 llvm::Value *RHS = Visit(rhsExpr);
Nate Begemanabb5a732010-09-20 22:41:17 +00002610
Chris Lattner2192fe52011-07-18 04:24:23 +00002611 llvm::Type *condType = ConvertType(condExpr->getType());
2612 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begemanabb5a732010-09-20 22:41:17 +00002613
2614 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00002615 llvm::Type *elemType = vecTy->getElementType();
Nate Begemanabb5a732010-09-20 22:41:17 +00002616
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002617 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00002618 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2619 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2620 llvm::VectorType::get(elemType,
2621 numElem),
2622 "sext");
2623 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2624
2625 // Cast float to int to perform ANDs if necessary.
2626 llvm::Value *RHSTmp = RHS;
2627 llvm::Value *LHSTmp = LHS;
2628 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00002629 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00002630 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00002631 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2632 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2633 wasCast = true;
2634 }
2635
2636 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2637 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2638 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2639 if (wasCast)
2640 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2641
2642 return tmp5;
2643 }
2644
Chris Lattner3fd91f832008-11-12 08:55:54 +00002645 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2646 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00002647 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00002648 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2649 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2650 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2651 llvm::Value *LHS = Visit(lhsExpr);
2652 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00002653 if (!LHS) {
2654 // If the conditional has void type, make sure we return a null Value*.
2655 assert(!RHS && "LHS and RHS types must match");
2656 return 0;
2657 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00002658 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2659 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002660
Daniel Dunbard2a53a72008-11-12 10:13:37 +00002661 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2662 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00002663 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00002664
2665 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00002666 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlsson43c52cd2009-06-04 03:00:32 +00002667
Chris Lattner2da04b32007-08-24 05:35:26 +00002668 CGF.EmitBlock(LHSBlock);
John McCallce1de612011-01-26 04:00:11 +00002669 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00002670 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00002671 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00002672
Chris Lattner2da04b32007-08-24 05:35:26 +00002673 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00002674 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00002675
Chris Lattner2da04b32007-08-24 05:35:26 +00002676 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00002677 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00002678 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00002679 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00002680
John McCallce1de612011-01-26 04:00:11 +00002681 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00002682 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00002683
Eli Friedmanf6c175b2009-12-07 20:25:53 +00002684 // If the LHS or RHS is a throw expression, it will be legitimately null.
2685 if (!LHS)
2686 return RHS;
2687 if (!RHS)
2688 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00002689
Chris Lattner2da04b32007-08-24 05:35:26 +00002690 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00002691 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00002692 PN->addIncoming(LHS, LHSBlock);
2693 PN->addIncoming(RHS, RHSBlock);
2694 return PN;
2695}
2696
2697Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmane0a5b8b2009-03-04 05:52:32 +00002698 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002699}
2700
Chris Lattnerb6a7b582007-11-30 17:56:23 +00002701Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedmanddea0ad2009-01-20 17:46:04 +00002702 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00002703 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2704
2705 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stump4a3999f2009-09-09 13:00:44 +00002706 if (!ArgPtr)
Anders Carlsson13abd7e2008-11-04 05:30:00 +00002707 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2708
Mike Stumpdf0fe272009-05-29 15:46:01 +00002709 // FIXME Volatility.
Anders Carlsson13abd7e2008-11-04 05:30:00 +00002710 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7e13ab82007-10-15 20:28:48 +00002711}
2712
John McCall351762c2011-02-07 10:33:21 +00002713Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2714 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00002715}
2716
Tanya Lattner55808c12011-06-04 00:47:47 +00002717Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2718 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00002719 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner55808c12011-06-04 00:47:47 +00002720
2721 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2722 // a shuffle vector instead of a bitcast.
Chris Lattner2192fe52011-07-18 04:24:23 +00002723 llvm::Type *SrcTy = Src->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00002724 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2725 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2726 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2727 if ((numElementsDst == 3 && numElementsSrc == 4)
2728 || (numElementsDst == 4 && numElementsSrc == 3)) {
2729
2730
2731 // In the case of going from int4->float3, a bitcast is needed before
2732 // doing a shuffle.
Chris Lattner2192fe52011-07-18 04:24:23 +00002733 llvm::Type *srcElemTy =
Tanya Lattner55808c12011-06-04 00:47:47 +00002734 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002735 llvm::Type *dstElemTy =
Tanya Lattner55808c12011-06-04 00:47:47 +00002736 cast<llvm::VectorType>(DstTy)->getElementType();
2737
2738 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2739 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2740 // Create a float type of the same size as the source or destination.
Chris Lattner2192fe52011-07-18 04:24:23 +00002741 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00002742 numElementsSrc);
2743
2744 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2745 }
2746
2747 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2748
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002749 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner55808c12011-06-04 00:47:47 +00002750 Args.push_back(Builder.getInt32(0));
2751 Args.push_back(Builder.getInt32(1));
2752 Args.push_back(Builder.getInt32(2));
2753
2754 if (numElementsDst == 4)
Chris Lattnerece04092012-02-07 00:39:47 +00002755 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner55808c12011-06-04 00:47:47 +00002756
2757 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2758
2759 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2760 }
2761 }
2762
2763 return Builder.CreateBitCast(Src, DstTy, "astype");
2764}
2765
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002766Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2767 return CGF.EmitAtomicExpr(E).getScalarVal();
2768}
2769
Chris Lattner2da04b32007-08-24 05:35:26 +00002770//===----------------------------------------------------------------------===//
2771// Entry Point into this File
2772//===----------------------------------------------------------------------===//
2773
Mike Stump4a3999f2009-09-09 13:00:44 +00002774/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2775/// type, ignoring the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002776Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002777 assert(E && !hasAggregateLLVMType(E->getType()) &&
2778 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00002779
Devang Patele65982c2011-03-07 18:29:53 +00002780 if (isa<CXXDefaultArgExpr>(E))
Devang Pateld6ffebb2011-03-07 18:45:56 +00002781 disableDebugInfo();
Devang Patele65982c2011-03-07 18:29:53 +00002782 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stumpdf0fe272009-05-29 15:46:01 +00002783 .Visit(const_cast<Expr*>(E));
Devang Patele65982c2011-03-07 18:29:53 +00002784 if (isa<CXXDefaultArgExpr>(E))
Devang Pateld6ffebb2011-03-07 18:45:56 +00002785 enableDebugInfo();
Devang Patele65982c2011-03-07 18:29:53 +00002786 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +00002787}
Chris Lattner3474c202007-08-26 06:48:56 +00002788
2789/// EmitScalarConversion - Emit a conversion from the specified type to the
2790/// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00002791Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2792 QualType DstTy) {
Chris Lattner3474c202007-08-26 06:48:56 +00002793 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2794 "Invalid scalar expression to emit");
2795 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2796}
Chris Lattner42e6b812007-08-26 16:34:22 +00002797
Mike Stump4a3999f2009-09-09 13:00:44 +00002798/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2799/// type to the specified destination type, where the destination type is an
2800/// LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00002801Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2802 QualType SrcTy,
2803 QualType DstTy) {
Chris Lattnerf3bc75a2008-04-04 16:54:41 +00002804 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00002805 "Invalid complex -> scalar conversion");
2806 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2807 DstTy);
2808}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00002809
Chris Lattner05dc78c2010-06-26 22:09:34 +00002810
2811llvm::Value *CodeGenFunction::
2812EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2813 bool isInc, bool isPre) {
2814 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2815}
2816
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00002817LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2818 llvm::Value *V;
2819 // object->isa or (*object).isa
2820 // Generate code as for: *(Class*)object
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00002821 // build Class* type
Chris Lattner2192fe52011-07-18 04:24:23 +00002822 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00002823
2824 Expr *BaseExpr = E->getBase();
John McCall086a4642010-11-24 05:12:34 +00002825 if (BaseExpr->isRValue()) {
Eli Friedman3184a5e2011-12-19 23:03:09 +00002826 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00002827 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2828 Builder.CreateStore(Src, V);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002829 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedman3184a5e2011-12-19 23:03:09 +00002830 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002831 } else {
2832 if (E->isArrow())
2833 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2834 else
2835 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00002836 }
2837
2838 // build Class* type
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00002839 ClassPtrTy = ClassPtrTy->getPointerTo();
2840 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedman3184a5e2011-12-19 23:03:09 +00002841 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00002842}
2843
Douglas Gregor914af212010-04-23 04:16:32 +00002844
John McCalla2342eb2010-12-05 02:00:02 +00002845LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00002846 const CompoundAssignOperator *E) {
2847 ScalarExprEmitter Scalar(*this);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002848 Value *Result = 0;
Douglas Gregor914af212010-04-23 04:16:32 +00002849 switch (E->getOpcode()) {
2850#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00002851 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00002852 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002853 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00002854 COMPOUND_OP(Mul);
2855 COMPOUND_OP(Div);
2856 COMPOUND_OP(Rem);
2857 COMPOUND_OP(Add);
2858 COMPOUND_OP(Sub);
2859 COMPOUND_OP(Shl);
2860 COMPOUND_OP(Shr);
2861 COMPOUND_OP(And);
2862 COMPOUND_OP(Xor);
2863 COMPOUND_OP(Or);
2864#undef COMPOUND_OP
2865
John McCalle3027922010-08-25 11:45:40 +00002866 case BO_PtrMemD:
2867 case BO_PtrMemI:
2868 case BO_Mul:
2869 case BO_Div:
2870 case BO_Rem:
2871 case BO_Add:
2872 case BO_Sub:
2873 case BO_Shl:
2874 case BO_Shr:
2875 case BO_LT:
2876 case BO_GT:
2877 case BO_LE:
2878 case BO_GE:
2879 case BO_EQ:
2880 case BO_NE:
2881 case BO_And:
2882 case BO_Xor:
2883 case BO_Or:
2884 case BO_LAnd:
2885 case BO_LOr:
2886 case BO_Assign:
2887 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00002888 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00002889 }
2890
2891 llvm_unreachable("Unhandled compound assignment operator");
2892}