blob: 2e2eea3e3105a1cab65d63b250b4c007932ceb69 [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"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000022#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000023#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000024#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000025#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000026
Chris Lattner9fba49a2007-08-24 05:35:26 +000027using namespace clang;
28using namespace CodeGen;
29using llvm::Value;
30
31//===----------------------------------------------------------------------===//
32// Scalar Expression Emitter
33//===----------------------------------------------------------------------===//
34
35struct BinOpInfo {
36 Value *LHS;
37 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000038 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000039 const BinaryOperator *E;
40};
41
42namespace {
43class VISIBILITY_HIDDEN ScalarExprEmitter
44 : public StmtVisitor<ScalarExprEmitter, Value*> {
45 CodeGenFunction &CGF;
Chris Lattnerfaf23db2008-08-08 19:57:58 +000046 llvm::IRBuilder<> &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000047
Chris Lattner9fba49a2007-08-24 05:35:26 +000048public:
49
Chris Lattnercbfb5512008-03-01 08:45:05 +000050 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbarf1f7f192008-08-20 00:28:19 +000051 Builder(CGF.Builder) {
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 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000112 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
113 return llvm::Constant::getNullValue(ConvertType(E->getType()));
114 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000115 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
116 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000117 CGF.getContext().typesAreCompatible(
118 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000119 }
120 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
121 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
122 }
Daniel Dunbar879788d2008-08-04 16:51:22 +0000123 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000124 llvm::Value *V =
125 llvm::ConstantInt::get(llvm::Type::Int32Ty,
126 CGF.GetIDForAddrOfLabel(E->getLabel()));
127
128 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000129 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000130
131 // l-values.
132 Value *VisitDeclRefExpr(DeclRefExpr *E) {
133 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
134 return llvm::ConstantInt::get(EC->getInitVal());
135 return EmitLoadOfLValue(E);
136 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000137 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
138 return CGF.EmitObjCSelectorExpr(E);
139 }
140 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
141 return CGF.EmitObjCProtocolExpr(E);
142 }
143 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
144 return EmitLoadOfLValue(E);
145 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000146 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000147 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000148 }
149 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
150 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000151 }
152
Chris Lattner9fba49a2007-08-24 05:35:26 +0000153 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000154 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000155 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000156 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000157 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
158 return EmitLoadOfLValue(E);
159 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000160 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattner69909292008-08-10 01:53:14 +0000161 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000162
163 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000164 unsigned NumInitElements = E->getNumInits();
165
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000166 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000167 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
168
169 // We have a scalar in braces. Just use the first element.
170 if (!VType)
171 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000172
Chris Lattnera9177982008-10-26 23:53:12 +0000173 if (E->hadDesignators()) {
174 CGF.ErrorUnsupported(E, "initializer list with designators");
175 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
176 }
177
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000178 unsigned NumVectorElements = VType->getNumElements();
179 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000180
181 // Emit individual vector element stores.
182 llvm::Value *V = llvm::UndefValue::get(VType);
183
Anders Carlsson323d5682007-12-18 02:45:33 +0000184 // Emit initializers
185 unsigned i;
186 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000187 Value *NewV = Visit(E->getInit(i));
188 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
189 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000190 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000191
192 // Emit remaining default initializers
193 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
194 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
195 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
196 V = Builder.CreateInsertElement(V, NewV, Idx);
197 }
198
Devang Patel32c39832007-10-24 18:05:48 +0000199 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000200 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000201
Chris Lattner9fba49a2007-08-24 05:35:26 +0000202 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
203 Value *VisitCastExpr(const CastExpr *E) {
204 return EmitCastExpr(E->getSubExpr(), E->getType());
205 }
206 Value *EmitCastExpr(const Expr *E, QualType T);
207
208 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000209 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000210 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000211
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000212 Value *VisitStmtExpr(const StmtExpr *E);
213
Chris Lattner9fba49a2007-08-24 05:35:26 +0000214 // Unary Operators.
215 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
216 Value *VisitUnaryPostDec(const UnaryOperator *E) {
217 return VisitPrePostIncDec(E, false, false);
218 }
219 Value *VisitUnaryPostInc(const UnaryOperator *E) {
220 return VisitPrePostIncDec(E, true, false);
221 }
222 Value *VisitUnaryPreDec(const UnaryOperator *E) {
223 return VisitPrePostIncDec(E, false, true);
224 }
225 Value *VisitUnaryPreInc(const UnaryOperator *E) {
226 return VisitPrePostIncDec(E, true, true);
227 }
228 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
229 return EmitLValue(E->getSubExpr()).getAddress();
230 }
231 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
232 Value *VisitUnaryPlus(const UnaryOperator *E) {
233 return Visit(E->getSubExpr());
234 }
235 Value *VisitUnaryMinus (const UnaryOperator *E);
236 Value *VisitUnaryNot (const UnaryOperator *E);
237 Value *VisitUnaryLNot (const UnaryOperator *E);
238 Value *VisitUnarySizeOf (const UnaryOperator *E) {
239 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
240 }
241 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
242 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
243 }
244 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000245 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000246 Value *VisitUnaryReal (const UnaryOperator *E);
247 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000248 Value *VisitUnaryExtension(const UnaryOperator *E) {
249 return Visit(E->getSubExpr());
250 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000251 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000252 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
253 return Visit(DAE->getExpr());
254 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000255
Chris Lattner9fba49a2007-08-24 05:35:26 +0000256 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000257 Value *EmitMul(const BinOpInfo &Ops) {
258 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
259 }
260 Value *EmitDiv(const BinOpInfo &Ops);
261 Value *EmitRem(const BinOpInfo &Ops);
262 Value *EmitAdd(const BinOpInfo &Ops);
263 Value *EmitSub(const BinOpInfo &Ops);
264 Value *EmitShl(const BinOpInfo &Ops);
265 Value *EmitShr(const BinOpInfo &Ops);
266 Value *EmitAnd(const BinOpInfo &Ops) {
267 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
268 }
269 Value *EmitXor(const BinOpInfo &Ops) {
270 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
271 }
272 Value *EmitOr (const BinOpInfo &Ops) {
273 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
274 }
275
Chris Lattner660e31d2007-08-24 21:00:35 +0000276 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000277 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000278 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
279
280 // Binary operators and binary compound assignment operators.
281#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000282 Value *VisitBin ## OP(const BinaryOperator *E) { \
283 return Emit ## OP(EmitBinOps(E)); \
284 } \
285 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
286 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000287 }
288 HANDLEBINOP(Mul);
289 HANDLEBINOP(Div);
290 HANDLEBINOP(Rem);
291 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000292 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000293 HANDLEBINOP(Shl);
294 HANDLEBINOP(Shr);
295 HANDLEBINOP(And);
296 HANDLEBINOP(Xor);
297 HANDLEBINOP(Or);
298#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000299
Chris Lattner9fba49a2007-08-24 05:35:26 +0000300 // Comparisons.
301 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
302 unsigned SICmpOpc, unsigned FCmpOpc);
303#define VISITCOMP(CODE, UI, SI, FP) \
304 Value *VisitBin##CODE(const BinaryOperator *E) { \
305 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
306 llvm::FCmpInst::FP); }
307 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
308 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
309 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
310 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
311 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
312 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
313#undef VISITCOMP
314
315 Value *VisitBinAssign (const BinaryOperator *E);
316
317 Value *VisitBinLAnd (const BinaryOperator *E);
318 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000319 Value *VisitBinComma (const BinaryOperator *E);
320
321 // Other Operators.
322 Value *VisitConditionalOperator(const ConditionalOperator *CO);
323 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000324 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000325 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000326 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
327 return CGF.EmitObjCStringLiteral(E);
328 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000329 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000330};
331} // end anonymous namespace.
332
333//===----------------------------------------------------------------------===//
334// Utilities
335//===----------------------------------------------------------------------===//
336
Chris Lattnerd8d44222007-08-26 16:42:57 +0000337/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000338/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000339Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
340 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
341
342 if (SrcType->isRealFloatingType()) {
343 // Compare against 0.0 for fp scalars.
344 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000345 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
346 }
347
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000348 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000349 "Unknown scalar type to convert");
350
351 // Because of the type rules of C, we often end up computing a logical value,
352 // then zero extending it to int, then wanting it as a logical value again.
353 // Optimize this common case.
354 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
355 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
356 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000357 // If there aren't any more uses, zap the instruction to save space.
358 // Note that there can be more uses, for example if this
359 // is the result of an assignment.
360 if (ZI->use_empty())
361 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000362 return Result;
363 }
364 }
365
366 // Compare against an integer or pointer null.
367 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
368 return Builder.CreateICmpNE(Src, Zero, "tobool");
369}
370
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000371/// EmitScalarConversion - Emit a conversion from the specified type to the
372/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000373Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
374 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000375 SrcType = CGF.getContext().getCanonicalType(SrcType);
376 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000377 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000378
379 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000380
381 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000382 if (DstType->isBooleanType())
383 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000384
385 const llvm::Type *DstTy = ConvertType(DstType);
386
387 // Ignore conversions like int -> uint.
388 if (Src->getType() == DstTy)
389 return Src;
390
Daniel Dunbar238335f2008-08-25 09:51:32 +0000391 // Handle pointer conversions next: pointers can only be converted
392 // to/from other pointers and integers. Check for pointer types in
393 // terms of LLVM, as some native types (like Obj-C id) may map to a
394 // pointer type.
395 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000396 // The source value may be an integer, or a pointer.
397 if (isa<llvm::PointerType>(Src->getType()))
398 return Builder.CreateBitCast(Src, DstTy, "conv");
399 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
400 return Builder.CreateIntToPtr(Src, DstTy, "conv");
401 }
402
Daniel Dunbar238335f2008-08-25 09:51:32 +0000403 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000404 // Must be an ptr to int cast.
405 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000406 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000407 }
408
Nate Begemanaf6ed502008-04-18 23:10:10 +0000409 // A scalar can be splatted to an extended vector of the same element type
410 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner4f025a42008-02-02 04:51:41 +0000411 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000412 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
413 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000414
Chris Lattner4f025a42008-02-02 04:51:41 +0000415 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000416 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000417 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000418 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000419
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000420 // Finally, we have the arithmetic types: real int/float.
421 if (isa<llvm::IntegerType>(Src->getType())) {
422 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000423 if (isa<llvm::IntegerType>(DstTy))
424 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
425 else if (InputSigned)
426 return Builder.CreateSIToFP(Src, DstTy, "conv");
427 else
428 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000429 }
430
431 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
432 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000433 if (DstType->isSignedIntegerType())
434 return Builder.CreateFPToSI(Src, DstTy, "conv");
435 else
436 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000437 }
438
439 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000440 if (DstTy->getTypeID() < Src->getType()->getTypeID())
441 return Builder.CreateFPTrunc(Src, DstTy, "conv");
442 else
443 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000444}
445
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000446/// EmitComplexToScalarConversion - Emit a conversion from the specified
447/// complex type to the specified destination type, where the destination
448/// type is an LLVM scalar type.
449Value *ScalarExprEmitter::
450EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
451 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000452 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000453 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000454
455 // Handle conversions to bool first, they are special: comparisons against 0.
456 if (DstTy->isBooleanType()) {
457 // Complex != 0 -> (Real != 0) | (Imag != 0)
458 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
459 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
460 return Builder.CreateOr(Src.first, Src.second, "tobool");
461 }
462
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000463 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
464 // the imaginary part of the complex value is discarded and the value of the
465 // real part is converted according to the conversion rules for the
466 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000467 return EmitScalarConversion(Src.first, SrcTy, DstTy);
468}
469
470
Chris Lattner9fba49a2007-08-24 05:35:26 +0000471//===----------------------------------------------------------------------===//
472// Visitor Methods
473//===----------------------------------------------------------------------===//
474
475Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000476 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000477 if (E->getType()->isVoidType())
478 return 0;
479 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
480}
481
Eli Friedmand0e9d092008-05-14 19:38:39 +0000482Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
483 llvm::SmallVector<llvm::Constant*, 32> indices;
484 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
485 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
486 }
487 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
488 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
489 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
490 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
491}
492
Chris Lattner9fba49a2007-08-24 05:35:26 +0000493Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
494 // Emit subscript expressions in rvalue context's. For most cases, this just
495 // loads the lvalue formed by the subscript expr. However, we have to be
496 // careful, because the base of a vector subscript is occasionally an rvalue,
497 // so we can't get it as an lvalue.
498 if (!E->getBase()->getType()->isVectorType())
499 return EmitLoadOfLValue(E);
500
501 // Handle the vector case. The base must be a vector, the index must be an
502 // integer value.
503 Value *Base = Visit(E->getBase());
504 Value *Idx = Visit(E->getIdx());
505
506 // FIXME: Convert Idx to i32 type.
507 return Builder.CreateExtractElement(Base, Idx, "vecext");
508}
509
510/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
511/// also handle things like function to pointer-to-function decay, and array to
512/// pointer decay.
513Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
514 const Expr *Op = E->getSubExpr();
515
516 // If this is due to array->pointer conversion, emit the array expression as
517 // an l-value.
518 if (Op->getType()->isArrayType()) {
519 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
520 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000521 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000522
Daniel Dunbar952f4732008-08-29 17:28:43 +0000523 if (!(isa<llvm::PointerType>(V->getType()) &&
524 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
525 ->getElementType()))) {
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000526 CGF.ErrorUnsupported(E, "variable-length array cast", true);
Daniel Dunbar952f4732008-08-29 17:28:43 +0000527 if (E->getType()->isVoidType())
528 return 0;
529 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
530 }
Chris Lattner07307562008-03-19 05:19:41 +0000531 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000532
533 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000534 // types as well (e.g. void*) and can be implicitly converted to integer.
535 const llvm::Type *DestTy = ConvertType(E->getType());
536 if (V->getType() != DestTy) {
537 if (isa<llvm::PointerType>(DestTy))
538 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
539 else {
540 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
541 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
542 }
543 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000544 return V;
545
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000546 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000547 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000548 }
549
550 return EmitCastExpr(Op, E->getType());
551}
552
553
554// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
555// have to handle a more broad range of conversions than explicit casts, as they
556// handle things like function to ptr-to-function decay etc.
557Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000558 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000559
560 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000561 Value *Src = Visit(const_cast<Expr*>(E));
562
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000563 // Use EmitScalarConversion to perform the conversion.
564 return EmitScalarConversion(Src, E->getType(), DestTy);
565 }
Chris Lattner77288792008-02-16 23:55:16 +0000566
Chris Lattnerde0908b2008-04-04 16:54:41 +0000567 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000568 // Handle cases where the source is a complex type.
569 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
570 DestTy);
571 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000572
Chris Lattner77288792008-02-16 23:55:16 +0000573 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
574 // evaluate the result and return.
575 CGF.EmitAggExpr(E, 0, false);
576 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000577}
578
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000579Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000580 return CGF.EmitCompoundStmt(*E->getSubStmt(),
581 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000582}
583
584
Chris Lattner9fba49a2007-08-24 05:35:26 +0000585//===----------------------------------------------------------------------===//
586// Unary Operators
587//===----------------------------------------------------------------------===//
588
589Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000590 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000591 LValue LV = EmitLValue(E->getSubExpr());
592 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000593 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000594 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000595
596 int AmountVal = isInc ? 1 : -1;
597
598 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000599 if (isa<llvm::PointerType>(InVal->getType())) {
600 // FIXME: This isn't right for VLAs.
601 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000602 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000603 } else {
604 // Add the inc/dec to the real part.
605 if (isa<llvm::IntegerType>(InVal->getType()))
606 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000607 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000608 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000609 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000610 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000611 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000612 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000613 else {
614 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000615 bool ignored;
616 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
617 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000618 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000619 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000620 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
621 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000622
623 // Store the updated result through the lvalue.
624 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
625 E->getSubExpr()->getType());
626
627 // If this is a postinc, return the value read from memory, otherwise use the
628 // updated value.
629 return isPre ? NextVal : InVal;
630}
631
632
633Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
634 Value *Op = Visit(E->getSubExpr());
635 return Builder.CreateNeg(Op, "neg");
636}
637
638Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
639 Value *Op = Visit(E->getSubExpr());
640 return Builder.CreateNot(Op, "neg");
641}
642
643Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
644 // Compare operand to zero.
645 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
646
647 // Invert value.
648 // TODO: Could dynamically modify easy computations here. For example, if
649 // the operand is an icmp ne, turn into icmp eq.
650 BoolVal = Builder.CreateNot(BoolVal, "lnot");
651
652 // ZExt result to int.
653 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
654}
655
656/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
657/// an integer (RetType).
658Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000659 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000660 assert(RetType->isIntegerType() && "Result type must be an integer!");
661 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000662 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000663
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000664 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
665 // for function types.
Daniel Dunbar1c73aa22008-07-22 19:44:18 +0000666 // FIXME: what is alignof a function type in gcc?
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000667 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattner20515462008-02-21 05:45:29 +0000668 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
669
Chris Lattner9fba49a2007-08-24 05:35:26 +0000670 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000671 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000672
673 uint64_t Val = isSizeOf ? Info.first : Info.second;
674 Val /= 8; // Return size in bytes, not bits.
675
Chris Lattner9fba49a2007-08-24 05:35:26 +0000676 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
677}
678
Chris Lattner01211af2007-08-24 21:20:17 +0000679Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
680 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000681 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000682 return CGF.EmitComplexExpr(Op).first;
683 return Visit(Op);
684}
685Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
686 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000687 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000688 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000689
690 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
691 // effects are evaluated.
692 CGF.EmitScalarExpr(Op);
693 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000694}
695
Anders Carlsson52774ad2008-01-29 15:56:48 +0000696Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
697{
698 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
699
700 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
701
Chris Lattner8cd0e932008-03-05 18:54:05 +0000702 uint32_t ResultWidth =
703 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000704 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
705}
Chris Lattner01211af2007-08-24 21:20:17 +0000706
Chris Lattner9fba49a2007-08-24 05:35:26 +0000707//===----------------------------------------------------------------------===//
708// Binary Operators
709//===----------------------------------------------------------------------===//
710
711BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
712 BinOpInfo Result;
713 Result.LHS = Visit(E->getLHS());
714 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000715 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000716 Result.E = E;
717 return Result;
718}
719
Chris Lattner0d965302007-08-26 21:41:21 +0000720Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000721 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
722 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
723
724 BinOpInfo OpInfo;
725
726 // Load the LHS and RHS operands.
727 LValue LHSLV = EmitLValue(E->getLHS());
728 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000729
730 // Determine the computation type. If the RHS is complex, then this is one of
731 // the add/sub/mul/div operators. All of these operators can be computed in
732 // with just their real component even though the computation domain really is
733 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000734 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000735
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000736 // If the computation type is complex, then the RHS is complex. Emit the RHS.
737 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
738 ComputeType = CT->getElementType();
739
740 // Emit the RHS, only keeping the real component.
741 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
742 RHSTy = RHSTy->getAsComplexType()->getElementType();
743 } else {
744 // Otherwise the RHS is a simple scalar value.
745 OpInfo.RHS = Visit(E->getRHS());
746 }
747
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000748 QualType LComputeTy, RComputeTy, ResultTy;
749
750 // Compound assignment does not contain enough information about all
751 // the types involved for pointer arithmetic cases. Figure it out
752 // here for now.
753 if (E->getLHS()->getType()->isPointerType()) {
754 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
755 assert((E->getOpcode() == BinaryOperator::AddAssign ||
756 E->getOpcode() == BinaryOperator::SubAssign) &&
757 "Invalid compound assignment operator on pointer type.");
758 LComputeTy = E->getLHS()->getType();
759
760 if (E->getRHS()->getType()->isPointerType()) {
761 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
762 // extension, the conversion from the pointer difference back to
763 // the LHS type is handled at the end.
764 assert(E->getOpcode() == BinaryOperator::SubAssign &&
765 "Invalid compound assignment operator on pointer type.");
766 RComputeTy = E->getLHS()->getType();
767 ResultTy = CGF.getContext().getPointerDiffType();
768 } else {
769 RComputeTy = E->getRHS()->getType();
770 ResultTy = LComputeTy;
771 }
772 } else if (E->getRHS()->getType()->isPointerType()) {
773 // Degenerate case of (int += ptr) allowed by GCC implicit cast
774 // extension.
775 assert(E->getOpcode() == BinaryOperator::AddAssign &&
776 "Invalid compound assignment operator on pointer type.");
777 LComputeTy = E->getLHS()->getType();
778 RComputeTy = E->getRHS()->getType();
779 ResultTy = RComputeTy;
780 } else {
781 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000782 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000783
784 // Convert the LHS/RHS values to the computation type.
785 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
786 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
787 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000788 OpInfo.E = E;
789
790 // Expand the binary operator.
791 Value *Result = (this->*Func)(OpInfo);
792
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000793 // Convert the result back to the LHS type.
794 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000795
796 // Store the result value into the LHS lvalue.
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000797 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000798
Daniel Dunbare6c31752008-08-29 08:11:39 +0000799 // For bitfields, we need the value in the bitfield. Note that
800 // property references do not reload their value (even though the
801 // setter may have changed it).
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000802 // FIXME: This adds an extra bitfield load
803 if (LHSLV.isBitfield())
804 Result = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000805 return Result;
806}
807
808
Chris Lattner9fba49a2007-08-24 05:35:26 +0000809Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000810 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000811 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000812 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000813 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
814 else
815 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
816}
817
818Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
819 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000820 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000821 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
822 else
823 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
824}
825
826
827Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000828 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000829 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000830
831 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000832 Value *Ptr, *Idx;
833 Expr *IdxExp;
834 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
835 Ptr = Ops.LHS;
836 Idx = Ops.RHS;
837 IdxExp = Ops.E->getRHS();
838 } else { // int + pointer
839 Ptr = Ops.RHS;
840 Idx = Ops.LHS;
841 IdxExp = Ops.E->getLHS();
842 }
843
844 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
845 if (Width < CGF.LLVMPointerWidth) {
846 // Zero or sign extend the pointer value based on whether the index is
847 // signed or not.
848 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000849 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000850 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
851 else
852 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
853 }
854
855 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000856}
857
858Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
859 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
860 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000861
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000862 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
863 // pointer - int
864 Value *Idx = Ops.RHS;
865 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
866 if (Width < CGF.LLVMPointerWidth) {
867 // Zero or sign extend the pointer value based on whether the index is
868 // signed or not.
869 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
870 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
871 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
872 else
873 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
874 }
875 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
876
877 // FIXME: The pointer could point to a VLA.
878 // The GNU void* - int case is automatically handled here because
879 // our LLVM type for void* is i8*.
880 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000881 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000882 // pointer - pointer
883 Value *LHS = Ops.LHS;
884 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000885
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000886 const QualType LHSType = Ops.E->getLHS()->getType();
887 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
888 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000889
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000890 // Handle GCC extension for pointer arithmetic on void* types.
891 if (LHSElementType->isVoidType()) {
892 ElementSize = 1;
893 } else {
894 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
895 }
896
897 const llvm::Type *ResultType = ConvertType(Ops.Ty);
898 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
899 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
900 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
901
902 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
903 // remainder. As such, we handle common power-of-two cases here to generate
904 // better code. See PR2247.
905 if (llvm::isPowerOf2_64(ElementSize)) {
906 Value *ShAmt =
907 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
908 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
909 }
910
911 // Otherwise, do a full sdiv.
912 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
913 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000914 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000915}
916
917Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
918 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
919 // RHS to the same size as the LHS.
920 Value *RHS = Ops.RHS;
921 if (Ops.LHS->getType() != RHS->getType())
922 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
923
924 return Builder.CreateShl(Ops.LHS, RHS, "shl");
925}
926
927Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
928 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
929 // RHS to the same size as the LHS.
930 Value *RHS = Ops.RHS;
931 if (Ops.LHS->getType() != RHS->getType())
932 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
933
Chris Lattner660e31d2007-08-24 21:00:35 +0000934 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000935 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
936 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
937}
938
939Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
940 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000941 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000942 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +0000943 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000944 Value *LHS = Visit(E->getLHS());
945 Value *RHS = Visit(E->getRHS());
946
947 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +0000948 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000949 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000950 } else if (LHSTy->isSignedIntegerType()) {
951 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000952 LHS, RHS, "cmp");
953 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000954 // Unsigned integers and pointers.
955 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000956 LHS, RHS, "cmp");
957 }
Nate Begeman1591bc52008-07-25 20:16:05 +0000958 } else if (LHSTy->isVectorType()) {
959 Value *LHS = Visit(E->getLHS());
960 Value *RHS = Visit(E->getRHS());
961
962 if (LHS->getType()->isFPOrFPVector()) {
963 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
964 LHS, RHS, "cmp");
965 } else if (LHSTy->isUnsignedIntegerType()) {
966 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
967 LHS, RHS, "cmp");
968 } else {
969 // Signed integers and pointers.
970 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
971 LHS, RHS, "cmp");
972 }
973 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000974 } else {
975 // Complex Comparison: can only be an equality comparison.
976 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
977 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
978
Chris Lattnerc154ac12008-07-26 22:37:01 +0000979 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000980
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000981 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000982 if (CETy->isRealFloatingType()) {
983 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
984 LHS.first, RHS.first, "cmp.r");
985 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
986 LHS.second, RHS.second, "cmp.i");
987 } else {
988 // Complex comparisons can only be equality comparisons. As such, signed
989 // and unsigned opcodes are the same.
990 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
991 LHS.first, RHS.first, "cmp.r");
992 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
993 LHS.second, RHS.second, "cmp.i");
994 }
995
996 if (E->getOpcode() == BinaryOperator::EQ) {
997 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
998 } else {
999 assert(E->getOpcode() == BinaryOperator::NE &&
1000 "Complex comparison other than == or != ?");
1001 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1002 }
1003 }
1004
1005 // ZExt result to int.
1006 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1007}
1008
1009Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1010 LValue LHS = EmitLValue(E->getLHS());
1011 Value *RHS = Visit(E->getRHS());
1012
1013 // Store the value into the LHS.
1014 // FIXME: Volatility!
1015 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001016
Daniel Dunbare6c31752008-08-29 08:11:39 +00001017 // For bitfields, we need the value in the bitfield. Note that
1018 // property references do not reload their value (even though the
1019 // setter may have changed it).
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001020 // FIXME: This adds an extra bitfield load
1021 if (LHS.isBitfield())
1022 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Daniel Dunbare6c31752008-08-29 08:11:39 +00001023
Chris Lattner9fba49a2007-08-24 05:35:26 +00001024 // Return the RHS.
1025 return RHS;
1026}
1027
1028Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1029 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1030
Gabor Greif815e2c12008-04-06 20:42:52 +00001031 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1032 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001033
1034 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1035 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1036
1037 CGF.EmitBlock(RHSBlock);
1038 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1039
1040 // Reaquire the RHS block, as there may be subblocks inserted.
1041 RHSBlock = Builder.GetInsertBlock();
1042 CGF.EmitBlock(ContBlock);
1043
1044 // Create a PHI node. If we just evaluted the LHS condition, the result is
1045 // false. If we evaluated both, the result is the RHS condition.
1046 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1047 PN->reserveOperandSpace(2);
1048 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1049 PN->addIncoming(RHSCond, RHSBlock);
1050
1051 // ZExt result to int.
1052 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1053}
1054
1055Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1056 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1057
Gabor Greif815e2c12008-04-06 20:42:52 +00001058 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1059 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001060
1061 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1062 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1063
1064 CGF.EmitBlock(RHSBlock);
1065 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1066
1067 // Reaquire the RHS block, as there may be subblocks inserted.
1068 RHSBlock = Builder.GetInsertBlock();
1069 CGF.EmitBlock(ContBlock);
1070
1071 // Create a PHI node. If we just evaluted the LHS condition, the result is
1072 // true. If we evaluated both, the result is the RHS condition.
1073 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1074 PN->reserveOperandSpace(2);
1075 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1076 PN->addIncoming(RHSCond, RHSBlock);
1077
1078 // ZExt result to int.
1079 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1080}
1081
1082Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1083 CGF.EmitStmt(E->getLHS());
1084 return Visit(E->getRHS());
1085}
1086
1087//===----------------------------------------------------------------------===//
1088// Other Operators
1089//===----------------------------------------------------------------------===//
1090
1091Value *ScalarExprEmitter::
1092VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001093 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1094 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1095 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001096
Chris Lattner98a425c2007-11-26 01:40:58 +00001097 // Evaluate the conditional, then convert it to bool. We do this explicitly
1098 // because we need the unconverted value if this is a GNU ?: expression with
1099 // missing middle value.
1100 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001101 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1102 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001103 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001104
1105 CGF.EmitBlock(LHSBlock);
1106
1107 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001108 Value *LHS;
1109 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001110 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001111 else // Perform promotions, to handle cases like "short ?: int"
1112 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1113
Chris Lattner9fba49a2007-08-24 05:35:26 +00001114 Builder.CreateBr(ContBlock);
1115 LHSBlock = Builder.GetInsertBlock();
1116
1117 CGF.EmitBlock(RHSBlock);
1118
Eli Friedmance8d7032008-05-16 20:38:39 +00001119 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001120 Builder.CreateBr(ContBlock);
1121 RHSBlock = Builder.GetInsertBlock();
1122
1123 CGF.EmitBlock(ContBlock);
1124
Nuno Lopesb62ff242008-06-04 19:15:45 +00001125 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001126 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1127 return 0;
1128 }
1129
Chris Lattner9fba49a2007-08-24 05:35:26 +00001130 // Create a PHI node for the real part.
1131 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1132 PN->reserveOperandSpace(2);
1133 PN->addIncoming(LHS, LHSBlock);
1134 PN->addIncoming(RHS, RHSBlock);
1135 return PN;
1136}
1137
1138Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001139 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001140 return
1141 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001142}
1143
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001144Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001145 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001146 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001147}
1148
Chris Lattner307da022007-11-30 17:56:23 +00001149Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001150 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1151
1152 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1153 return V;
1154}
1155
Chris Lattner307da022007-11-30 17:56:23 +00001156Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001157 std::string str;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001158 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001159
1160 llvm::Constant *C = llvm::ConstantArray::get(str);
1161 C = new llvm::GlobalVariable(C->getType(), true,
1162 llvm::GlobalValue::InternalLinkage,
1163 C, ".str", &CGF.CGM.getModule());
1164 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1165 llvm::Constant *Zeros[] = { Zero, Zero };
1166 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1167
1168 return C;
1169}
1170
Chris Lattner9fba49a2007-08-24 05:35:26 +00001171//===----------------------------------------------------------------------===//
1172// Entry Point into this File
1173//===----------------------------------------------------------------------===//
1174
1175/// EmitComplexExpr - Emit the computation of the specified expression of
1176/// complex type, ignoring the result.
1177Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1178 assert(E && !hasAggregateLLVMType(E->getType()) &&
1179 "Invalid scalar expression to emit");
1180
1181 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1182}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001183
1184/// EmitScalarConversion - Emit a conversion from the specified type to the
1185/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001186Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1187 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001188 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1189 "Invalid scalar expression to emit");
1190 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1191}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001192
1193/// EmitComplexToScalarConversion - Emit a conversion from the specified
1194/// complex type to the specified destination type, where the destination
1195/// type is an LLVM scalar type.
1196Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1197 QualType SrcTy,
1198 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001199 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001200 "Invalid complex -> scalar conversion");
1201 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1202 DstTy);
1203}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001204
1205Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1206 assert(V1->getType() == V2->getType() &&
1207 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001208 unsigned NumElements =
1209 cast<llvm::VectorType>(V1->getType())->getNumElements();
1210
1211 va_list va;
1212 va_start(va, V2);
1213
1214 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001215 for (unsigned i = 0; i < NumElements; i++) {
1216 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001217 assert(n >= 0 && n < (int)NumElements * 2 &&
1218 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001219 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1220 }
1221
1222 const char *Name = va_arg(va, const char *);
1223 va_end(va);
1224
1225 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1226
1227 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1228}
1229
Anders Carlsson68b8be92007-12-15 21:23:30 +00001230llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001231 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001232 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001233 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001234
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001235 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001236 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001237 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001238 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001239 }
1240
1241 return Vec;
1242}