blob: 8afed8997b873e3e2865fcd52da70f61cb028f69 [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"
Chris Lattner9fba49a2007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000026#include "llvm/Support/CFG.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000027#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000028
Chris Lattner9fba49a2007-08-24 05:35:26 +000029using namespace clang;
30using namespace CodeGen;
31using llvm::Value;
32
33//===----------------------------------------------------------------------===//
34// Scalar Expression Emitter
35//===----------------------------------------------------------------------===//
36
37struct BinOpInfo {
38 Value *LHS;
39 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000040 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000041 const BinaryOperator *E;
42};
43
44namespace {
45class VISIBILITY_HIDDEN ScalarExprEmitter
46 : public StmtVisitor<ScalarExprEmitter, Value*> {
47 CodeGenFunction &CGF;
Daniel Dunbard916e6e2008-11-01 01:53:16 +000048 CGBuilderTy &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049
Chris Lattner9fba49a2007-08-24 05:35:26 +000050public:
51
Chris Lattnercbfb5512008-03-01 08:45:05 +000052 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbarf1f7f192008-08-20 00:28:19 +000053 Builder(CGF.Builder) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000054 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000055
56 //===--------------------------------------------------------------------===//
57 // Utilities
58 //===--------------------------------------------------------------------===//
59
60 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
61 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
62
63 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000064 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000065 }
66
67 /// EmitLoadOfLValue - Given an expression with complex type that represents a
68 /// value l-value, this method emits the address of the l-value, then loads
69 /// and returns the result.
70 Value *EmitLoadOfLValue(const Expr *E) {
71 // FIXME: Volatile
72 return EmitLoadOfLValue(EmitLValue(E), E->getType());
73 }
74
Chris Lattnerd8d44222007-08-26 16:42:57 +000075 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000076 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000077 Value *EmitConversionToBool(Value *Src, QualType DstTy);
78
Chris Lattner4e05d1e2007-08-26 06:48:56 +000079 /// EmitScalarConversion - Emit a conversion from the specified type to the
80 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000081 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
82
83 /// EmitComplexToScalarConversion - Emit a conversion from the specified
84 /// complex type to the specified destination type, where the destination
85 /// type is an LLVM scalar type.
86 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
87 QualType SrcTy, QualType DstTy);
Mike Stump4eb81dc2009-02-12 18:29:15 +000088
89 llvm::Constant *BuildBlockLiteralTmp ();
90 llvm::Constant *BuildDescriptorBlockDecl();
91
Chris Lattner9fba49a2007-08-24 05:35:26 +000092 //===--------------------------------------------------------------------===//
93 // Visitor Methods
94 //===--------------------------------------------------------------------===//
95
96 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000097 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000098 assert(0 && "Stmt can't have complex result type!");
99 return 0;
100 }
101 Value *VisitExpr(Expr *S);
102 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
103
104 // Leaves.
105 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
106 return llvm::ConstantInt::get(E->getValue());
107 }
108 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000109 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000110 }
111 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
112 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
113 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000114 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
115 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
116 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000117 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
118 return llvm::Constant::getNullValue(ConvertType(E->getType()));
119 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000120 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
121 return llvm::Constant::getNullValue(ConvertType(E->getType()));
122 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000123 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
124 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000125 CGF.getContext().typesAreCompatible(
126 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000127 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000128 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000129 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000130 llvm::Value *V =
131 llvm::ConstantInt::get(llvm::Type::Int32Ty,
132 CGF.GetIDForAddrOfLabel(E->getLabel()));
133
134 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000135 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000136
137 // l-values.
138 Value *VisitDeclRefExpr(DeclRefExpr *E) {
139 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
140 return llvm::ConstantInt::get(EC->getInitVal());
141 return EmitLoadOfLValue(E);
142 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000143 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
144 return CGF.EmitObjCSelectorExpr(E);
145 }
146 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
147 return CGF.EmitObjCProtocolExpr(E);
148 }
149 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
150 return EmitLoadOfLValue(E);
151 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000152 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000153 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000154 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000155 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
156 return EmitLoadOfLValue(E);
157 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000158 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
159 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000160 }
161
Chris Lattner9fba49a2007-08-24 05:35:26 +0000162 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000163 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000164 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000165 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000166 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
167 return EmitLoadOfLValue(E);
168 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000169 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattner69909292008-08-10 01:53:14 +0000170 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000171
172 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000173 unsigned NumInitElements = E->getNumInits();
174
Douglas Gregor9fddded2009-01-29 19:42:23 +0000175 if (E->hadArrayRangeDesignator()) {
176 CGF.ErrorUnsupported(E, "GNU array range designator extension");
177 }
178
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000179 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000180 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
181
182 // We have a scalar in braces. Just use the first element.
183 if (!VType)
184 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000185
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000186 unsigned NumVectorElements = VType->getNumElements();
187 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000188
189 // Emit individual vector element stores.
190 llvm::Value *V = llvm::UndefValue::get(VType);
191
Anders Carlsson323d5682007-12-18 02:45:33 +0000192 // Emit initializers
193 unsigned i;
194 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000195 Value *NewV = Visit(E->getInit(i));
196 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
197 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000198 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000199
200 // Emit remaining default initializers
201 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
202 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
203 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
204 V = Builder.CreateInsertElement(V, NewV, Idx);
205 }
206
Devang Patel32c39832007-10-24 18:05:48 +0000207 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000208 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000209
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000210 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
211 return llvm::Constant::getNullValue(ConvertType(E->getType()));
212 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000213 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
214 Value *VisitCastExpr(const CastExpr *E) {
215 return EmitCastExpr(E->getSubExpr(), E->getType());
216 }
217 Value *EmitCastExpr(const Expr *E, QualType T);
218
219 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000220 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000221 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000222
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000223 Value *VisitStmtExpr(const StmtExpr *E);
224
Chris Lattner9fba49a2007-08-24 05:35:26 +0000225 // Unary Operators.
226 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
227 Value *VisitUnaryPostDec(const UnaryOperator *E) {
228 return VisitPrePostIncDec(E, false, false);
229 }
230 Value *VisitUnaryPostInc(const UnaryOperator *E) {
231 return VisitPrePostIncDec(E, true, false);
232 }
233 Value *VisitUnaryPreDec(const UnaryOperator *E) {
234 return VisitPrePostIncDec(E, false, true);
235 }
236 Value *VisitUnaryPreInc(const UnaryOperator *E) {
237 return VisitPrePostIncDec(E, true, true);
238 }
239 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
240 return EmitLValue(E->getSubExpr()).getAddress();
241 }
242 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
243 Value *VisitUnaryPlus(const UnaryOperator *E) {
244 return Visit(E->getSubExpr());
245 }
246 Value *VisitUnaryMinus (const UnaryOperator *E);
247 Value *VisitUnaryNot (const UnaryOperator *E);
248 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000249 Value *VisitUnaryReal (const UnaryOperator *E);
250 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000251 Value *VisitUnaryExtension(const UnaryOperator *E) {
252 return Visit(E->getSubExpr());
253 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000254 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000255 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
256 return Visit(DAE->getExpr());
257 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000258
Chris Lattner9fba49a2007-08-24 05:35:26 +0000259 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000260 Value *EmitMul(const BinOpInfo &Ops) {
261 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
262 }
263 Value *EmitDiv(const BinOpInfo &Ops);
264 Value *EmitRem(const BinOpInfo &Ops);
265 Value *EmitAdd(const BinOpInfo &Ops);
266 Value *EmitSub(const BinOpInfo &Ops);
267 Value *EmitShl(const BinOpInfo &Ops);
268 Value *EmitShr(const BinOpInfo &Ops);
269 Value *EmitAnd(const BinOpInfo &Ops) {
270 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
271 }
272 Value *EmitXor(const BinOpInfo &Ops) {
273 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
274 }
275 Value *EmitOr (const BinOpInfo &Ops) {
276 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
277 }
278
Chris Lattner660e31d2007-08-24 21:00:35 +0000279 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000280 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000281 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
282
283 // Binary operators and binary compound assignment operators.
284#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000285 Value *VisitBin ## OP(const BinaryOperator *E) { \
286 return Emit ## OP(EmitBinOps(E)); \
287 } \
288 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
289 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000290 }
291 HANDLEBINOP(Mul);
292 HANDLEBINOP(Div);
293 HANDLEBINOP(Rem);
294 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000295 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000296 HANDLEBINOP(Shl);
297 HANDLEBINOP(Shr);
298 HANDLEBINOP(And);
299 HANDLEBINOP(Xor);
300 HANDLEBINOP(Or);
301#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000302
Chris Lattner9fba49a2007-08-24 05:35:26 +0000303 // Comparisons.
304 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
305 unsigned SICmpOpc, unsigned FCmpOpc);
306#define VISITCOMP(CODE, UI, SI, FP) \
307 Value *VisitBin##CODE(const BinaryOperator *E) { \
308 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
309 llvm::FCmpInst::FP); }
310 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
311 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
312 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
313 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
314 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
315 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
316#undef VISITCOMP
317
318 Value *VisitBinAssign (const BinaryOperator *E);
319
320 Value *VisitBinLAnd (const BinaryOperator *E);
321 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000322 Value *VisitBinComma (const BinaryOperator *E);
323
324 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000325 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000326 Value *VisitConditionalOperator(const ConditionalOperator *CO);
327 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000328 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000329 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000330 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
331 return CGF.EmitObjCStringLiteral(E);
332 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000333 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000334};
335} // end anonymous namespace.
336
337//===----------------------------------------------------------------------===//
338// Utilities
339//===----------------------------------------------------------------------===//
340
Chris Lattnerd8d44222007-08-26 16:42:57 +0000341/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000342/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000343Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
344 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
345
346 if (SrcType->isRealFloatingType()) {
347 // Compare against 0.0 for fp scalars.
348 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000349 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
350 }
351
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000352 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000353 "Unknown scalar type to convert");
354
355 // Because of the type rules of C, we often end up computing a logical value,
356 // then zero extending it to int, then wanting it as a logical value again.
357 // Optimize this common case.
358 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
359 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
360 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000361 // If there aren't any more uses, zap the instruction to save space.
362 // Note that there can be more uses, for example if this
363 // is the result of an assignment.
364 if (ZI->use_empty())
365 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000366 return Result;
367 }
368 }
369
370 // Compare against an integer or pointer null.
371 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
372 return Builder.CreateICmpNE(Src, Zero, "tobool");
373}
374
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000375/// EmitScalarConversion - Emit a conversion from the specified type to the
376/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000377Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
378 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000379 SrcType = CGF.getContext().getCanonicalType(SrcType);
380 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000381 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000382
383 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000384
385 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000386 if (DstType->isBooleanType())
387 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000388
389 const llvm::Type *DstTy = ConvertType(DstType);
390
391 // Ignore conversions like int -> uint.
392 if (Src->getType() == DstTy)
393 return Src;
394
Daniel Dunbar238335f2008-08-25 09:51:32 +0000395 // Handle pointer conversions next: pointers can only be converted
396 // to/from other pointers and integers. Check for pointer types in
397 // terms of LLVM, as some native types (like Obj-C id) may map to a
398 // pointer type.
399 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000400 // The source value may be an integer, or a pointer.
401 if (isa<llvm::PointerType>(Src->getType()))
402 return Builder.CreateBitCast(Src, DstTy, "conv");
403 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
404 return Builder.CreateIntToPtr(Src, DstTy, "conv");
405 }
406
Daniel Dunbar238335f2008-08-25 09:51:32 +0000407 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000408 // Must be an ptr to int cast.
409 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000410 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000411 }
412
Nate Begemanaf6ed502008-04-18 23:10:10 +0000413 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000414 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
415 // Cast the scalar to element type
416 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
417 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
418
419 // Insert the element in element zero of an undef vector
420 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
421 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
422 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
423
424 // Splat the element across to all elements
425 llvm::SmallVector<llvm::Constant*, 16> Args;
426 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
427 for (unsigned i = 0; i < NumElements; i++)
428 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
429
430 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
431 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
432 return Yay;
433 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000434
Chris Lattner4f025a42008-02-02 04:51:41 +0000435 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000436 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000437 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000438 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000439
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000440 // Finally, we have the arithmetic types: real int/float.
441 if (isa<llvm::IntegerType>(Src->getType())) {
442 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000443 if (isa<llvm::IntegerType>(DstTy))
444 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
445 else if (InputSigned)
446 return Builder.CreateSIToFP(Src, DstTy, "conv");
447 else
448 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000449 }
450
451 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
452 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000453 if (DstType->isSignedIntegerType())
454 return Builder.CreateFPToSI(Src, DstTy, "conv");
455 else
456 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000457 }
458
459 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000460 if (DstTy->getTypeID() < Src->getType()->getTypeID())
461 return Builder.CreateFPTrunc(Src, DstTy, "conv");
462 else
463 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000464}
465
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000466/// EmitComplexToScalarConversion - Emit a conversion from the specified
467/// complex type to the specified destination type, where the destination
468/// type is an LLVM scalar type.
469Value *ScalarExprEmitter::
470EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
471 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000472 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000473 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000474
475 // Handle conversions to bool first, they are special: comparisons against 0.
476 if (DstTy->isBooleanType()) {
477 // Complex != 0 -> (Real != 0) | (Imag != 0)
478 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
479 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
480 return Builder.CreateOr(Src.first, Src.second, "tobool");
481 }
482
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000483 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
484 // the imaginary part of the complex value is discarded and the value of the
485 // real part is converted according to the conversion rules for the
486 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000487 return EmitScalarConversion(Src.first, SrcTy, DstTy);
488}
489
490
Chris Lattner9fba49a2007-08-24 05:35:26 +0000491//===----------------------------------------------------------------------===//
492// Visitor Methods
493//===----------------------------------------------------------------------===//
494
495Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000496 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000497 if (E->getType()->isVoidType())
498 return 0;
499 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
500}
501
Eli Friedmand0e9d092008-05-14 19:38:39 +0000502Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
503 llvm::SmallVector<llvm::Constant*, 32> indices;
504 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
505 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
506 }
507 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
508 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
509 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
510 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
511}
512
Chris Lattner9fba49a2007-08-24 05:35:26 +0000513Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
514 // Emit subscript expressions in rvalue context's. For most cases, this just
515 // loads the lvalue formed by the subscript expr. However, we have to be
516 // careful, because the base of a vector subscript is occasionally an rvalue,
517 // so we can't get it as an lvalue.
518 if (!E->getBase()->getType()->isVectorType())
519 return EmitLoadOfLValue(E);
520
521 // Handle the vector case. The base must be a vector, the index must be an
522 // integer value.
523 Value *Base = Visit(E->getBase());
524 Value *Idx = Visit(E->getIdx());
525
526 // FIXME: Convert Idx to i32 type.
527 return Builder.CreateExtractElement(Base, Idx, "vecext");
528}
529
530/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
531/// also handle things like function to pointer-to-function decay, and array to
532/// pointer decay.
533Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
534 const Expr *Op = E->getSubExpr();
535
536 // If this is due to array->pointer conversion, emit the array expression as
537 // an l-value.
538 if (Op->getType()->isArrayType()) {
539 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
540 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000541 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000542
543 if (!Op->getType()->isVariableArrayType()) {
544 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
545 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
546 ->getElementType()) &&
547 "Expected pointer to array");
548 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000549 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000550
551 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000552 // types as well (e.g. void*) and can be implicitly converted to integer.
553 const llvm::Type *DestTy = ConvertType(E->getType());
554 if (V->getType() != DestTy) {
555 if (isa<llvm::PointerType>(DestTy))
556 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
557 else {
558 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
559 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
560 }
561 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000562 return V;
563
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000564 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000565 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000566 }
567
568 return EmitCastExpr(Op, E->getType());
569}
570
571
572// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
573// have to handle a more broad range of conversions than explicit casts, as they
574// handle things like function to ptr-to-function decay etc.
575Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000576 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000577
578 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000579 Value *Src = Visit(const_cast<Expr*>(E));
580
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000581 // Use EmitScalarConversion to perform the conversion.
582 return EmitScalarConversion(Src, E->getType(), DestTy);
583 }
Chris Lattner77288792008-02-16 23:55:16 +0000584
Chris Lattnerde0908b2008-04-04 16:54:41 +0000585 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000586 // Handle cases where the source is a complex type.
587 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
588 DestTy);
589 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000590
Chris Lattner77288792008-02-16 23:55:16 +0000591 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
592 // evaluate the result and return.
593 CGF.EmitAggExpr(E, 0, false);
594 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000595}
596
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000597Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000598 return CGF.EmitCompoundStmt(*E->getSubStmt(),
599 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000600}
601
602
Chris Lattner9fba49a2007-08-24 05:35:26 +0000603//===----------------------------------------------------------------------===//
604// Unary Operators
605//===----------------------------------------------------------------------===//
606
607Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000608 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000609 LValue LV = EmitLValue(E->getSubExpr());
610 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000611 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000612 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000613
614 int AmountVal = isInc ? 1 : -1;
615
616 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000617 if (isa<llvm::PointerType>(InVal->getType())) {
618 // FIXME: This isn't right for VLAs.
619 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000620 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner49083172009-02-11 07:40:06 +0000621 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
622 // Bool++ is an interesting case, due to promotion rules, we get:
623 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
624 // Bool = ((int)Bool+1) != 0
625 // An interesting aspect of this is that increment is always true.
626 // Decrement does not have this property.
627 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner0dc11f62007-08-26 05:10:16 +0000628 } else {
629 // Add the inc/dec to the real part.
630 if (isa<llvm::IntegerType>(InVal->getType()))
631 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000632 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000633 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000634 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000635 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000636 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000637 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000638 else {
639 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000640 bool ignored;
641 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
642 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000643 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000644 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000645 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
646 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000647
648 // Store the updated result through the lvalue.
649 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
650 E->getSubExpr()->getType());
651
652 // If this is a postinc, return the value read from memory, otherwise use the
653 // updated value.
654 return isPre ? NextVal : InVal;
655}
656
657
658Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
659 Value *Op = Visit(E->getSubExpr());
660 return Builder.CreateNeg(Op, "neg");
661}
662
663Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
664 Value *Op = Visit(E->getSubExpr());
665 return Builder.CreateNot(Op, "neg");
666}
667
668Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
669 // Compare operand to zero.
670 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
671
672 // Invert value.
673 // TODO: Could dynamically modify easy computations here. For example, if
674 // the operand is an icmp ne, turn into icmp eq.
675 BoolVal = Builder.CreateNot(BoolVal, "lnot");
676
677 // ZExt result to int.
678 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
679}
680
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000681/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
682/// argument of the sizeof expression as an integer.
683Value *
684ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000685 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000686 if (E->isSizeOf()) {
687 if (const VariableArrayType *VAT =
688 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
689 if (E->isArgumentType()) {
690 // sizeof(type) - make sure to emit the VLA size.
691 CGF.EmitVLASize(TypeToSize);
692 }
Anders Carlssond309f572009-01-30 16:41:04 +0000693
Anders Carlsson8f30de92009-02-05 19:43:10 +0000694 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000695 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000696 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000697
698 // If this isn't sizeof(vla), the result must be constant; use the
699 // constant folding logic so we don't have to duplicate it here.
700 Expr::EvalResult Result;
701 E->Evaluate(Result, CGF.getContext());
702 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000703}
704
Chris Lattner01211af2007-08-24 21:20:17 +0000705Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
706 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000707 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000708 return CGF.EmitComplexExpr(Op).first;
709 return Visit(Op);
710}
711Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
712 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000713 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000714 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000715
716 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
717 // effects are evaluated.
718 CGF.EmitScalarExpr(Op);
719 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000720}
721
Anders Carlsson52774ad2008-01-29 15:56:48 +0000722Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
723{
Eli Friedmanccffea92009-01-24 22:38:55 +0000724 const Expr* SubExpr = E->getSubExpr();
725 const llvm::Type* ResultType = ConvertType(E->getType());
726 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
727 while (!isa<CompoundLiteralExpr>(SubExpr)) {
728 if (const MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr)) {
729 SubExpr = ME->getBase();
730 QualType Ty = SubExpr->getType();
731
732 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
733 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
734 FieldDecl *FD = cast<FieldDecl>(ME->getMemberDecl());
735
736 // FIXME: This is linear time. And the fact that we're indexing
737 // into the layout by position in the record means that we're
738 // either stuck numbering the fields in the AST or we have to keep
739 // the linear search (yuck and yuck).
740 unsigned i = 0;
741 for (RecordDecl::field_iterator Field = RD->field_begin(),
742 FieldEnd = RD->field_end();
743 Field != FieldEnd; (void)++Field, ++i) {
744 if (*Field == FD)
745 break;
746 }
747
748 llvm::Value* Offset =
749 llvm::ConstantInt::get(ResultType, RL.getFieldOffset(i) / 8);
750 Result = Builder.CreateAdd(Result, Offset);
751 } else if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(SubExpr)) {
752 SubExpr = ASE->getBase();
753 int64_t size = CGF.getContext().getTypeSize(ASE->getType()) / 8;
754 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, size);
755 llvm::Value* ElemIndex = CGF.EmitScalarExpr(ASE->getIdx());
756 bool IndexSigned = ASE->getIdx()->getType()->isSignedIntegerType();
757 ElemIndex = Builder.CreateIntCast(ElemIndex, ResultType, IndexSigned);
758 llvm::Value* Offset = Builder.CreateMul(ElemSize, ElemIndex);
759 Result = Builder.CreateAdd(Result, Offset);
760 } else {
761 assert(0 && "This should be impossible!");
762 }
763 }
764 return Result;
Anders Carlsson52774ad2008-01-29 15:56:48 +0000765}
Chris Lattner01211af2007-08-24 21:20:17 +0000766
Chris Lattner9fba49a2007-08-24 05:35:26 +0000767//===----------------------------------------------------------------------===//
768// Binary Operators
769//===----------------------------------------------------------------------===//
770
771BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
772 BinOpInfo Result;
773 Result.LHS = Visit(E->getLHS());
774 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000775 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000776 Result.E = E;
777 return Result;
778}
779
Chris Lattner0d965302007-08-26 21:41:21 +0000780Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000781 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
782 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
783
784 BinOpInfo OpInfo;
785
786 // Load the LHS and RHS operands.
787 LValue LHSLV = EmitLValue(E->getLHS());
788 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000789
790 // Determine the computation type. If the RHS is complex, then this is one of
791 // the add/sub/mul/div operators. All of these operators can be computed in
792 // with just their real component even though the computation domain really is
793 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000794 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000795
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000796 // If the computation type is complex, then the RHS is complex. Emit the RHS.
797 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
798 ComputeType = CT->getElementType();
799
800 // Emit the RHS, only keeping the real component.
801 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
802 RHSTy = RHSTy->getAsComplexType()->getElementType();
803 } else {
804 // Otherwise the RHS is a simple scalar value.
805 OpInfo.RHS = Visit(E->getRHS());
806 }
807
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000808 QualType LComputeTy, RComputeTy, ResultTy;
809
810 // Compound assignment does not contain enough information about all
811 // the types involved for pointer arithmetic cases. Figure it out
812 // here for now.
813 if (E->getLHS()->getType()->isPointerType()) {
814 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
815 assert((E->getOpcode() == BinaryOperator::AddAssign ||
816 E->getOpcode() == BinaryOperator::SubAssign) &&
817 "Invalid compound assignment operator on pointer type.");
818 LComputeTy = E->getLHS()->getType();
819
820 if (E->getRHS()->getType()->isPointerType()) {
821 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
822 // extension, the conversion from the pointer difference back to
823 // the LHS type is handled at the end.
824 assert(E->getOpcode() == BinaryOperator::SubAssign &&
825 "Invalid compound assignment operator on pointer type.");
826 RComputeTy = E->getLHS()->getType();
827 ResultTy = CGF.getContext().getPointerDiffType();
828 } else {
829 RComputeTy = E->getRHS()->getType();
830 ResultTy = LComputeTy;
831 }
832 } else if (E->getRHS()->getType()->isPointerType()) {
833 // Degenerate case of (int += ptr) allowed by GCC implicit cast
834 // extension.
835 assert(E->getOpcode() == BinaryOperator::AddAssign &&
836 "Invalid compound assignment operator on pointer type.");
837 LComputeTy = E->getLHS()->getType();
838 RComputeTy = E->getRHS()->getType();
839 ResultTy = RComputeTy;
840 } else {
841 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000842 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000843
844 // Convert the LHS/RHS values to the computation type.
845 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
846 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
847 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000848 OpInfo.E = E;
849
850 // Expand the binary operator.
851 Value *Result = (this->*Func)(OpInfo);
852
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000853 // Convert the result back to the LHS type.
854 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000855
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000856 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000857 // handled specially because the result is altered by the store,
858 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
859 // the left operand after the assignment...'.
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000860 if (LHSLV.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000861 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
862 &Result);
863 else
864 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
865
Chris Lattner660e31d2007-08-24 21:00:35 +0000866 return Result;
867}
868
869
Chris Lattner9fba49a2007-08-24 05:35:26 +0000870Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000871 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000872 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000873 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000874 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
875 else
876 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
877}
878
879Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
880 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000881 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000882 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
883 else
884 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
885}
886
887
888Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000889 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000890 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000891
892 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000893 Value *Ptr, *Idx;
894 Expr *IdxExp;
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000895 const PointerType *PT;
896 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000897 Ptr = Ops.LHS;
898 Idx = Ops.RHS;
899 IdxExp = Ops.E->getRHS();
900 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000901 PT = Ops.E->getRHS()->getType()->getAsPointerType();
902 assert(PT && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +0000903 Ptr = Ops.RHS;
904 Idx = Ops.LHS;
905 IdxExp = Ops.E->getLHS();
906 }
907
908 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
909 if (Width < CGF.LLVMPointerWidth) {
910 // Zero or sign extend the pointer value based on whether the index is
911 // signed or not.
912 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000913 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000914 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
915 else
916 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
917 }
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000918
919 // Explicitly handle GNU void* and function pointer arithmetic
920 // extensions. The GNU void* casts amount to no-ops since our void*
921 // type is i8*, but this is future proof.
922 const QualType ElementType = PT->getPointeeType();
923 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
924 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
925 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
926 Value *Res = Builder.CreateGEP(Casted, Idx, "sub.ptr");
927 return Builder.CreateBitCast(Res, Ptr->getType());
928 }
Chris Lattner17c0cb02008-01-03 06:36:51 +0000929
930 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000931}
932
933Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
934 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
935 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000936
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000937 const QualType LHSType = Ops.E->getLHS()->getType();
938 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000939 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
940 // pointer - int
941 Value *Idx = Ops.RHS;
942 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
943 if (Width < CGF.LLVMPointerWidth) {
944 // Zero or sign extend the pointer value based on whether the index is
945 // signed or not.
946 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
947 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
948 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
949 else
950 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
951 }
952 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
953
954 // FIXME: The pointer could point to a VLA.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000955
956 // Explicitly handle GNU void* and function pointer arithmetic
957 // extensions. The GNU void* casts amount to no-ops since our
958 // void* type is i8*, but this is future proof.
959 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
960 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
961 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
962 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
963 return Builder.CreateBitCast(Res, Ops.LHS->getType());
964 }
965
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000966 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000967 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000968 // pointer - pointer
969 Value *LHS = Ops.LHS;
970 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000971
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000972 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000973
Chris Lattner6d2e3492009-02-11 07:21:43 +0000974 // Handle GCC extension for pointer arithmetic on void* and function pointer
975 // types.
976 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000977 ElementSize = 1;
978 } else {
979 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
980 }
981
982 const llvm::Type *ResultType = ConvertType(Ops.Ty);
983 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
984 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
985 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
986
Chris Lattner6d2e3492009-02-11 07:21:43 +0000987 // Optimize out the shift for element size of 1.
988 if (ElementSize == 1)
989 return BytesBetween;
990
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000991 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
992 // remainder. As such, we handle common power-of-two cases here to generate
993 // better code. See PR2247.
994 if (llvm::isPowerOf2_64(ElementSize)) {
995 Value *ShAmt =
996 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
997 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
998 }
999
1000 // Otherwise, do a full sdiv.
1001 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1002 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001003 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001004}
1005
1006Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1007 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1008 // RHS to the same size as the LHS.
1009 Value *RHS = Ops.RHS;
1010 if (Ops.LHS->getType() != RHS->getType())
1011 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1012
1013 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1014}
1015
1016Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1017 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1018 // RHS to the same size as the LHS.
1019 Value *RHS = Ops.RHS;
1020 if (Ops.LHS->getType() != RHS->getType())
1021 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1022
Chris Lattner660e31d2007-08-24 21:00:35 +00001023 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001024 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1025 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1026}
1027
1028Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1029 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001030 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001031 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +00001032 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001033 Value *LHS = Visit(E->getLHS());
1034 Value *RHS = Visit(E->getRHS());
1035
1036 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001037 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001038 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001039 } else if (LHSTy->isSignedIntegerType()) {
1040 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001041 LHS, RHS, "cmp");
1042 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001043 // Unsigned integers and pointers.
1044 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001045 LHS, RHS, "cmp");
1046 }
Nate Begeman1591bc52008-07-25 20:16:05 +00001047 } else if (LHSTy->isVectorType()) {
1048 Value *LHS = Visit(E->getLHS());
1049 Value *RHS = Visit(E->getRHS());
1050
1051 if (LHS->getType()->isFPOrFPVector()) {
1052 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1053 LHS, RHS, "cmp");
1054 } else if (LHSTy->isUnsignedIntegerType()) {
1055 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1056 LHS, RHS, "cmp");
1057 } else {
1058 // Signed integers and pointers.
1059 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1060 LHS, RHS, "cmp");
1061 }
1062 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001063 } else {
1064 // Complex Comparison: can only be an equality comparison.
1065 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1066 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1067
Chris Lattnerc154ac12008-07-26 22:37:01 +00001068 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001069
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001070 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001071 if (CETy->isRealFloatingType()) {
1072 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1073 LHS.first, RHS.first, "cmp.r");
1074 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1075 LHS.second, RHS.second, "cmp.i");
1076 } else {
1077 // Complex comparisons can only be equality comparisons. As such, signed
1078 // and unsigned opcodes are the same.
1079 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1080 LHS.first, RHS.first, "cmp.r");
1081 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1082 LHS.second, RHS.second, "cmp.i");
1083 }
1084
1085 if (E->getOpcode() == BinaryOperator::EQ) {
1086 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1087 } else {
1088 assert(E->getOpcode() == BinaryOperator::NE &&
1089 "Complex comparison other than == or != ?");
1090 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1091 }
1092 }
Nuno Lopes92577002009-01-11 23:22:37 +00001093
1094 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001095}
1096
1097Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1098 LValue LHS = EmitLValue(E->getLHS());
1099 Value *RHS = Visit(E->getRHS());
1100
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001101 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001102 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1103 // 'An assignment expression has the value of the left operand after
1104 // the assignment...'.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001105 // FIXME: Volatility!
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001106 if (LHS.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001107 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1108 &RHS);
1109 else
1110 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbare6c31752008-08-29 08:11:39 +00001111
Chris Lattner9fba49a2007-08-24 05:35:26 +00001112 // Return the RHS.
1113 return RHS;
1114}
1115
1116Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001117 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1118 // If we have 1 && X, just emit X without inserting the control flow.
1119 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1120 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001121 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1122 // ZExt result to int.
1123 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1124 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001125
1126 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1127 if (!CGF.ContainsLabel(E->getRHS()))
1128 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001129 }
1130
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001131 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1132 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001133
Chris Lattner7f80bb32008-11-12 08:38:24 +00001134 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1135 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1136
1137 // Any edges into the ContBlock are now from an (indeterminate number of)
1138 // edges from this first condition. All of these values will be false. Start
1139 // setting up the PHI node in the Cont Block for this.
1140 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1141 PN->reserveOperandSpace(2); // Normal case, two inputs.
1142 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1143 PI != PE; ++PI)
1144 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001145
1146 CGF.EmitBlock(RHSBlock);
1147 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1148
1149 // Reaquire the RHS block, as there may be subblocks inserted.
1150 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001151
1152 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1153 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001154 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001155 PN->addIncoming(RHSCond, RHSBlock);
1156
1157 // ZExt result to int.
1158 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1159}
1160
1161Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001162 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1163 // If we have 0 || X, just emit X without inserting the control flow.
1164 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1165 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001166 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1167 // ZExt result to int.
1168 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1169 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001170
Eli Friedmanea137cd2008-12-02 16:02:46 +00001171 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001172 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001173 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001174 }
1175
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001176 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1177 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001178
Chris Lattner7f80bb32008-11-12 08:38:24 +00001179 // Branch on the LHS first. If it is true, go to the success (cont) block.
1180 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1181
1182 // Any edges into the ContBlock are now from an (indeterminate number of)
1183 // edges from this first condition. All of these values will be true. Start
1184 // setting up the PHI node in the Cont Block for this.
1185 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1186 PN->reserveOperandSpace(2); // Normal case, two inputs.
1187 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1188 PI != PE; ++PI)
1189 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1190
1191 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001192 CGF.EmitBlock(RHSBlock);
1193 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1194
1195 // Reaquire the RHS block, as there may be subblocks inserted.
1196 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001197
Chris Lattner7f80bb32008-11-12 08:38:24 +00001198 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1199 // into the phi node for the edge with the value of RHSCond.
1200 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001201 PN->addIncoming(RHSCond, RHSBlock);
1202
1203 // ZExt result to int.
1204 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1205}
1206
1207Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1208 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001209 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001210 return Visit(E->getRHS());
1211}
1212
1213//===----------------------------------------------------------------------===//
1214// Other Operators
1215//===----------------------------------------------------------------------===//
1216
Chris Lattner504a5282008-11-12 08:55:54 +00001217/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1218/// expression is cheap enough and side-effect-free enough to evaluate
1219/// unconditionally instead of conditionally. This is used to convert control
1220/// flow into selects in some cases.
1221static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1222 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1223 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1224
1225 // TODO: Allow anything we can constant fold to an integer or fp constant.
1226 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1227 isa<FloatingLiteral>(E))
1228 return true;
1229
1230 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1231 // X and Y are local variables.
1232 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1233 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1234 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1235 return true;
1236
1237 return false;
1238}
1239
1240
Chris Lattner9fba49a2007-08-24 05:35:26 +00001241Value *ScalarExprEmitter::
1242VisitConditionalOperator(const ConditionalOperator *E) {
Chris Lattner3d6606b2008-11-12 08:04:58 +00001243 // If the condition constant folds and can be elided, try to avoid emitting
1244 // the condition and the dead arm.
1245 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001246 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001247 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001248 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001249
1250 // If the dead side doesn't have labels we need, and if the Live side isn't
1251 // the gnu missing ?: extension (which we could handle, but don't bother
1252 // to), just emit the Live part.
1253 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1254 Live) // Live part isn't missing.
1255 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001256 }
1257
Chris Lattner504a5282008-11-12 08:55:54 +00001258
1259 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1260 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001261 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001262 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1263 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1264 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1265 llvm::Value *LHS = Visit(E->getLHS());
1266 llvm::Value *RHS = Visit(E->getRHS());
1267 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1268 }
1269
1270
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001271 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1272 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001273 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001274 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001275
Chris Lattner67e22462008-11-12 08:08:13 +00001276 // If we have the GNU missing condition extension, evaluate the conditional
1277 // and then convert it to bool the hard way. We do this explicitly
1278 // because we need the unconverted value for the missing middle value of
1279 // the ?:.
1280 if (E->getLHS() == 0) {
1281 CondVal = CGF.EmitScalarExpr(E->getCond());
1282 Value *CondBoolVal =
1283 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1284 CGF.getContext().BoolTy);
1285 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1286 } else {
1287 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1288 // the branch on bool.
1289 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1290 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001291
1292 CGF.EmitBlock(LHSBlock);
1293
1294 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001295 Value *LHS;
1296 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001297 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001298 else // Perform promotions, to handle cases like "short ?: int"
1299 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1300
Chris Lattner9fba49a2007-08-24 05:35:26 +00001301 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001302 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001303
1304 CGF.EmitBlock(RHSBlock);
1305
Eli Friedmance8d7032008-05-16 20:38:39 +00001306 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001307 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001308 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001309
1310 CGF.EmitBlock(ContBlock);
1311
Nuno Lopesb62ff242008-06-04 19:15:45 +00001312 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001313 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1314 return 0;
1315 }
1316
Chris Lattner9fba49a2007-08-24 05:35:26 +00001317 // Create a PHI node for the real part.
1318 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1319 PN->reserveOperandSpace(2);
1320 PN->addIncoming(LHS, LHSBlock);
1321 PN->addIncoming(RHS, RHSBlock);
1322 return PN;
1323}
1324
1325Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001326 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001327 return
1328 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001329}
1330
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001331Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001332 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001333 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001334}
1335
Chris Lattner307da022007-11-30 17:56:23 +00001336Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001337 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001338 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1339
1340 // If EmitVAArg fails, we fall back to the LLVM instruction.
1341 if (!ArgPtr)
1342 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1343
1344 // FIXME: volatile?
1345 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001346}
1347
Chris Lattner307da022007-11-30 17:56:23 +00001348Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001349 std::string str;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001350 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001351
1352 llvm::Constant *C = llvm::ConstantArray::get(str);
1353 C = new llvm::GlobalVariable(C->getType(), true,
1354 llvm::GlobalValue::InternalLinkage,
1355 C, ".str", &CGF.CGM.getModule());
1356 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1357 llvm::Constant *Zeros[] = { Zero, Zero };
1358 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1359
1360 return C;
1361}
1362
Mike Stump4eb81dc2009-02-12 18:29:15 +00001363enum {
1364 BLOCK_NEEDS_FREE = (1 << 24),
1365 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
1366 BLOCK_HAS_CXX_OBJ = (1 << 26),
1367 BLOCK_IS_GC = (1 << 27),
1368 BLOCK_IS_GLOBAL = (1 << 28),
1369 BLOCK_HAS_DESCRIPTOR = (1 << 29)
1370};
1371
1372llvm::Constant *ScalarExprEmitter::BuildDescriptorBlockDecl() {
1373 // FIXME: Push up.
1374 bool BlockHasCopyDispose = false;
1375
1376 const llvm::PointerType *PtrToInt8Ty
1377 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1378 llvm::Constant *C;
1379 std::vector<llvm::Constant*> Elts;
1380
1381 // reserved
1382 const llvm::IntegerType *LongTy
1383 = cast<llvm::IntegerType>(
1384 CGF.CGM.getTypes().ConvertType(CGF.CGM.getContext().LongTy));
1385 C = llvm::ConstantInt::get(LongTy, 0);
1386 Elts.push_back(C);
1387
1388 // Size
1389 // FIXME: This should be the size of BlockStructType
1390 C = llvm::ConstantInt::get(LongTy, 20);
1391 Elts.push_back(C);
1392
1393 if (BlockHasCopyDispose) {
1394 // copy_func_helper_decl
1395 C = llvm::ConstantInt::get(LongTy, 0);
1396 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1397 Elts.push_back(C);
1398
1399 // destroy_func_decl
1400 C = llvm::ConstantInt::get(LongTy, 0);
1401 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1402 Elts.push_back(C);
1403 }
1404
1405 C = llvm::ConstantStruct::get(Elts);
1406
1407 // FIXME: Should be in module?
1408 static int desc_unique_count;
1409 char Name[32];
1410 sprintf(Name, "__block_descriptor_tmp_%d", ++desc_unique_count);
1411 C = new llvm::GlobalVariable(C->getType(), true,
1412 llvm::GlobalValue::InternalLinkage,
1413 C, Name, &CGF.CGM.getModule());
1414 return C;
1415}
1416
1417llvm::Constant *ScalarExprEmitter::BuildBlockLiteralTmp() {
1418 // FIXME: Push up
1419 bool BlockHasCopyDispose = false;
1420 bool insideFunction = false;
1421 bool BlockRefDeclList = false;
1422 bool BlockByrefDeclList = false;
1423
1424 std::vector<llvm::Constant*> Elts;
1425 llvm::Constant *C;
1426
1427 bool staticBlockTmp = (BlockRefDeclList == 0
1428 && BlockByrefDeclList == 0);
1429
1430 {
1431 // C = BuildBlockStructInitlist();
1432 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
1433
1434 if (BlockHasCopyDispose)
1435 flags |= BLOCK_HAS_COPY_DISPOSE;
1436
1437 const llvm::PointerType *PtrToInt8Ty
1438 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1439 // FIXME: static? What if we start up a new, unrelated module?
1440 // logically we want 1 per module.
1441 static llvm::Constant *NSConcreteGlobalBlock_decl
1442 = new llvm::GlobalVariable(PtrToInt8Ty, false,
1443 llvm::GlobalValue::ExternalLinkage,
1444 0, "_NSConcreteGlobalBlock",
1445 &CGF.CGM.getModule());
1446 static llvm::Constant *NSConcreteStackBlock_decl
1447 = new llvm::GlobalVariable(PtrToInt8Ty, false,
1448 llvm::GlobalValue::ExternalLinkage,
1449 0, "_NSConcreteStackBlock",
1450 &CGF.CGM.getModule());
1451 C = NSConcreteStackBlock_decl;
1452 if (!insideFunction ||
1453 (!BlockRefDeclList && !BlockByrefDeclList)) {
1454 C = NSConcreteGlobalBlock_decl;
1455 flags |= BLOCK_IS_GLOBAL;
1456 }
1457 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1458 Elts.push_back(C);
1459
1460 // __flags
1461 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
1462 CGF.CGM.getTypes().ConvertType(CGF.CGM.getContext().IntTy));
1463 C = llvm::ConstantInt::get(IntTy, flags);
1464 Elts.push_back(C);
1465
1466 // __reserved
1467 C = llvm::ConstantInt::get(IntTy, 0);
1468 Elts.push_back(C);
1469
1470 // __FuncPtr
1471 // FIXME: Build this up.
1472 Elts.push_back(C);
1473
1474 // __descriptor
1475 Elts.push_back(BuildDescriptorBlockDecl());
1476
1477 // FIXME: Add block_original_ref_decl_list and block_byref_decl_list.
1478 }
1479
1480 C = llvm::ConstantStruct::get(Elts);
1481
1482 char Name[32];
1483 // FIXME: Boost in CGM?
1484 static int global_unique_count;
1485 sprintf(Name, "__block_holder_tmp_%d", ++global_unique_count);
1486 C = new llvm::GlobalVariable(C->getType(), true,
1487 llvm::GlobalValue::InternalLinkage,
1488 C, Name, &CGF.CGM.getModule());
1489 return C;
1490}
1491
1492Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
1493 llvm::Constant *C = BuildBlockLiteralTmp();
1494
1495 const llvm::PointerType *PtrToInt8Ty
1496 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1497 return llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1498}
1499
Chris Lattner9fba49a2007-08-24 05:35:26 +00001500//===----------------------------------------------------------------------===//
1501// Entry Point into this File
1502//===----------------------------------------------------------------------===//
1503
1504/// EmitComplexExpr - Emit the computation of the specified expression of
1505/// complex type, ignoring the result.
1506Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1507 assert(E && !hasAggregateLLVMType(E->getType()) &&
1508 "Invalid scalar expression to emit");
1509
1510 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1511}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001512
1513/// EmitScalarConversion - Emit a conversion from the specified type to the
1514/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001515Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1516 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001517 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1518 "Invalid scalar expression to emit");
1519 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1520}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001521
1522/// EmitComplexToScalarConversion - Emit a conversion from the specified
1523/// complex type to the specified destination type, where the destination
1524/// type is an LLVM scalar type.
1525Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1526 QualType SrcTy,
1527 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001528 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001529 "Invalid complex -> scalar conversion");
1530 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1531 DstTy);
1532}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001533
1534Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1535 assert(V1->getType() == V2->getType() &&
1536 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001537 unsigned NumElements =
1538 cast<llvm::VectorType>(V1->getType())->getNumElements();
1539
1540 va_list va;
1541 va_start(va, V2);
1542
1543 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001544 for (unsigned i = 0; i < NumElements; i++) {
1545 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001546 assert(n >= 0 && n < (int)NumElements * 2 &&
1547 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001548 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1549 }
1550
1551 const char *Name = va_arg(va, const char *);
1552 va_end(va);
1553
1554 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1555
1556 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1557}
1558
Anders Carlsson68b8be92007-12-15 21:23:30 +00001559llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001560 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001561 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001562 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001563
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001564 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001565 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001566 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001567 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001568 }
1569
1570 return Vec;
1571}