blob: 6ceb2a67900f9271729d7456bd471d72e42e0a2b [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner9fba49a2007-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
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Eli Friedmanccffea92009-01-24 22:38:55 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stumpdb789912009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000030
Chris Lattner9fba49a2007-08-24 05:35:26 +000031using namespace clang;
32using namespace CodeGen;
33using llvm::Value;
34
35//===----------------------------------------------------------------------===//
36// Scalar Expression Emitter
37//===----------------------------------------------------------------------===//
38
39struct BinOpInfo {
40 Value *LHS;
41 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000043 const BinaryOperator *E;
44};
45
46namespace {
47class VISIBILITY_HIDDEN ScalarExprEmitter
48 : public StmtVisitor<ScalarExprEmitter, Value*> {
49 CodeGenFunction &CGF;
Daniel Dunbard916e6e2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000051
Chris Lattner9fba49a2007-08-24 05:35:26 +000052public:
53
Chris Lattnercbfb5512008-03-01 08:45:05 +000054 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbarf1f7f192008-08-20 00:28:19 +000055 Builder(CGF.Builder) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000056 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000057
58 //===--------------------------------------------------------------------===//
59 // Utilities
60 //===--------------------------------------------------------------------===//
61
62 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
63 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
64
65 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000066 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000067 }
68
69 /// EmitLoadOfLValue - Given an expression with complex type that represents a
70 /// value l-value, this method emits the address of the l-value, then loads
71 /// and returns the result.
72 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000073 return EmitLoadOfLValue(EmitLValue(E), E->getType());
74 }
75
Chris Lattnerd8d44222007-08-26 16:42:57 +000076 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000077 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000078 Value *EmitConversionToBool(Value *Src, QualType DstTy);
79
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080 /// EmitScalarConversion - Emit a conversion from the specified type to the
81 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000082 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
83
84 /// EmitComplexToScalarConversion - Emit a conversion from the specified
85 /// complex type to the specified destination type, where the destination
86 /// type is an LLVM scalar type.
87 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
88 QualType SrcTy, QualType DstTy);
Mike Stump4eb81dc2009-02-12 18:29:15 +000089
Chris Lattner9fba49a2007-08-24 05:35:26 +000090 //===--------------------------------------------------------------------===//
91 // Visitor Methods
92 //===--------------------------------------------------------------------===//
93
94 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000095 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000096 assert(0 && "Stmt can't have complex result type!");
97 return 0;
98 }
99 Value *VisitExpr(Expr *S);
100 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
101
102 // Leaves.
103 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
104 return llvm::ConstantInt::get(E->getValue());
105 }
106 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000107 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 }
109 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000112 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
114 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000115 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
116 return llvm::Constant::getNullValue(ConvertType(E->getType()));
117 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000118 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
119 return llvm::Constant::getNullValue(ConvertType(E->getType()));
120 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000121 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
122 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000123 CGF.getContext().typesAreCompatible(
124 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000125 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000126 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000127 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000128 llvm::Value *V =
129 llvm::ConstantInt::get(llvm::Type::Int32Ty,
130 CGF.GetIDForAddrOfLabel(E->getLabel()));
131
132 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000133 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000134
135 // l-values.
136 Value *VisitDeclRefExpr(DeclRefExpr *E) {
137 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
138 return llvm::ConstantInt::get(EC->getInitVal());
139 return EmitLoadOfLValue(E);
140 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000141 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
142 return CGF.EmitObjCSelectorExpr(E);
143 }
144 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
145 return CGF.EmitObjCProtocolExpr(E);
146 }
147 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
148 return EmitLoadOfLValue(E);
149 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000150 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000151 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000152 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000153 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
154 return EmitLoadOfLValue(E);
155 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000156 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
157 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000158 }
159
Chris Lattner9fba49a2007-08-24 05:35:26 +0000160 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000161 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000162 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000163 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000164 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
165 return EmitLoadOfLValue(E);
166 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000167 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerc5d32632009-02-24 22:18:39 +0000168 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
169 return EmitLValue(E).getAddress();
170 }
171
Chris Lattner69909292008-08-10 01:53:14 +0000172 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000173
174 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000175 unsigned NumInitElements = E->getNumInits();
176
Douglas Gregor9fddded2009-01-29 19:42:23 +0000177 if (E->hadArrayRangeDesignator()) {
178 CGF.ErrorUnsupported(E, "GNU array range designator extension");
179 }
180
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000181 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000182 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
183
184 // We have a scalar in braces. Just use the first element.
185 if (!VType)
186 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000187
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000188 unsigned NumVectorElements = VType->getNumElements();
189 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000190
191 // Emit individual vector element stores.
192 llvm::Value *V = llvm::UndefValue::get(VType);
193
Anders Carlsson323d5682007-12-18 02:45:33 +0000194 // Emit initializers
195 unsigned i;
196 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000197 Value *NewV = Visit(E->getInit(i));
198 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
199 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000200 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000201
202 // Emit remaining default initializers
203 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
204 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
205 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
206 V = Builder.CreateInsertElement(V, NewV, Idx);
207 }
208
Devang Patel32c39832007-10-24 18:05:48 +0000209 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000210 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000211
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000212 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
213 return llvm::Constant::getNullValue(ConvertType(E->getType()));
214 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000215 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmana7ef8e52009-04-20 03:54:15 +0000216 Value *VisitCastExpr(const CastExpr *E) {
217 // Make sure to evaluate VLA bounds now so that we have them for later.
218 if (E->getType()->isVariablyModifiedType())
219 CGF.EmitVLASize(E->getType());
220
Chris Lattner9fba49a2007-08-24 05:35:26 +0000221 return EmitCastExpr(E->getSubExpr(), E->getType());
222 }
223 Value *EmitCastExpr(const Expr *E, QualType T);
224
225 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000226 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000227 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000228
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000229 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000230
Mike Stump2b6933f2009-02-28 09:07:16 +0000231 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000232
Chris Lattner9fba49a2007-08-24 05:35:26 +0000233 // Unary Operators.
234 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
235 Value *VisitUnaryPostDec(const UnaryOperator *E) {
236 return VisitPrePostIncDec(E, false, false);
237 }
238 Value *VisitUnaryPostInc(const UnaryOperator *E) {
239 return VisitPrePostIncDec(E, true, false);
240 }
241 Value *VisitUnaryPreDec(const UnaryOperator *E) {
242 return VisitPrePostIncDec(E, false, true);
243 }
244 Value *VisitUnaryPreInc(const UnaryOperator *E) {
245 return VisitPrePostIncDec(E, true, true);
246 }
247 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
248 return EmitLValue(E->getSubExpr()).getAddress();
249 }
250 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
251 Value *VisitUnaryPlus(const UnaryOperator *E) {
252 return Visit(E->getSubExpr());
253 }
254 Value *VisitUnaryMinus (const UnaryOperator *E);
255 Value *VisitUnaryNot (const UnaryOperator *E);
256 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000257 Value *VisitUnaryReal (const UnaryOperator *E);
258 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000259 Value *VisitUnaryExtension(const UnaryOperator *E) {
260 return Visit(E->getSubExpr());
261 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000262 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson49d4a572009-04-14 16:58:56 +0000263
264 // C++
Chris Lattner3e254fb2008-04-08 04:40:51 +0000265 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
266 return Visit(DAE->getExpr());
267 }
Anders Carlsson49d4a572009-04-14 16:58:56 +0000268 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
269 return CGF.LoadCXXThis();
270 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000271
Anders Carlsson272b5f52009-05-19 04:48:36 +0000272 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
273 // FIXME: Do something with the temporaries!
274 return Visit(E->getSubExpr());
275 }
276
Chris Lattner9fba49a2007-08-24 05:35:26 +0000277 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000278 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000279 if (CGF.getContext().getLangOptions().OverflowChecking
280 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000281 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000282 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
283 }
Mike Stumpdb789912009-04-01 20:28:16 +0000284 /// Create a binary op that checks for overflow.
285 /// Currently only supports +, - and *.
286 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000287 Value *EmitDiv(const BinOpInfo &Ops);
288 Value *EmitRem(const BinOpInfo &Ops);
289 Value *EmitAdd(const BinOpInfo &Ops);
290 Value *EmitSub(const BinOpInfo &Ops);
291 Value *EmitShl(const BinOpInfo &Ops);
292 Value *EmitShr(const BinOpInfo &Ops);
293 Value *EmitAnd(const BinOpInfo &Ops) {
294 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
295 }
296 Value *EmitXor(const BinOpInfo &Ops) {
297 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
298 }
299 Value *EmitOr (const BinOpInfo &Ops) {
300 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
301 }
302
Chris Lattner660e31d2007-08-24 21:00:35 +0000303 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000304 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000305 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
306
307 // Binary operators and binary compound assignment operators.
308#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000309 Value *VisitBin ## OP(const BinaryOperator *E) { \
310 return Emit ## OP(EmitBinOps(E)); \
311 } \
312 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
313 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000314 }
315 HANDLEBINOP(Mul);
316 HANDLEBINOP(Div);
317 HANDLEBINOP(Rem);
318 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000319 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000320 HANDLEBINOP(Shl);
321 HANDLEBINOP(Shr);
322 HANDLEBINOP(And);
323 HANDLEBINOP(Xor);
324 HANDLEBINOP(Or);
325#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000326
Chris Lattner9fba49a2007-08-24 05:35:26 +0000327 // Comparisons.
328 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
329 unsigned SICmpOpc, unsigned FCmpOpc);
330#define VISITCOMP(CODE, UI, SI, FP) \
331 Value *VisitBin##CODE(const BinaryOperator *E) { \
332 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
333 llvm::FCmpInst::FP); }
334 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
335 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
336 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
337 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
338 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
339 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
340#undef VISITCOMP
341
342 Value *VisitBinAssign (const BinaryOperator *E);
343
344 Value *VisitBinLAnd (const BinaryOperator *E);
345 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000346 Value *VisitBinComma (const BinaryOperator *E);
347
348 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000349 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000350 Value *VisitConditionalOperator(const ConditionalOperator *CO);
351 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000352 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000353 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
354 return CGF.EmitObjCStringLiteral(E);
355 }
356};
357} // end anonymous namespace.
358
359//===----------------------------------------------------------------------===//
360// Utilities
361//===----------------------------------------------------------------------===//
362
Chris Lattnerd8d44222007-08-26 16:42:57 +0000363/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000364/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000365Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
366 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
367
368 if (SrcType->isRealFloatingType()) {
369 // Compare against 0.0 for fp scalars.
370 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000371 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
372 }
373
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000374 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000375 "Unknown scalar type to convert");
376
377 // Because of the type rules of C, we often end up computing a logical value,
378 // then zero extending it to int, then wanting it as a logical value again.
379 // Optimize this common case.
380 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
381 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
382 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000383 // If there aren't any more uses, zap the instruction to save space.
384 // Note that there can be more uses, for example if this
385 // is the result of an assignment.
386 if (ZI->use_empty())
387 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000388 return Result;
389 }
390 }
391
392 // Compare against an integer or pointer null.
393 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
394 return Builder.CreateICmpNE(Src, Zero, "tobool");
395}
396
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000397/// EmitScalarConversion - Emit a conversion from the specified type to the
398/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000399Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
400 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000401 SrcType = CGF.getContext().getCanonicalType(SrcType);
402 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000403 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000404
405 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000406
407 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000408 if (DstType->isBooleanType())
409 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000410
411 const llvm::Type *DstTy = ConvertType(DstType);
412
413 // Ignore conversions like int -> uint.
414 if (Src->getType() == DstTy)
415 return Src;
416
Daniel Dunbar238335f2008-08-25 09:51:32 +0000417 // Handle pointer conversions next: pointers can only be converted
418 // to/from other pointers and integers. Check for pointer types in
419 // terms of LLVM, as some native types (like Obj-C id) may map to a
420 // pointer type.
421 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000422 // The source value may be an integer, or a pointer.
423 if (isa<llvm::PointerType>(Src->getType()))
424 return Builder.CreateBitCast(Src, DstTy, "conv");
425 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000426 // First, convert to the correct width so that we control the kind of
427 // extension.
428 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
429 bool InputSigned = SrcType->isSignedIntegerType();
430 llvm::Value* IntResult =
431 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
432 // Then, cast to pointer.
433 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000434 }
435
Daniel Dunbar238335f2008-08-25 09:51:32 +0000436 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000437 // Must be an ptr to int cast.
438 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000439 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000440 }
441
Nate Begemanaf6ed502008-04-18 23:10:10 +0000442 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000443 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
444 // Cast the scalar to element type
445 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
446 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
447
448 // Insert the element in element zero of an undef vector
449 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
450 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
451 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
452
453 // Splat the element across to all elements
454 llvm::SmallVector<llvm::Constant*, 16> Args;
455 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
456 for (unsigned i = 0; i < NumElements; i++)
457 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
458
459 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
460 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
461 return Yay;
462 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000463
Chris Lattner4f025a42008-02-02 04:51:41 +0000464 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000465 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000466 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000467 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000468
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000469 // Finally, we have the arithmetic types: real int/float.
470 if (isa<llvm::IntegerType>(Src->getType())) {
471 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000472 if (isa<llvm::IntegerType>(DstTy))
473 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
474 else if (InputSigned)
475 return Builder.CreateSIToFP(Src, DstTy, "conv");
476 else
477 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000478 }
479
480 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
481 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000482 if (DstType->isSignedIntegerType())
483 return Builder.CreateFPToSI(Src, DstTy, "conv");
484 else
485 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000486 }
487
488 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000489 if (DstTy->getTypeID() < Src->getType()->getTypeID())
490 return Builder.CreateFPTrunc(Src, DstTy, "conv");
491 else
492 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000493}
494
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000495/// EmitComplexToScalarConversion - Emit a conversion from the specified
496/// complex type to the specified destination type, where the destination
497/// type is an LLVM scalar type.
498Value *ScalarExprEmitter::
499EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
500 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000501 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000502 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000503
504 // Handle conversions to bool first, they are special: comparisons against 0.
505 if (DstTy->isBooleanType()) {
506 // Complex != 0 -> (Real != 0) | (Imag != 0)
507 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
508 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
509 return Builder.CreateOr(Src.first, Src.second, "tobool");
510 }
511
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000512 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
513 // the imaginary part of the complex value is discarded and the value of the
514 // real part is converted according to the conversion rules for the
515 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000516 return EmitScalarConversion(Src.first, SrcTy, DstTy);
517}
518
519
Chris Lattner9fba49a2007-08-24 05:35:26 +0000520//===----------------------------------------------------------------------===//
521// Visitor Methods
522//===----------------------------------------------------------------------===//
523
524Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000525 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000526 if (E->getType()->isVoidType())
527 return 0;
528 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
529}
530
Eli Friedmand0e9d092008-05-14 19:38:39 +0000531Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
532 llvm::SmallVector<llvm::Constant*, 32> indices;
533 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
534 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
535 }
536 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
537 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
538 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
539 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
540}
541
Chris Lattner9fba49a2007-08-24 05:35:26 +0000542Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
543 // Emit subscript expressions in rvalue context's. For most cases, this just
544 // loads the lvalue formed by the subscript expr. However, we have to be
545 // careful, because the base of a vector subscript is occasionally an rvalue,
546 // so we can't get it as an lvalue.
547 if (!E->getBase()->getType()->isVectorType())
548 return EmitLoadOfLValue(E);
549
550 // Handle the vector case. The base must be a vector, the index must be an
551 // integer value.
552 Value *Base = Visit(E->getBase());
553 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000554 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedmand4531942009-03-28 03:27:06 +0000555 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
556 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000557 return Builder.CreateExtractElement(Base, Idx, "vecext");
558}
559
560/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
561/// also handle things like function to pointer-to-function decay, and array to
562/// pointer decay.
563Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
564 const Expr *Op = E->getSubExpr();
565
566 // If this is due to array->pointer conversion, emit the array expression as
567 // an l-value.
568 if (Op->getType()->isArrayType()) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000569 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000570
Eli Friedman4a0073b2009-03-28 02:45:41 +0000571 // Note that VLA pointers are always decayed, so we don't need to do
572 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000573 if (!Op->getType()->isVariableArrayType()) {
574 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
575 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
576 ->getElementType()) &&
577 "Expected pointer to array");
578 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000579 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000580
581 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000582 // types as well (e.g. void*) and can be implicitly converted to integer.
583 const llvm::Type *DestTy = ConvertType(E->getType());
584 if (V->getType() != DestTy) {
585 if (isa<llvm::PointerType>(DestTy))
586 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
587 else {
588 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
589 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
590 }
591 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000592 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000594
Chris Lattner9fba49a2007-08-24 05:35:26 +0000595 return EmitCastExpr(Op, E->getType());
596}
597
598
599// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
600// have to handle a more broad range of conversions than explicit casts, as they
601// handle things like function to ptr-to-function decay etc.
602Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000603 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000604
605 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000606 Value *Src = Visit(const_cast<Expr*>(E));
607
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000608 // Use EmitScalarConversion to perform the conversion.
609 return EmitScalarConversion(Src, E->getType(), DestTy);
610 }
Chris Lattner77288792008-02-16 23:55:16 +0000611
Chris Lattnerde0908b2008-04-04 16:54:41 +0000612 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000613 // Handle cases where the source is a complex type.
614 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
615 DestTy);
616 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000617
Chris Lattner77288792008-02-16 23:55:16 +0000618 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
619 // evaluate the result and return.
620 CGF.EmitAggExpr(E, 0, false);
621 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000622}
623
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000624Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000625 return CGF.EmitCompoundStmt(*E->getSubStmt(),
626 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000627}
628
Mike Stump2b6933f2009-02-28 09:07:16 +0000629Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
630 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000631}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000632
Chris Lattner9fba49a2007-08-24 05:35:26 +0000633//===----------------------------------------------------------------------===//
634// Unary Operators
635//===----------------------------------------------------------------------===//
636
637Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000638 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000639 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000640 QualType ValTy = E->getSubExpr()->getType();
641 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000642
643 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000644
645 if (ValTy->isPointerType() &&
646 ValTy->getAsPointerType()->isVariableArrayType()) {
647 // The amount of the addition/subtraction needs to account for the VLA size
648 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
649 }
650
Chris Lattner9fba49a2007-08-24 05:35:26 +0000651 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000652 if (const llvm::PointerType *PT =
653 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner8360c612009-03-18 04:25:13 +0000654 llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
655 if (!isa<llvm::FunctionType>(PT->getElementType())) {
656 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
657 } else {
658 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
659 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
660 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
661 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
662 }
Chris Lattner49083172009-02-11 07:40:06 +0000663 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
664 // Bool++ is an interesting case, due to promotion rules, we get:
665 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
666 // Bool = ((int)Bool+1) != 0
667 // An interesting aspect of this is that increment is always true.
668 // Decrement does not have this property.
669 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner0dc11f62007-08-26 05:10:16 +0000670 } else {
671 // Add the inc/dec to the real part.
672 if (isa<llvm::IntegerType>(InVal->getType()))
673 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000674 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000675 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000676 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000677 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000678 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000679 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000680 else {
681 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000682 bool ignored;
683 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
684 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000685 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000686 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000687 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
688 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000689
690 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000691 if (LV.isBitfield())
692 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
693 &NextVal);
694 else
695 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000696
697 // If this is a postinc, return the value read from memory, otherwise use the
698 // updated value.
699 return isPre ? NextVal : InVal;
700}
701
702
703Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
704 Value *Op = Visit(E->getSubExpr());
705 return Builder.CreateNeg(Op, "neg");
706}
707
708Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
709 Value *Op = Visit(E->getSubExpr());
710 return Builder.CreateNot(Op, "neg");
711}
712
713Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
714 // Compare operand to zero.
715 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
716
717 // Invert value.
718 // TODO: Could dynamically modify easy computations here. For example, if
719 // the operand is an icmp ne, turn into icmp eq.
720 BoolVal = Builder.CreateNot(BoolVal, "lnot");
721
722 // ZExt result to int.
723 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
724}
725
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000726/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
727/// argument of the sizeof expression as an integer.
728Value *
729ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000730 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000731 if (E->isSizeOf()) {
732 if (const VariableArrayType *VAT =
733 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
734 if (E->isArgumentType()) {
735 // sizeof(type) - make sure to emit the VLA size.
736 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000737 } else {
738 // C99 6.5.3.4p2: If the argument is an expression of type
739 // VLA, it is evaluated.
740 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000741 }
Anders Carlssond309f572009-01-30 16:41:04 +0000742
Anders Carlsson8f30de92009-02-05 19:43:10 +0000743 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000744 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000745 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000746
747 // If this isn't sizeof(vla), the result must be constant; use the
748 // constant folding logic so we don't have to duplicate it here.
749 Expr::EvalResult Result;
750 E->Evaluate(Result, CGF.getContext());
751 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000752}
753
Chris Lattner01211af2007-08-24 21:20:17 +0000754Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
755 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000756 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000757 return CGF.EmitComplexExpr(Op).first;
758 return Visit(Op);
759}
760Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
761 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000762 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000763 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000764
765 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
766 // effects are evaluated.
767 CGF.EmitScalarExpr(Op);
768 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000769}
770
Anders Carlsson52774ad2008-01-29 15:56:48 +0000771Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
772{
Eli Friedman342d9432009-02-27 06:44:11 +0000773 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000774 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000775 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000776}
Chris Lattner01211af2007-08-24 21:20:17 +0000777
Chris Lattner9fba49a2007-08-24 05:35:26 +0000778//===----------------------------------------------------------------------===//
779// Binary Operators
780//===----------------------------------------------------------------------===//
781
782BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
783 BinOpInfo Result;
784 Result.LHS = Visit(E->getLHS());
785 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000786 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000787 Result.E = E;
788 return Result;
789}
790
Chris Lattner0d965302007-08-26 21:41:21 +0000791Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000792 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
793 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
794
795 BinOpInfo OpInfo;
796
Eli Friedman3cd92882009-03-28 01:22:36 +0000797 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000798 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000799 // it's a tad complicated to do that... I'm leaving it out for now.
800 // (Note that we do actually need the imaginary part of the RHS for
801 // multiplication and division.)
802 CGF.ErrorUnsupported(E, "complex compound assignment");
803 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
804 }
805
806 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000807 LValue LHSLV = EmitLValue(E->getLHS());
808 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000809 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
810 E->getComputationLHSType());
811 // Emit the RHS.
812 OpInfo.RHS = Visit(E->getRHS());
813 OpInfo.Ty = E->getComputationResultType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000814 OpInfo.E = E;
815
816 // Expand the binary operator.
817 Value *Result = (this->*Func)(OpInfo);
818
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000819 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000820 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
821
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000822 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000823 // handled specially because the result is altered by the store,
824 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
825 // the left operand after the assignment...'.
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000826 if (LHSLV.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000827 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
828 &Result);
829 else
830 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
831
Chris Lattner660e31d2007-08-24 21:00:35 +0000832 return Result;
833}
834
835
Chris Lattner9fba49a2007-08-24 05:35:26 +0000836Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000837 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000838 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000839 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000840 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
841 else
842 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
843}
844
845Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
846 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000847 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000848 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
849 else
850 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
851}
852
Mike Stumpdb789912009-04-01 20:28:16 +0000853Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
854 unsigned IID;
855 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000856
Mike Stumpf71b7742009-04-02 18:15:54 +0000857 switch (Ops.E->getOpcode()) {
858 case BinaryOperator::Add:
859 case BinaryOperator::AddAssign:
860 OpID = 1;
861 IID = llvm::Intrinsic::sadd_with_overflow;
862 break;
863 case BinaryOperator::Sub:
864 case BinaryOperator::SubAssign:
865 OpID = 2;
866 IID = llvm::Intrinsic::ssub_with_overflow;
867 break;
868 case BinaryOperator::Mul:
869 case BinaryOperator::MulAssign:
870 OpID = 3;
871 IID = llvm::Intrinsic::smul_with_overflow;
872 break;
873 default:
874 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000875 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000876 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000877 OpID <<= 1;
878 OpID |= 1;
879
Mike Stumpdb789912009-04-01 20:28:16 +0000880 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
881
882 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
883
884 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
885 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
886 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
887
888 // Branch in case of overflow.
889 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
890 llvm::BasicBlock *overflowBB =
891 CGF.createBasicBlock("overflow", CGF.CurFn);
892 llvm::BasicBlock *continueBB =
893 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
894
895 Builder.CreateCondBr(overflow, overflowBB, continueBB);
896
897 // Handle overflow
898
899 Builder.SetInsertPoint(overflowBB);
900
901 // Handler is:
902 // long long *__overflow_handler)(long long a, long long b, char op,
903 // char width)
904 std::vector<const llvm::Type*> handerArgTypes;
905 handerArgTypes.push_back(llvm::Type::Int64Ty);
906 handerArgTypes.push_back(llvm::Type::Int64Ty);
907 handerArgTypes.push_back(llvm::Type::Int8Ty);
908 handerArgTypes.push_back(llvm::Type::Int8Ty);
909 llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
910 handerArgTypes, false);
911 llvm::Value *handlerFunction =
912 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
913 llvm::PointerType::getUnqual(handlerTy));
914 handlerFunction = Builder.CreateLoad(handlerFunction);
915
916 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
917 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
918 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
919 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
920 llvm::ConstantInt::get(llvm::Type::Int8Ty,
921 cast<llvm::IntegerType>(opTy)->getBitWidth()));
922
923 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
924
925 Builder.CreateBr(continueBB);
926
927 // Set up the continuation
928 Builder.SetInsertPoint(continueBB);
929 // Get the correct result
930 llvm::PHINode *phi = Builder.CreatePHI(opTy);
931 phi->reserveOperandSpace(2);
932 phi->addIncoming(result, initialBB);
933 phi->addIncoming(handlerResult, overflowBB);
934
935 return phi;
936}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000937
938Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +0000939 if (!Ops.Ty->isPointerType()) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000940 if (CGF.getContext().getLangOptions().OverflowChecking
941 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000942 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000943 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +0000944 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000945
946 if (Ops.Ty->getAsPointerType()->isVariableArrayType()) {
947 // The amount of the addition needs to account for the VLA size
948 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
949 }
Chris Lattner17c0cb02008-01-03 06:36:51 +0000950 Value *Ptr, *Idx;
951 Expr *IdxExp;
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000952 const PointerType *PT;
953 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000954 Ptr = Ops.LHS;
955 Idx = Ops.RHS;
956 IdxExp = Ops.E->getRHS();
957 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000958 PT = Ops.E->getRHS()->getType()->getAsPointerType();
959 assert(PT && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +0000960 Ptr = Ops.RHS;
961 Idx = Ops.LHS;
962 IdxExp = Ops.E->getLHS();
963 }
964
965 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +0000966 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000967 // Zero or sign extend the pointer value based on whether the index is
968 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +0000969 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000970 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000971 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
972 else
973 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
974 }
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000975
Daniel Dunbar6864c0d2009-04-25 05:08:32 +0000976 const QualType ElementType = PT->getPointeeType();
977 // Handle interface types, which are not represented with a concrete
978 // type.
979 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
980 llvm::Value *InterfaceSize =
981 llvm::ConstantInt::get(Idx->getType(),
982 CGF.getContext().getTypeSize(OIT) / 8);
983 Idx = Builder.CreateMul(Idx, InterfaceSize);
984 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
985 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
986 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
987 return Builder.CreateBitCast(Res, Ptr->getType());
988 }
989
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000990 // Explicitly handle GNU void* and function pointer arithmetic
991 // extensions. The GNU void* casts amount to no-ops since our void*
992 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000993 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
994 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
995 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +0000996 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000997 return Builder.CreateBitCast(Res, Ptr->getType());
998 }
Chris Lattner17c0cb02008-01-03 06:36:51 +0000999
1000 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001001}
1002
1003Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001004 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001005 if (CGF.getContext().getLangOptions().OverflowChecking
1006 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001007 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001008 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001009 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001010
Eli Friedman4a0073b2009-03-28 02:45:41 +00001011 if (Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
1012 // The amount of the addition needs to account for the VLA size for
1013 // ptr-int
1014 // The amount of the division needs to account for the VLA size for
1015 // ptr-ptr.
1016 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1017 }
1018
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001019 const QualType LHSType = Ops.E->getLHS()->getType();
1020 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001021 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1022 // pointer - int
1023 Value *Idx = Ops.RHS;
1024 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001025 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001026 // Zero or sign extend the pointer value based on whether the index is
1027 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001028 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001029 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1030 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1031 else
1032 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1033 }
1034 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001035
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001036 // Handle interface types, which are not represented with a concrete
1037 // type.
1038 if (const ObjCInterfaceType *OIT =
1039 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1040 llvm::Value *InterfaceSize =
1041 llvm::ConstantInt::get(Idx->getType(),
1042 CGF.getContext().getTypeSize(OIT) / 8);
1043 Idx = Builder.CreateMul(Idx, InterfaceSize);
1044 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1045 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1046 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1047 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1048 }
1049
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001050 // Explicitly handle GNU void* and function pointer arithmetic
1051 // extensions. The GNU void* casts amount to no-ops since our
1052 // void* type is i8*, but this is future proof.
1053 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1054 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1055 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1056 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1057 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1058 }
1059
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001060 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001061 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001062 // pointer - pointer
1063 Value *LHS = Ops.LHS;
1064 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001065
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001066 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001067
Chris Lattner6d2e3492009-02-11 07:21:43 +00001068 // Handle GCC extension for pointer arithmetic on void* and function pointer
1069 // types.
1070 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001071 ElementSize = 1;
1072 } else {
1073 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1074 }
1075
1076 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1077 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1078 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1079 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1080
Chris Lattner6d2e3492009-02-11 07:21:43 +00001081 // Optimize out the shift for element size of 1.
1082 if (ElementSize == 1)
1083 return BytesBetween;
1084
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001085 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1086 // remainder. As such, we handle common power-of-two cases here to generate
1087 // better code. See PR2247.
1088 if (llvm::isPowerOf2_64(ElementSize)) {
1089 Value *ShAmt =
1090 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1091 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1092 }
1093
1094 // Otherwise, do a full sdiv.
1095 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1096 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001097 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001098}
1099
1100Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1101 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1102 // RHS to the same size as the LHS.
1103 Value *RHS = Ops.RHS;
1104 if (Ops.LHS->getType() != RHS->getType())
1105 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1106
1107 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1108}
1109
1110Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1111 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1112 // RHS to the same size as the LHS.
1113 Value *RHS = Ops.RHS;
1114 if (Ops.LHS->getType() != RHS->getType())
1115 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1116
Chris Lattner660e31d2007-08-24 21:00:35 +00001117 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001118 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1119 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1120}
1121
1122Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1123 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001124 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001125 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +00001126 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001127 Value *LHS = Visit(E->getLHS());
1128 Value *RHS = Visit(E->getRHS());
1129
1130 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001131 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001132 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001133 } else if (LHSTy->isSignedIntegerType()) {
1134 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001135 LHS, RHS, "cmp");
1136 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001137 // Unsigned integers and pointers.
1138 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001139 LHS, RHS, "cmp");
1140 }
Nate Begeman1591bc52008-07-25 20:16:05 +00001141 } else if (LHSTy->isVectorType()) {
1142 Value *LHS = Visit(E->getLHS());
1143 Value *RHS = Visit(E->getRHS());
1144
1145 if (LHS->getType()->isFPOrFPVector()) {
1146 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1147 LHS, RHS, "cmp");
1148 } else if (LHSTy->isUnsignedIntegerType()) {
1149 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1150 LHS, RHS, "cmp");
1151 } else {
1152 // Signed integers and pointers.
1153 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1154 LHS, RHS, "cmp");
1155 }
1156 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001157 } else {
1158 // Complex Comparison: can only be an equality comparison.
1159 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1160 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1161
Chris Lattnerc154ac12008-07-26 22:37:01 +00001162 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001163
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001164 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001165 if (CETy->isRealFloatingType()) {
1166 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1167 LHS.first, RHS.first, "cmp.r");
1168 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1169 LHS.second, RHS.second, "cmp.i");
1170 } else {
1171 // Complex comparisons can only be equality comparisons. As such, signed
1172 // and unsigned opcodes are the same.
1173 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1174 LHS.first, RHS.first, "cmp.r");
1175 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1176 LHS.second, RHS.second, "cmp.i");
1177 }
1178
1179 if (E->getOpcode() == BinaryOperator::EQ) {
1180 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1181 } else {
1182 assert(E->getOpcode() == BinaryOperator::NE &&
1183 "Complex comparison other than == or != ?");
1184 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1185 }
1186 }
Nuno Lopes92577002009-01-11 23:22:37 +00001187
1188 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001189}
1190
1191Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1192 LValue LHS = EmitLValue(E->getLHS());
1193 Value *RHS = Visit(E->getRHS());
1194
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001195 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001196 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1197 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001198 // the assignment...'.
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001199 if (LHS.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001200 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1201 &RHS);
1202 else
1203 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbare6c31752008-08-29 08:11:39 +00001204
Chris Lattner9fba49a2007-08-24 05:35:26 +00001205 // Return the RHS.
1206 return RHS;
1207}
1208
1209Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001210 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1211 // If we have 1 && X, just emit X without inserting the control flow.
1212 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1213 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001214 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1215 // ZExt result to int.
1216 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1217 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001218
1219 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1220 if (!CGF.ContainsLabel(E->getRHS()))
1221 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001222 }
1223
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001224 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1225 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001226
Chris Lattner7f80bb32008-11-12 08:38:24 +00001227 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1228 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1229
1230 // Any edges into the ContBlock are now from an (indeterminate number of)
1231 // edges from this first condition. All of these values will be false. Start
1232 // setting up the PHI node in the Cont Block for this.
1233 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1234 PN->reserveOperandSpace(2); // Normal case, two inputs.
1235 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1236 PI != PE; ++PI)
1237 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001238
1239 CGF.EmitBlock(RHSBlock);
1240 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1241
1242 // Reaquire the RHS block, as there may be subblocks inserted.
1243 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001244
1245 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1246 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001247 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001248 PN->addIncoming(RHSCond, RHSBlock);
1249
1250 // ZExt result to int.
1251 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1252}
1253
1254Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001255 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1256 // If we have 0 || X, just emit X without inserting the control flow.
1257 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1258 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001259 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1260 // ZExt result to int.
1261 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1262 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001263
Eli Friedmanea137cd2008-12-02 16:02:46 +00001264 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001265 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001266 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001267 }
1268
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001269 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1270 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001271
Chris Lattner7f80bb32008-11-12 08:38:24 +00001272 // Branch on the LHS first. If it is true, go to the success (cont) block.
1273 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1274
1275 // Any edges into the ContBlock are now from an (indeterminate number of)
1276 // edges from this first condition. All of these values will be true. Start
1277 // setting up the PHI node in the Cont Block for this.
1278 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1279 PN->reserveOperandSpace(2); // Normal case, two inputs.
1280 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1281 PI != PE; ++PI)
1282 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1283
1284 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001285 CGF.EmitBlock(RHSBlock);
1286 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1287
1288 // Reaquire the RHS block, as there may be subblocks inserted.
1289 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001290
Chris Lattner7f80bb32008-11-12 08:38:24 +00001291 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1292 // into the phi node for the edge with the value of RHSCond.
1293 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001294 PN->addIncoming(RHSCond, RHSBlock);
1295
1296 // ZExt result to int.
1297 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1298}
1299
1300Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1301 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001302 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001303 return Visit(E->getRHS());
1304}
1305
1306//===----------------------------------------------------------------------===//
1307// Other Operators
1308//===----------------------------------------------------------------------===//
1309
Chris Lattner504a5282008-11-12 08:55:54 +00001310/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1311/// expression is cheap enough and side-effect-free enough to evaluate
1312/// unconditionally instead of conditionally. This is used to convert control
1313/// flow into selects in some cases.
1314static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1315 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1316 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1317
1318 // TODO: Allow anything we can constant fold to an integer or fp constant.
1319 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1320 isa<FloatingLiteral>(E))
1321 return true;
1322
1323 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1324 // X and Y are local variables.
1325 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1326 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1327 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1328 return true;
1329
1330 return false;
1331}
1332
1333
Chris Lattner9fba49a2007-08-24 05:35:26 +00001334Value *ScalarExprEmitter::
1335VisitConditionalOperator(const ConditionalOperator *E) {
Chris Lattner3d6606b2008-11-12 08:04:58 +00001336 // If the condition constant folds and can be elided, try to avoid emitting
1337 // the condition and the dead arm.
1338 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001339 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001340 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001341 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001342
1343 // If the dead side doesn't have labels we need, and if the Live side isn't
1344 // the gnu missing ?: extension (which we could handle, but don't bother
1345 // to), just emit the Live part.
1346 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1347 Live) // Live part isn't missing.
1348 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001349 }
1350
Chris Lattner504a5282008-11-12 08:55:54 +00001351
1352 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1353 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001354 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001355 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1356 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1357 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1358 llvm::Value *LHS = Visit(E->getLHS());
1359 llvm::Value *RHS = Visit(E->getRHS());
1360 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1361 }
1362
1363
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001364 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1365 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001366 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001367 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001368
Chris Lattner86031712009-02-13 23:35:32 +00001369 // If we don't have the GNU missing condition extension, emit a branch on
1370 // bool the normal way.
1371 if (E->getLHS()) {
1372 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1373 // the branch on bool.
1374 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1375 } else {
1376 // Otherwise, for the ?: extension, evaluate the conditional and then
1377 // convert it to bool the hard way. We do this explicitly because we need
1378 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001379 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001380
1381 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1382 // if there are no extra uses (an optimization). Inhibit this by making an
1383 // extra dead use, because we're going to add a use of CondVal later. We
1384 // don't use the builder for this, because we don't want it to get optimized
1385 // away. This leaves dead code, but the ?: extension isn't common.
1386 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1387 Builder.GetInsertBlock());
1388
Chris Lattner67e22462008-11-12 08:08:13 +00001389 Value *CondBoolVal =
1390 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1391 CGF.getContext().BoolTy);
1392 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001393 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001394
1395 CGF.EmitBlock(LHSBlock);
1396
1397 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001398 Value *LHS;
1399 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001400 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001401 else // Perform promotions, to handle cases like "short ?: int"
1402 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1403
Chris Lattner9fba49a2007-08-24 05:35:26 +00001404 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001405 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001406
1407 CGF.EmitBlock(RHSBlock);
1408
Eli Friedmance8d7032008-05-16 20:38:39 +00001409 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001410 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001411 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001412
1413 CGF.EmitBlock(ContBlock);
1414
Nuno Lopesb62ff242008-06-04 19:15:45 +00001415 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001416 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1417 return 0;
1418 }
1419
Chris Lattner9fba49a2007-08-24 05:35:26 +00001420 // Create a PHI node for the real part.
1421 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1422 PN->reserveOperandSpace(2);
1423 PN->addIncoming(LHS, LHSBlock);
1424 PN->addIncoming(RHS, RHSBlock);
1425 return PN;
1426}
1427
1428Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001429 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001430}
1431
Chris Lattner307da022007-11-30 17:56:23 +00001432Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001433 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001434 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1435
1436 // If EmitVAArg fails, we fall back to the LLVM instruction.
1437 if (!ArgPtr)
1438 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1439
Anders Carlsson285611e2008-11-04 05:30:00 +00001440 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001441}
1442
Mike Stump4eb81dc2009-02-12 18:29:15 +00001443Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001444 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001445}
1446
Chris Lattner9fba49a2007-08-24 05:35:26 +00001447//===----------------------------------------------------------------------===//
1448// Entry Point into this File
1449//===----------------------------------------------------------------------===//
1450
1451/// EmitComplexExpr - Emit the computation of the specified expression of
1452/// complex type, ignoring the result.
1453Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1454 assert(E && !hasAggregateLLVMType(E->getType()) &&
1455 "Invalid scalar expression to emit");
1456
1457 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1458}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001459
1460/// EmitScalarConversion - Emit a conversion from the specified type to the
1461/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001462Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1463 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001464 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1465 "Invalid scalar expression to emit");
1466 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1467}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001468
1469/// EmitComplexToScalarConversion - Emit a conversion from the specified
1470/// complex type to the specified destination type, where the destination
1471/// type is an LLVM scalar type.
1472Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1473 QualType SrcTy,
1474 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001475 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001476 "Invalid complex -> scalar conversion");
1477 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1478 DstTy);
1479}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001480
1481Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1482 assert(V1->getType() == V2->getType() &&
1483 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001484 unsigned NumElements =
1485 cast<llvm::VectorType>(V1->getType())->getNumElements();
1486
1487 va_list va;
1488 va_start(va, V2);
1489
1490 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001491 for (unsigned i = 0; i < NumElements; i++) {
1492 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001493 assert(n >= 0 && n < (int)NumElements * 2 &&
1494 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001495 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1496 }
1497
1498 const char *Name = va_arg(va, const char *);
1499 va_end(va);
1500
1501 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1502
1503 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1504}
1505
Anders Carlsson68b8be92007-12-15 21:23:30 +00001506llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001507 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001508 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001509 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001510
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001511 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001512 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001513 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001514 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001515 }
1516
1517 return Vec;
1518}