blob: ce49cb20d3567996a27e70d7d00d55b73706baeb [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"
16#include "clang/AST/AST.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000018#include "llvm/Constants.h"
19#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000020#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000021#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000022#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000023#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000024
Chris Lattner9fba49a2007-08-24 05:35:26 +000025using namespace clang;
26using namespace CodeGen;
27using llvm::Value;
28
29//===----------------------------------------------------------------------===//
30// Scalar Expression Emitter
31//===----------------------------------------------------------------------===//
32
33struct BinOpInfo {
34 Value *LHS;
35 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000036 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000037 const BinaryOperator *E;
38};
39
40namespace {
41class VISIBILITY_HIDDEN ScalarExprEmitter
42 : public StmtVisitor<ScalarExprEmitter, Value*> {
43 CodeGenFunction &CGF;
Chris Lattner676bf212008-04-13 07:32:11 +000044 llvm::IRBuilder &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000045 CGObjCRuntime *Runtime;
46
Chris Lattner9fba49a2007-08-24 05:35:26 +000047public:
48
Chris Lattnercbfb5512008-03-01 08:45:05 +000049 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
50 Builder(CGF.Builder),
51 Runtime(CGF.CGM.getObjCRuntime()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000052 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000053
54 //===--------------------------------------------------------------------===//
55 // Utilities
56 //===--------------------------------------------------------------------===//
57
58 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
59 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
60
61 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000062 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000063 }
64
65 /// EmitLoadOfLValue - Given an expression with complex type that represents a
66 /// value l-value, this method emits the address of the l-value, then loads
67 /// and returns the result.
68 Value *EmitLoadOfLValue(const Expr *E) {
69 // FIXME: Volatile
70 return EmitLoadOfLValue(EmitLValue(E), E->getType());
71 }
72
Chris Lattnerd8d44222007-08-26 16:42:57 +000073 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000074 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000075 Value *EmitConversionToBool(Value *Src, QualType DstTy);
76
Chris Lattner4e05d1e2007-08-26 06:48:56 +000077 /// EmitScalarConversion - Emit a conversion from the specified type to the
78 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000079 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
80
81 /// EmitComplexToScalarConversion - Emit a conversion from the specified
82 /// complex type to the specified destination type, where the destination
83 /// type is an LLVM scalar type.
84 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
85 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000086
Chris Lattner9fba49a2007-08-24 05:35:26 +000087 //===--------------------------------------------------------------------===//
88 // Visitor Methods
89 //===--------------------------------------------------------------------===//
90
91 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000092 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000093 assert(0 && "Stmt can't have complex result type!");
94 return 0;
95 }
96 Value *VisitExpr(Expr *S);
97 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
98
99 // Leaves.
100 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
101 return llvm::ConstantInt::get(E->getValue());
102 }
103 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000104 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000105 }
106 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
107 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
108 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000109 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000112 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000114 CGF.getContext().typesAreCompatible(
115 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000116 }
117 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
118 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
119 }
120
121 // l-values.
122 Value *VisitDeclRefExpr(DeclRefExpr *E) {
123 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
124 return llvm::ConstantInt::get(EC->getInitVal());
125 return EmitLoadOfLValue(E);
126 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000127 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000128 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000129 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000130 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000131 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000132 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000133 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000134 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
135 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000136
137 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000138 unsigned NumInitElements = E->getNumInits();
139
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000140 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000141 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
142
143 // We have a scalar in braces. Just use the first element.
144 if (!VType)
145 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000146
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000147 unsigned NumVectorElements = VType->getNumElements();
148 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000149
150 // Emit individual vector element stores.
151 llvm::Value *V = llvm::UndefValue::get(VType);
152
Anders Carlsson323d5682007-12-18 02:45:33 +0000153 // Emit initializers
154 unsigned i;
155 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000156 Value *NewV = Visit(E->getInit(i));
157 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
158 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000159 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000160
161 // Emit remaining default initializers
162 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
163 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
164 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
165 V = Builder.CreateInsertElement(V, NewV, Idx);
166 }
167
Devang Patel32c39832007-10-24 18:05:48 +0000168 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000169 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000170
Chris Lattner9fba49a2007-08-24 05:35:26 +0000171 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
172 Value *VisitCastExpr(const CastExpr *E) {
173 return EmitCastExpr(E->getSubExpr(), E->getType());
174 }
175 Value *EmitCastExpr(const Expr *E, QualType T);
176
177 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000178 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000179 }
180
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000181 Value *VisitStmtExpr(const StmtExpr *E);
182
Chris Lattner9fba49a2007-08-24 05:35:26 +0000183 // Unary Operators.
184 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
185 Value *VisitUnaryPostDec(const UnaryOperator *E) {
186 return VisitPrePostIncDec(E, false, false);
187 }
188 Value *VisitUnaryPostInc(const UnaryOperator *E) {
189 return VisitPrePostIncDec(E, true, false);
190 }
191 Value *VisitUnaryPreDec(const UnaryOperator *E) {
192 return VisitPrePostIncDec(E, false, true);
193 }
194 Value *VisitUnaryPreInc(const UnaryOperator *E) {
195 return VisitPrePostIncDec(E, true, true);
196 }
197 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
198 return EmitLValue(E->getSubExpr()).getAddress();
199 }
200 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
201 Value *VisitUnaryPlus(const UnaryOperator *E) {
202 return Visit(E->getSubExpr());
203 }
204 Value *VisitUnaryMinus (const UnaryOperator *E);
205 Value *VisitUnaryNot (const UnaryOperator *E);
206 Value *VisitUnaryLNot (const UnaryOperator *E);
207 Value *VisitUnarySizeOf (const UnaryOperator *E) {
208 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
209 }
210 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
211 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
212 }
213 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000214 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000215 Value *VisitUnaryReal (const UnaryOperator *E);
216 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000217 Value *VisitUnaryExtension(const UnaryOperator *E) {
218 return Visit(E->getSubExpr());
219 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000220 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000221 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
222 return Visit(DAE->getExpr());
223 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000224
Chris Lattner9fba49a2007-08-24 05:35:26 +0000225 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000226 Value *EmitMul(const BinOpInfo &Ops) {
227 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
228 }
229 Value *EmitDiv(const BinOpInfo &Ops);
230 Value *EmitRem(const BinOpInfo &Ops);
231 Value *EmitAdd(const BinOpInfo &Ops);
232 Value *EmitSub(const BinOpInfo &Ops);
233 Value *EmitShl(const BinOpInfo &Ops);
234 Value *EmitShr(const BinOpInfo &Ops);
235 Value *EmitAnd(const BinOpInfo &Ops) {
236 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
237 }
238 Value *EmitXor(const BinOpInfo &Ops) {
239 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
240 }
241 Value *EmitOr (const BinOpInfo &Ops) {
242 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
243 }
244
Chris Lattner660e31d2007-08-24 21:00:35 +0000245 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000246 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000247 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
248
249 // Binary operators and binary compound assignment operators.
250#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000251 Value *VisitBin ## OP(const BinaryOperator *E) { \
252 return Emit ## OP(EmitBinOps(E)); \
253 } \
254 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
255 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000256 }
257 HANDLEBINOP(Mul);
258 HANDLEBINOP(Div);
259 HANDLEBINOP(Rem);
260 HANDLEBINOP(Add);
261 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
262 HANDLEBINOP(Shl);
263 HANDLEBINOP(Shr);
264 HANDLEBINOP(And);
265 HANDLEBINOP(Xor);
266 HANDLEBINOP(Or);
267#undef HANDLEBINOP
268 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000269 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000270 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
271 }
272
Chris Lattner9fba49a2007-08-24 05:35:26 +0000273 // Comparisons.
274 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
275 unsigned SICmpOpc, unsigned FCmpOpc);
276#define VISITCOMP(CODE, UI, SI, FP) \
277 Value *VisitBin##CODE(const BinaryOperator *E) { \
278 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
279 llvm::FCmpInst::FP); }
280 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
281 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
282 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
283 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
284 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
285 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
286#undef VISITCOMP
287
288 Value *VisitBinAssign (const BinaryOperator *E);
289
290 Value *VisitBinLAnd (const BinaryOperator *E);
291 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000292 Value *VisitBinComma (const BinaryOperator *E);
293
294 // Other Operators.
295 Value *VisitConditionalOperator(const ConditionalOperator *CO);
296 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000297 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000298 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000299 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
300 return CGF.EmitObjCStringLiteral(E);
301 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000302 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000303};
304} // end anonymous namespace.
305
306//===----------------------------------------------------------------------===//
307// Utilities
308//===----------------------------------------------------------------------===//
309
Chris Lattnerd8d44222007-08-26 16:42:57 +0000310/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000311/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000312Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
313 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
314
315 if (SrcType->isRealFloatingType()) {
316 // Compare against 0.0 for fp scalars.
317 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000318 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
319 }
320
321 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
322 "Unknown scalar type to convert");
323
324 // Because of the type rules of C, we often end up computing a logical value,
325 // then zero extending it to int, then wanting it as a logical value again.
326 // Optimize this common case.
327 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
328 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
329 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000330 // If there aren't any more uses, zap the instruction to save space.
331 // Note that there can be more uses, for example if this
332 // is the result of an assignment.
333 if (ZI->use_empty())
334 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000335 return Result;
336 }
337 }
338
339 // Compare against an integer or pointer null.
340 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
341 return Builder.CreateICmpNE(Src, Zero, "tobool");
342}
343
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000344/// EmitScalarConversion - Emit a conversion from the specified type to the
345/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000346Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
347 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000348 SrcType = SrcType.getCanonicalType();
349 DstType = DstType.getCanonicalType();
350 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000351
352 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000353
354 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000355 if (DstType->isBooleanType())
356 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000357
358 const llvm::Type *DstTy = ConvertType(DstType);
359
360 // Ignore conversions like int -> uint.
361 if (Src->getType() == DstTy)
362 return Src;
363
364 // Handle pointer conversions next: pointers can only be converted to/from
365 // other pointers and integers.
366 if (isa<PointerType>(DstType)) {
367 // The source value may be an integer, or a pointer.
368 if (isa<llvm::PointerType>(Src->getType()))
369 return Builder.CreateBitCast(Src, DstTy, "conv");
370 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
371 return Builder.CreateIntToPtr(Src, DstTy, "conv");
372 }
373
374 if (isa<PointerType>(SrcType)) {
375 // Must be an ptr to int cast.
376 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000377 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000378 }
379
Nate Begemanaf6ed502008-04-18 23:10:10 +0000380 // A scalar can be splatted to an extended vector of the same element type
381 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner4f025a42008-02-02 04:51:41 +0000382 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000383 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
384 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000385
Chris Lattner4f025a42008-02-02 04:51:41 +0000386 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000387 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000388 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000389 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000390
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000391 // Finally, we have the arithmetic types: real int/float.
392 if (isa<llvm::IntegerType>(Src->getType())) {
393 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000394 if (isa<llvm::IntegerType>(DstTy))
395 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
396 else if (InputSigned)
397 return Builder.CreateSIToFP(Src, DstTy, "conv");
398 else
399 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000400 }
401
402 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
403 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000404 if (DstType->isSignedIntegerType())
405 return Builder.CreateFPToSI(Src, DstTy, "conv");
406 else
407 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000408 }
409
410 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000411 if (DstTy->getTypeID() < Src->getType()->getTypeID())
412 return Builder.CreateFPTrunc(Src, DstTy, "conv");
413 else
414 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000415}
416
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000417/// EmitComplexToScalarConversion - Emit a conversion from the specified
418/// complex type to the specified destination type, where the destination
419/// type is an LLVM scalar type.
420Value *ScalarExprEmitter::
421EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
422 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000423 // Get the source element type.
424 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
425
426 // Handle conversions to bool first, they are special: comparisons against 0.
427 if (DstTy->isBooleanType()) {
428 // Complex != 0 -> (Real != 0) | (Imag != 0)
429 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
430 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
431 return Builder.CreateOr(Src.first, Src.second, "tobool");
432 }
433
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000434 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
435 // the imaginary part of the complex value is discarded and the value of the
436 // real part is converted according to the conversion rules for the
437 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000438 return EmitScalarConversion(Src.first, SrcTy, DstTy);
439}
440
441
Chris Lattner9fba49a2007-08-24 05:35:26 +0000442//===----------------------------------------------------------------------===//
443// Visitor Methods
444//===----------------------------------------------------------------------===//
445
446Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000447 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000448 if (E->getType()->isVoidType())
449 return 0;
450 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
451}
452
Eli Friedmand0e9d092008-05-14 19:38:39 +0000453Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
454 llvm::SmallVector<llvm::Constant*, 32> indices;
455 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
456 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
457 }
458 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
459 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
460 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
461 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
462}
463
Chris Lattnercbfb5512008-03-01 08:45:05 +0000464Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
465 // Only the lookup mechanism and first two arguments of the method
466 // implementation vary between runtimes. We can get the receiver and
467 // arguments in generic code.
468
469 // Find the receiver
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000470 llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000471
472 // Process the arguments
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000473 unsigned ArgC = E->getNumArgs();
Chris Lattnercbfb5512008-03-01 08:45:05 +0000474 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000475 for (unsigned i = 0; i != ArgC; ++i) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000476 Expr *ArgExpr = E->getArg(i);
477 QualType ArgTy = ArgExpr->getType();
478 if (!CGF.hasAggregateLLVMType(ArgTy)) {
479 // Scalar argument is passed by-value.
480 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
Chris Lattnerde0908b2008-04-04 16:54:41 +0000481 } else if (ArgTy->isAnyComplexType()) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000482 // Make a temporary alloca to pass the argument.
483 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
484 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
485 Args.push_back(DestMem);
486 } else {
487 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
488 CGF.EmitAggExpr(ArgExpr, DestMem, false);
489 Args.push_back(DestMem);
490 }
491 }
492
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000493 return Runtime->GenerateMessageSend(Builder, ConvertType(E->getType()),
Chris Lattner6e6a5972008-04-04 04:07:35 +0000494 CGF.LoadObjCSelf(),
Chris Lattner8384c142008-06-26 04:42:20 +0000495 Receiver, E->getSelector(),
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000496 &Args[0], Args.size());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000497}
498
Chris Lattner9fba49a2007-08-24 05:35:26 +0000499Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
500 // Emit subscript expressions in rvalue context's. For most cases, this just
501 // loads the lvalue formed by the subscript expr. However, we have to be
502 // careful, because the base of a vector subscript is occasionally an rvalue,
503 // so we can't get it as an lvalue.
504 if (!E->getBase()->getType()->isVectorType())
505 return EmitLoadOfLValue(E);
506
507 // Handle the vector case. The base must be a vector, the index must be an
508 // integer value.
509 Value *Base = Visit(E->getBase());
510 Value *Idx = Visit(E->getIdx());
511
512 // FIXME: Convert Idx to i32 type.
513 return Builder.CreateExtractElement(Base, Idx, "vecext");
514}
515
516/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
517/// also handle things like function to pointer-to-function decay, and array to
518/// pointer decay.
519Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
520 const Expr *Op = E->getSubExpr();
521
522 // If this is due to array->pointer conversion, emit the array expression as
523 // an l-value.
524 if (Op->getType()->isArrayType()) {
525 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
526 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000527 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000528
529 assert(isa<llvm::PointerType>(V->getType()) &&
530 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
531 ->getElementType()) &&
532 "Doesn't support VLAs yet!");
Chris Lattner07307562008-03-19 05:19:41 +0000533 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000534
535 // The resultant pointer type can be implicitly casted to other pointer
536 // types as well, for example void*.
537 const llvm::Type *DestPTy = ConvertType(E->getType());
538 assert(isa<llvm::PointerType>(DestPTy) &&
539 "Only expect implicit cast to pointer");
540 if (V->getType() != DestPTy)
541 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
542 return V;
543
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000544 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000545 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
Chris Lattnercfac88d2008-04-02 17:35:06 +0000546 getPointeeType() ==
Anders Carlsson88842452007-10-13 05:52:34 +0000547 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000548
549 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000550 }
551
552 return EmitCastExpr(Op, E->getType());
553}
554
555
556// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
557// have to handle a more broad range of conversions than explicit casts, as they
558// handle things like function to ptr-to-function decay etc.
559Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000560 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000561
562 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000563 Value *Src = Visit(const_cast<Expr*>(E));
564
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000565 // Use EmitScalarConversion to perform the conversion.
566 return EmitScalarConversion(Src, E->getType(), DestTy);
567 }
Chris Lattner77288792008-02-16 23:55:16 +0000568
Chris Lattnerde0908b2008-04-04 16:54:41 +0000569 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000570 // Handle cases where the source is a complex type.
571 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
572 DestTy);
573 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000574
Chris Lattner77288792008-02-16 23:55:16 +0000575 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
576 // evaluate the result and return.
577 CGF.EmitAggExpr(E, 0, false);
578 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000579}
580
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000581Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000582 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000583}
584
585
Chris Lattner9fba49a2007-08-24 05:35:26 +0000586//===----------------------------------------------------------------------===//
587// Unary Operators
588//===----------------------------------------------------------------------===//
589
590Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000591 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000592 LValue LV = EmitLValue(E->getSubExpr());
593 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000594 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000595 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000596
597 int AmountVal = isInc ? 1 : -1;
598
599 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000600 if (isa<llvm::PointerType>(InVal->getType())) {
601 // FIXME: This isn't right for VLAs.
602 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000603 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000604 } else {
605 // Add the inc/dec to the real part.
606 if (isa<llvm::IntegerType>(InVal->getType()))
607 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000608 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000609 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000610 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000611 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000612 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000613 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000614 else {
615 llvm::APFloat F(static_cast<float>(AmountVal));
616 F.convert(*CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
617 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000618 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000619 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
620 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000621
622 // Store the updated result through the lvalue.
623 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
624 E->getSubExpr()->getType());
625
626 // If this is a postinc, return the value read from memory, otherwise use the
627 // updated value.
628 return isPre ? NextVal : InVal;
629}
630
631
632Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
633 Value *Op = Visit(E->getSubExpr());
634 return Builder.CreateNeg(Op, "neg");
635}
636
637Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
638 Value *Op = Visit(E->getSubExpr());
639 return Builder.CreateNot(Op, "neg");
640}
641
642Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
643 // Compare operand to zero.
644 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
645
646 // Invert value.
647 // TODO: Could dynamically modify easy computations here. For example, if
648 // the operand is an icmp ne, turn into icmp eq.
649 BoolVal = Builder.CreateNot(BoolVal, "lnot");
650
651 // ZExt result to int.
652 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
653}
654
655/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
656/// an integer (RetType).
657Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000658 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000659 assert(RetType->isIntegerType() && "Result type must be an integer!");
660 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000661 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000662
663 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
664 if (TypeToSize->isVoidType())
665 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
666
Chris Lattner9fba49a2007-08-24 05:35:26 +0000667 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000668 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000669
670 uint64_t Val = isSizeOf ? Info.first : Info.second;
671 Val /= 8; // Return size in bytes, not bits.
672
Chris Lattner9fba49a2007-08-24 05:35:26 +0000673 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
674}
675
Chris Lattner01211af2007-08-24 21:20:17 +0000676Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
677 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000678 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000679 return CGF.EmitComplexExpr(Op).first;
680 return Visit(Op);
681}
682Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
683 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000684 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000685 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000686
687 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
688 // effects are evaluated.
689 CGF.EmitScalarExpr(Op);
690 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000691}
692
Anders Carlsson52774ad2008-01-29 15:56:48 +0000693Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
694{
695 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
696
697 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
698
Chris Lattner8cd0e932008-03-05 18:54:05 +0000699 uint32_t ResultWidth =
700 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000701 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
702}
Chris Lattner01211af2007-08-24 21:20:17 +0000703
Chris Lattner9fba49a2007-08-24 05:35:26 +0000704//===----------------------------------------------------------------------===//
705// Binary Operators
706//===----------------------------------------------------------------------===//
707
708BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
709 BinOpInfo Result;
710 Result.LHS = Visit(E->getLHS());
711 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000712 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000713 Result.E = E;
714 return Result;
715}
716
Chris Lattner0d965302007-08-26 21:41:21 +0000717Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000718 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
719 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
720
721 BinOpInfo OpInfo;
722
723 // Load the LHS and RHS operands.
724 LValue LHSLV = EmitLValue(E->getLHS());
725 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000726
727 // Determine the computation type. If the RHS is complex, then this is one of
728 // the add/sub/mul/div operators. All of these operators can be computed in
729 // with just their real component even though the computation domain really is
730 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000731 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000732
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000733 // If the computation type is complex, then the RHS is complex. Emit the RHS.
734 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
735 ComputeType = CT->getElementType();
736
737 // Emit the RHS, only keeping the real component.
738 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
739 RHSTy = RHSTy->getAsComplexType()->getElementType();
740 } else {
741 // Otherwise the RHS is a simple scalar value.
742 OpInfo.RHS = Visit(E->getRHS());
743 }
744
745 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000746 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000747
Devang Patel04011802007-10-25 22:19:13 +0000748 // Do not merge types for -= or += where the LHS is a pointer.
749 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000750 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000751 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000752 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000753 }
754 OpInfo.Ty = ComputeType;
755 OpInfo.E = E;
756
757 // Expand the binary operator.
758 Value *Result = (this->*Func)(OpInfo);
759
760 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000761 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000762
763 // Store the result value into the LHS lvalue.
764 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
765
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000766 // For bitfields, we need the value in the bitfield
767 // FIXME: This adds an extra bitfield load
768 if (LHSLV.isBitfield())
769 Result = EmitLoadOfLValue(LHSLV, LHSTy);
770
Chris Lattner660e31d2007-08-24 21:00:35 +0000771 return Result;
772}
773
774
Chris Lattner9fba49a2007-08-24 05:35:26 +0000775Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000776 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000777 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000778 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000779 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
780 else
781 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
782}
783
784Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
785 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000786 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000787 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
788 else
789 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
790}
791
792
793Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000794 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000795 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000796
797 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000798 Value *Ptr, *Idx;
799 Expr *IdxExp;
800 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
801 Ptr = Ops.LHS;
802 Idx = Ops.RHS;
803 IdxExp = Ops.E->getRHS();
804 } else { // int + pointer
805 Ptr = Ops.RHS;
806 Idx = Ops.LHS;
807 IdxExp = Ops.E->getLHS();
808 }
809
810 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
811 if (Width < CGF.LLVMPointerWidth) {
812 // Zero or sign extend the pointer value based on whether the index is
813 // signed or not.
814 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
815 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
816 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
817 else
818 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
819 }
820
821 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000822}
823
824Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
825 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
826 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
827
Chris Lattner660e31d2007-08-24 21:00:35 +0000828 // pointer - int
829 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
830 "ptr-ptr shouldn't get here");
831 // FIXME: The pointer could point to a VLA.
Chris Lattnere78c1ea2008-01-31 04:12:50 +0000832 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
833
834 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
835 if (Width < CGF.LLVMPointerWidth) {
836 // Zero or sign extend the pointer value based on whether the index is
837 // signed or not.
838 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
839 if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
840 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
841 else
842 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
843 }
844
845 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner660e31d2007-08-24 21:00:35 +0000846}
847
848Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
849 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
850 // the compound assignment case it is invalid, so just handle it here.
851 if (!E->getRHS()->getType()->isPointerType())
852 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000853
854 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000855 Value *LHS = Visit(E->getLHS());
856 Value *RHS = Visit(E->getRHS());
857
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000858 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000859 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner8cd0e932008-03-05 18:54:05 +0000860 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000861
862 const llvm::Type *ResultType = ConvertType(E->getType());
863 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
864 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
865 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000866
867 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
868 // remainder. As such, we handle common power-of-two cases here to generate
869 // better code.
870 if (llvm::isPowerOf2_64(ElementSize)) {
871 Value *ShAmt =
872 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
873 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
874 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000875
Chris Lattner9fba49a2007-08-24 05:35:26 +0000876 // Otherwise, do a full sdiv.
877 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
878 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
879}
880
Chris Lattner660e31d2007-08-24 21:00:35 +0000881
Chris Lattner9fba49a2007-08-24 05:35:26 +0000882Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
883 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
884 // RHS to the same size as the LHS.
885 Value *RHS = Ops.RHS;
886 if (Ops.LHS->getType() != RHS->getType())
887 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
888
889 return Builder.CreateShl(Ops.LHS, RHS, "shl");
890}
891
892Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
893 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
894 // RHS to the same size as the LHS.
895 Value *RHS = Ops.RHS;
896 if (Ops.LHS->getType() != RHS->getType())
897 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
898
Chris Lattner660e31d2007-08-24 21:00:35 +0000899 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000900 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
901 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
902}
903
904Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
905 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000906 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000907 QualType LHSTy = E->getLHS()->getType();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000908 if (!LHSTy->isAnyComplexType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000909 Value *LHS = Visit(E->getLHS());
910 Value *RHS = Visit(E->getRHS());
911
912 if (LHS->getType()->isFloatingPoint()) {
913 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
914 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000915 } else if (LHSTy->isSignedIntegerType()) {
916 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000917 LHS, RHS, "cmp");
918 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000919 // Unsigned integers and pointers.
920 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000921 LHS, RHS, "cmp");
922 }
923 } else {
924 // Complex Comparison: can only be an equality comparison.
925 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
926 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
927
928 QualType CETy =
929 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
930
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000931 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000932 if (CETy->isRealFloatingType()) {
933 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
934 LHS.first, RHS.first, "cmp.r");
935 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
936 LHS.second, RHS.second, "cmp.i");
937 } else {
938 // Complex comparisons can only be equality comparisons. As such, signed
939 // and unsigned opcodes are the same.
940 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
941 LHS.first, RHS.first, "cmp.r");
942 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
943 LHS.second, RHS.second, "cmp.i");
944 }
945
946 if (E->getOpcode() == BinaryOperator::EQ) {
947 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
948 } else {
949 assert(E->getOpcode() == BinaryOperator::NE &&
950 "Complex comparison other than == or != ?");
951 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
952 }
953 }
954
955 // ZExt result to int.
956 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
957}
958
959Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
960 LValue LHS = EmitLValue(E->getLHS());
961 Value *RHS = Visit(E->getRHS());
962
963 // Store the value into the LHS.
964 // FIXME: Volatility!
965 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000966
967 // For bitfields, we need the value in the bitfield
968 // FIXME: This adds an extra bitfield load
969 if (LHS.isBitfield())
970 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000971 // Return the RHS.
972 return RHS;
973}
974
975Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
976 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
977
Gabor Greif815e2c12008-04-06 20:42:52 +0000978 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
979 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000980
981 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
982 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
983
984 CGF.EmitBlock(RHSBlock);
985 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
986
987 // Reaquire the RHS block, as there may be subblocks inserted.
988 RHSBlock = Builder.GetInsertBlock();
989 CGF.EmitBlock(ContBlock);
990
991 // Create a PHI node. If we just evaluted the LHS condition, the result is
992 // false. If we evaluated both, the result is the RHS condition.
993 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
994 PN->reserveOperandSpace(2);
995 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
996 PN->addIncoming(RHSCond, RHSBlock);
997
998 // ZExt result to int.
999 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1000}
1001
1002Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1003 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1004
Gabor Greif815e2c12008-04-06 20:42:52 +00001005 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1006 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001007
1008 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1009 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1010
1011 CGF.EmitBlock(RHSBlock);
1012 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1013
1014 // Reaquire the RHS block, as there may be subblocks inserted.
1015 RHSBlock = Builder.GetInsertBlock();
1016 CGF.EmitBlock(ContBlock);
1017
1018 // Create a PHI node. If we just evaluted the LHS condition, the result is
1019 // true. If we evaluated both, the result is the RHS condition.
1020 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1021 PN->reserveOperandSpace(2);
1022 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1023 PN->addIncoming(RHSCond, RHSBlock);
1024
1025 // ZExt result to int.
1026 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1027}
1028
1029Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1030 CGF.EmitStmt(E->getLHS());
1031 return Visit(E->getRHS());
1032}
1033
1034//===----------------------------------------------------------------------===//
1035// Other Operators
1036//===----------------------------------------------------------------------===//
1037
1038Value *ScalarExprEmitter::
1039VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001040 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1041 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1042 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001043
Chris Lattner98a425c2007-11-26 01:40:58 +00001044 // Evaluate the conditional, then convert it to bool. We do this explicitly
1045 // because we need the unconverted value if this is a GNU ?: expression with
1046 // missing middle value.
1047 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001048 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1049 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001050 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001051
1052 CGF.EmitBlock(LHSBlock);
1053
1054 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001055 Value *LHS;
1056 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001057 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001058 else // Perform promotions, to handle cases like "short ?: int"
1059 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1060
Chris Lattner9fba49a2007-08-24 05:35:26 +00001061 Builder.CreateBr(ContBlock);
1062 LHSBlock = Builder.GetInsertBlock();
1063
1064 CGF.EmitBlock(RHSBlock);
1065
Eli Friedmance8d7032008-05-16 20:38:39 +00001066 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001067 Builder.CreateBr(ContBlock);
1068 RHSBlock = Builder.GetInsertBlock();
1069
1070 CGF.EmitBlock(ContBlock);
1071
Nuno Lopesb62ff242008-06-04 19:15:45 +00001072 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001073 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1074 return 0;
1075 }
1076
Chris Lattner9fba49a2007-08-24 05:35:26 +00001077 // Create a PHI node for the real part.
1078 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1079 PN->reserveOperandSpace(2);
1080 PN->addIncoming(LHS, LHSBlock);
1081 PN->addIncoming(RHS, RHSBlock);
1082 return PN;
1083}
1084
1085Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001086 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001087 return
1088 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001089}
1090
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001091Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001092 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001093 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001094}
1095
Chris Lattner307da022007-11-30 17:56:23 +00001096Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001097 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1098
1099 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1100 return V;
1101}
1102
Chris Lattner307da022007-11-30 17:56:23 +00001103Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001104 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001105 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1106 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1107 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001108
1109 llvm::Constant *C = llvm::ConstantArray::get(str);
1110 C = new llvm::GlobalVariable(C->getType(), true,
1111 llvm::GlobalValue::InternalLinkage,
1112 C, ".str", &CGF.CGM.getModule());
1113 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1114 llvm::Constant *Zeros[] = { Zero, Zero };
1115 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1116
1117 return C;
1118}
1119
Chris Lattner9fba49a2007-08-24 05:35:26 +00001120//===----------------------------------------------------------------------===//
1121// Entry Point into this File
1122//===----------------------------------------------------------------------===//
1123
1124/// EmitComplexExpr - Emit the computation of the specified expression of
1125/// complex type, ignoring the result.
1126Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1127 assert(E && !hasAggregateLLVMType(E->getType()) &&
1128 "Invalid scalar expression to emit");
1129
1130 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1131}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001132
1133/// EmitScalarConversion - Emit a conversion from the specified type to the
1134/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001135Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1136 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001137 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1138 "Invalid scalar expression to emit");
1139 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1140}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001141
1142/// EmitComplexToScalarConversion - Emit a conversion from the specified
1143/// complex type to the specified destination type, where the destination
1144/// type is an LLVM scalar type.
1145Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1146 QualType SrcTy,
1147 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001148 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001149 "Invalid complex -> scalar conversion");
1150 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1151 DstTy);
1152}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001153
1154Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1155 assert(V1->getType() == V2->getType() &&
1156 "Vector operands must be of the same type");
1157
1158 unsigned NumElements =
1159 cast<llvm::VectorType>(V1->getType())->getNumElements();
1160
1161 va_list va;
1162 va_start(va, V2);
1163
1164 llvm::SmallVector<llvm::Constant*, 16> Args;
1165
1166 for (unsigned i = 0; i < NumElements; i++) {
1167 int n = va_arg(va, int);
1168
1169 assert(n >= 0 && n < (int)NumElements * 2 &&
1170 "Vector shuffle index out of bounds!");
1171
1172 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1173 }
1174
1175 const char *Name = va_arg(va, const char *);
1176 va_end(va);
1177
1178 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1179
1180 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1181}
1182
Anders Carlsson68b8be92007-12-15 21:23:30 +00001183llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001184 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001185{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001186 llvm::Value *Vec
1187 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1188
1189 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001190 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001191 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001192 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001193 }
1194
1195 return Vec;
1196}