blob: decf539f1c8a3084457944a29ad07b50d68403b1 [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"
17#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000018#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000019#include "llvm/Constants.h"
20#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000021#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000022#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000023#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000024#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000025
Chris Lattner9fba49a2007-08-24 05:35:26 +000026using namespace clang;
27using namespace CodeGen;
28using llvm::Value;
29
30//===----------------------------------------------------------------------===//
31// Scalar Expression Emitter
32//===----------------------------------------------------------------------===//
33
34struct BinOpInfo {
35 Value *LHS;
36 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000037 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000038 const BinaryOperator *E;
39};
40
41namespace {
42class VISIBILITY_HIDDEN ScalarExprEmitter
43 : public StmtVisitor<ScalarExprEmitter, Value*> {
44 CodeGenFunction &CGF;
Chris Lattnerfaf23db2008-08-08 19:57:58 +000045 llvm::IRBuilder<> &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000046 CGObjCRuntime *Runtime;
47
Chris Lattner9fba49a2007-08-24 05:35:26 +000048public:
49
Chris Lattnercbfb5512008-03-01 08:45:05 +000050 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
51 Builder(CGF.Builder),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000052 Runtime(0) {
53 if (CGF.CGM.hasObjCRuntime())
54 Runtime = &CGF.CGM.getObjCRuntime();
Chris Lattner9fba49a2007-08-24 05:35:26 +000055 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000056
57 //===--------------------------------------------------------------------===//
58 // Utilities
59 //===--------------------------------------------------------------------===//
60
61 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
62 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
63
64 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000065 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000066 }
67
68 /// EmitLoadOfLValue - Given an expression with complex type that represents a
69 /// value l-value, this method emits the address of the l-value, then loads
70 /// and returns the result.
71 Value *EmitLoadOfLValue(const Expr *E) {
72 // FIXME: Volatile
73 return EmitLoadOfLValue(EmitLValue(E), E->getType());
74 }
75
Chris Lattnerd8d44222007-08-26 16:42:57 +000076 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000077 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000078 Value *EmitConversionToBool(Value *Src, QualType DstTy);
79
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080 /// EmitScalarConversion - Emit a conversion from the specified type to the
81 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000082 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
83
84 /// EmitComplexToScalarConversion - Emit a conversion from the specified
85 /// complex type to the specified destination type, where the destination
86 /// type is an LLVM scalar type.
87 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
88 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000089
Chris Lattner9fba49a2007-08-24 05:35:26 +000090 //===--------------------------------------------------------------------===//
91 // Visitor Methods
92 //===--------------------------------------------------------------------===//
93
94 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000095 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000096 assert(0 && "Stmt can't have complex result type!");
97 return 0;
98 }
99 Value *VisitExpr(Expr *S);
100 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
101
102 // Leaves.
103 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
104 return llvm::ConstantInt::get(E->getValue());
105 }
106 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000107 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 }
109 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000112 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
114 }
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) {
124 Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
125 CGF.GetIDForAddrOfLabel(E->getLabel()));
126 return Builder.CreateIntToPtr(V,
127 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
128 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000129
130 // l-values.
131 Value *VisitDeclRefExpr(DeclRefExpr *E) {
132 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
133 return llvm::ConstantInt::get(EC->getInitVal());
134 return EmitLoadOfLValue(E);
135 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000136 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbara5a0cdb2008-08-12 03:55:34 +0000137 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E);
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000138 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000139 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000140 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000141 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000142 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000143 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000144 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattner69909292008-08-10 01:53:14 +0000145 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000146
147 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000148 unsigned NumInitElements = E->getNumInits();
149
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000150 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000151 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
152
153 // We have a scalar in braces. Just use the first element.
154 if (!VType)
155 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000156
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000157 unsigned NumVectorElements = VType->getNumElements();
158 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000159
160 // Emit individual vector element stores.
161 llvm::Value *V = llvm::UndefValue::get(VType);
162
Anders Carlsson323d5682007-12-18 02:45:33 +0000163 // Emit initializers
164 unsigned i;
165 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000166 Value *NewV = Visit(E->getInit(i));
167 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
168 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000169 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000170
171 // Emit remaining default initializers
172 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
173 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
174 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
175 V = Builder.CreateInsertElement(V, NewV, Idx);
176 }
177
Devang Patel32c39832007-10-24 18:05:48 +0000178 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000179 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000180
Chris Lattner9fba49a2007-08-24 05:35:26 +0000181 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
182 Value *VisitCastExpr(const CastExpr *E) {
183 return EmitCastExpr(E->getSubExpr(), E->getType());
184 }
185 Value *EmitCastExpr(const Expr *E, QualType T);
186
187 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000188 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000189 }
190
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000191 Value *VisitStmtExpr(const StmtExpr *E);
192
Chris Lattner9fba49a2007-08-24 05:35:26 +0000193 // Unary Operators.
194 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
195 Value *VisitUnaryPostDec(const UnaryOperator *E) {
196 return VisitPrePostIncDec(E, false, false);
197 }
198 Value *VisitUnaryPostInc(const UnaryOperator *E) {
199 return VisitPrePostIncDec(E, true, false);
200 }
201 Value *VisitUnaryPreDec(const UnaryOperator *E) {
202 return VisitPrePostIncDec(E, false, true);
203 }
204 Value *VisitUnaryPreInc(const UnaryOperator *E) {
205 return VisitPrePostIncDec(E, true, true);
206 }
207 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
208 return EmitLValue(E->getSubExpr()).getAddress();
209 }
210 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
211 Value *VisitUnaryPlus(const UnaryOperator *E) {
212 return Visit(E->getSubExpr());
213 }
214 Value *VisitUnaryMinus (const UnaryOperator *E);
215 Value *VisitUnaryNot (const UnaryOperator *E);
216 Value *VisitUnaryLNot (const UnaryOperator *E);
217 Value *VisitUnarySizeOf (const UnaryOperator *E) {
218 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
219 }
220 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
221 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
222 }
223 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000224 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000225 Value *VisitUnaryReal (const UnaryOperator *E);
226 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000227 Value *VisitUnaryExtension(const UnaryOperator *E) {
228 return Visit(E->getSubExpr());
229 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000230 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000231 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
232 return Visit(DAE->getExpr());
233 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000234
Chris Lattner9fba49a2007-08-24 05:35:26 +0000235 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000236 Value *EmitMul(const BinOpInfo &Ops) {
237 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
238 }
239 Value *EmitDiv(const BinOpInfo &Ops);
240 Value *EmitRem(const BinOpInfo &Ops);
241 Value *EmitAdd(const BinOpInfo &Ops);
242 Value *EmitSub(const BinOpInfo &Ops);
243 Value *EmitShl(const BinOpInfo &Ops);
244 Value *EmitShr(const BinOpInfo &Ops);
245 Value *EmitAnd(const BinOpInfo &Ops) {
246 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
247 }
248 Value *EmitXor(const BinOpInfo &Ops) {
249 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
250 }
251 Value *EmitOr (const BinOpInfo &Ops) {
252 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
253 }
254
Chris Lattner660e31d2007-08-24 21:00:35 +0000255 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000256 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000257 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
258
259 // Binary operators and binary compound assignment operators.
260#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000261 Value *VisitBin ## OP(const BinaryOperator *E) { \
262 return Emit ## OP(EmitBinOps(E)); \
263 } \
264 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
265 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000266 }
267 HANDLEBINOP(Mul);
268 HANDLEBINOP(Div);
269 HANDLEBINOP(Rem);
270 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000271 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000272 HANDLEBINOP(Shl);
273 HANDLEBINOP(Shr);
274 HANDLEBINOP(And);
275 HANDLEBINOP(Xor);
276 HANDLEBINOP(Or);
277#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000278
Chris Lattner9fba49a2007-08-24 05:35:26 +0000279 // Comparisons.
280 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
281 unsigned SICmpOpc, unsigned FCmpOpc);
282#define VISITCOMP(CODE, UI, SI, FP) \
283 Value *VisitBin##CODE(const BinaryOperator *E) { \
284 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
285 llvm::FCmpInst::FP); }
286 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
287 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
288 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
289 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
290 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
291 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
292#undef VISITCOMP
293
294 Value *VisitBinAssign (const BinaryOperator *E);
295
296 Value *VisitBinLAnd (const BinaryOperator *E);
297 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000298 Value *VisitBinComma (const BinaryOperator *E);
299
300 // Other Operators.
301 Value *VisitConditionalOperator(const ConditionalOperator *CO);
302 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000303 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000304 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000305 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
306 return CGF.EmitObjCStringLiteral(E);
307 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000308 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000309};
310} // end anonymous namespace.
311
312//===----------------------------------------------------------------------===//
313// Utilities
314//===----------------------------------------------------------------------===//
315
Chris Lattnerd8d44222007-08-26 16:42:57 +0000316/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000317/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000318Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
319 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
320
321 if (SrcType->isRealFloatingType()) {
322 // Compare against 0.0 for fp scalars.
323 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000324 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
325 }
326
327 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
328 "Unknown scalar type to convert");
329
330 // Because of the type rules of C, we often end up computing a logical value,
331 // then zero extending it to int, then wanting it as a logical value again.
332 // Optimize this common case.
333 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
334 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
335 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000336 // If there aren't any more uses, zap the instruction to save space.
337 // Note that there can be more uses, for example if this
338 // is the result of an assignment.
339 if (ZI->use_empty())
340 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000341 return Result;
342 }
343 }
344
345 // Compare against an integer or pointer null.
346 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
347 return Builder.CreateICmpNE(Src, Zero, "tobool");
348}
349
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000350/// EmitScalarConversion - Emit a conversion from the specified type to the
351/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000352Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
353 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000354 SrcType = CGF.getContext().getCanonicalType(SrcType);
355 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000356 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000357
358 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000359
360 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000361 if (DstType->isBooleanType())
362 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000363
364 const llvm::Type *DstTy = ConvertType(DstType);
365
366 // Ignore conversions like int -> uint.
367 if (Src->getType() == DstTy)
368 return Src;
369
370 // Handle pointer conversions next: pointers can only be converted to/from
371 // other pointers and integers.
372 if (isa<PointerType>(DstType)) {
373 // The source value may be an integer, or a pointer.
374 if (isa<llvm::PointerType>(Src->getType()))
375 return Builder.CreateBitCast(Src, DstTy, "conv");
376 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
377 return Builder.CreateIntToPtr(Src, DstTy, "conv");
378 }
379
380 if (isa<PointerType>(SrcType)) {
381 // Must be an ptr to int cast.
382 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000383 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000384 }
385
Nate Begemanaf6ed502008-04-18 23:10:10 +0000386 // A scalar can be splatted to an extended vector of the same element type
387 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner4f025a42008-02-02 04:51:41 +0000388 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000389 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
390 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000391
Chris Lattner4f025a42008-02-02 04:51:41 +0000392 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000393 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000394 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000395 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000396
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000397 // Finally, we have the arithmetic types: real int/float.
398 if (isa<llvm::IntegerType>(Src->getType())) {
399 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000400 if (isa<llvm::IntegerType>(DstTy))
401 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
402 else if (InputSigned)
403 return Builder.CreateSIToFP(Src, DstTy, "conv");
404 else
405 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000406 }
407
408 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
409 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000410 if (DstType->isSignedIntegerType())
411 return Builder.CreateFPToSI(Src, DstTy, "conv");
412 else
413 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000414 }
415
416 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000417 if (DstTy->getTypeID() < Src->getType()->getTypeID())
418 return Builder.CreateFPTrunc(Src, DstTy, "conv");
419 else
420 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000421}
422
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000423/// EmitComplexToScalarConversion - Emit a conversion from the specified
424/// complex type to the specified destination type, where the destination
425/// type is an LLVM scalar type.
426Value *ScalarExprEmitter::
427EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
428 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000429 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000430 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000431
432 // Handle conversions to bool first, they are special: comparisons against 0.
433 if (DstTy->isBooleanType()) {
434 // Complex != 0 -> (Real != 0) | (Imag != 0)
435 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
436 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
437 return Builder.CreateOr(Src.first, Src.second, "tobool");
438 }
439
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000440 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
441 // the imaginary part of the complex value is discarded and the value of the
442 // real part is converted according to the conversion rules for the
443 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000444 return EmitScalarConversion(Src.first, SrcTy, DstTy);
445}
446
447
Chris Lattner9fba49a2007-08-24 05:35:26 +0000448//===----------------------------------------------------------------------===//
449// Visitor Methods
450//===----------------------------------------------------------------------===//
451
452Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000453 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000454 if (E->getType()->isVoidType())
455 return 0;
456 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
457}
458
Eli Friedmand0e9d092008-05-14 19:38:39 +0000459Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
460 llvm::SmallVector<llvm::Constant*, 32> indices;
461 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
462 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
463 }
464 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
465 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
466 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
467 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
468}
469
Chris Lattnercbfb5512008-03-01 08:45:05 +0000470Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
471 // Only the lookup mechanism and first two arguments of the method
472 // implementation vary between runtimes. We can get the receiver and
473 // arguments in generic code.
474
475 // Find the receiver
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000476 llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000477
478 // Process the arguments
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000479 unsigned ArgC = E->getNumArgs();
Chris Lattnercbfb5512008-03-01 08:45:05 +0000480 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000481 for (unsigned i = 0; i != ArgC; ++i) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000482 Expr *ArgExpr = E->getArg(i);
483 QualType ArgTy = ArgExpr->getType();
484 if (!CGF.hasAggregateLLVMType(ArgTy)) {
485 // Scalar argument is passed by-value.
486 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
Chris Lattnerde0908b2008-04-04 16:54:41 +0000487 } else if (ArgTy->isAnyComplexType()) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000488 // Make a temporary alloca to pass the argument.
489 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
490 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
491 Args.push_back(DestMem);
492 } else {
493 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
494 CGF.EmitAggExpr(ArgExpr, DestMem, false);
495 Args.push_back(DestMem);
496 }
497 }
498
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000499 return Runtime->GenerateMessageSend(Builder, ConvertType(E->getType()),
Chris Lattner6e6a5972008-04-04 04:07:35 +0000500 CGF.LoadObjCSelf(),
Chris Lattner8384c142008-06-26 04:42:20 +0000501 Receiver, E->getSelector(),
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000502 &Args[0], Args.size());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000503}
504
Daniel Dunbara5a0cdb2008-08-12 03:55:34 +0000505Value *ScalarExprEmitter::VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
506 return Runtime->GetSelector(Builder, E->getSelector());
507}
508
Chris Lattner9fba49a2007-08-24 05:35:26 +0000509Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
510 // Emit subscript expressions in rvalue context's. For most cases, this just
511 // loads the lvalue formed by the subscript expr. However, we have to be
512 // careful, because the base of a vector subscript is occasionally an rvalue,
513 // so we can't get it as an lvalue.
514 if (!E->getBase()->getType()->isVectorType())
515 return EmitLoadOfLValue(E);
516
517 // Handle the vector case. The base must be a vector, the index must be an
518 // integer value.
519 Value *Base = Visit(E->getBase());
520 Value *Idx = Visit(E->getIdx());
521
522 // FIXME: Convert Idx to i32 type.
523 return Builder.CreateExtractElement(Base, Idx, "vecext");
524}
525
526/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
527/// also handle things like function to pointer-to-function decay, and array to
528/// pointer decay.
529Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
530 const Expr *Op = E->getSubExpr();
531
532 // If this is due to array->pointer conversion, emit the array expression as
533 // an l-value.
534 if (Op->getType()->isArrayType()) {
535 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
536 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000537 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000538
539 assert(isa<llvm::PointerType>(V->getType()) &&
540 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
541 ->getElementType()) &&
542 "Doesn't support VLAs yet!");
Chris Lattner07307562008-03-19 05:19:41 +0000543 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000544
545 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000546 // types as well (e.g. void*) and can be implicitly converted to integer.
547 const llvm::Type *DestTy = ConvertType(E->getType());
548 if (V->getType() != DestTy) {
549 if (isa<llvm::PointerType>(DestTy))
550 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
551 else {
552 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
553 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
554 }
555 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000556 return V;
557
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000558 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000559 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000560 }
561
562 return EmitCastExpr(Op, E->getType());
563}
564
565
566// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
567// have to handle a more broad range of conversions than explicit casts, as they
568// handle things like function to ptr-to-function decay etc.
569Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000570 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000571
572 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000573 Value *Src = Visit(const_cast<Expr*>(E));
574
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000575 // Use EmitScalarConversion to perform the conversion.
576 return EmitScalarConversion(Src, E->getType(), DestTy);
577 }
Chris Lattner77288792008-02-16 23:55:16 +0000578
Chris Lattnerde0908b2008-04-04 16:54:41 +0000579 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000580 // Handle cases where the source is a complex type.
581 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
582 DestTy);
583 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000584
Chris Lattner77288792008-02-16 23:55:16 +0000585 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
586 // evaluate the result and return.
587 CGF.EmitAggExpr(E, 0, false);
588 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000589}
590
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000591Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000592 return CGF.EmitCompoundStmt(*E->getSubStmt(),
593 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000594}
595
596
Chris Lattner9fba49a2007-08-24 05:35:26 +0000597//===----------------------------------------------------------------------===//
598// Unary Operators
599//===----------------------------------------------------------------------===//
600
601Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000602 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000603 LValue LV = EmitLValue(E->getSubExpr());
604 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000605 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000606 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000607
608 int AmountVal = isInc ? 1 : -1;
609
610 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000611 if (isa<llvm::PointerType>(InVal->getType())) {
612 // FIXME: This isn't right for VLAs.
613 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000614 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000615 } else {
616 // Add the inc/dec to the real part.
617 if (isa<llvm::IntegerType>(InVal->getType()))
618 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000619 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000620 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000621 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000622 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000623 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000624 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000625 else {
626 llvm::APFloat F(static_cast<float>(AmountVal));
Chris Lattner2a674dc2008-06-30 18:32:54 +0000627 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000628 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000629 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000630 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
631 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000632
633 // Store the updated result through the lvalue.
634 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
635 E->getSubExpr()->getType());
636
637 // If this is a postinc, return the value read from memory, otherwise use the
638 // updated value.
639 return isPre ? NextVal : InVal;
640}
641
642
643Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
644 Value *Op = Visit(E->getSubExpr());
645 return Builder.CreateNeg(Op, "neg");
646}
647
648Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
649 Value *Op = Visit(E->getSubExpr());
650 return Builder.CreateNot(Op, "neg");
651}
652
653Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
654 // Compare operand to zero.
655 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
656
657 // Invert value.
658 // TODO: Could dynamically modify easy computations here. For example, if
659 // the operand is an icmp ne, turn into icmp eq.
660 BoolVal = Builder.CreateNot(BoolVal, "lnot");
661
662 // ZExt result to int.
663 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
664}
665
666/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
667/// an integer (RetType).
668Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000669 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000670 assert(RetType->isIntegerType() && "Result type must be an integer!");
671 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000672 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000673
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000674 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
675 // for function types.
Daniel Dunbar1c73aa22008-07-22 19:44:18 +0000676 // FIXME: what is alignof a function type in gcc?
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000677 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattner20515462008-02-21 05:45:29 +0000678 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
679
Chris Lattner9fba49a2007-08-24 05:35:26 +0000680 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000681 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000682
683 uint64_t Val = isSizeOf ? Info.first : Info.second;
684 Val /= 8; // Return size in bytes, not bits.
685
Chris Lattner9fba49a2007-08-24 05:35:26 +0000686 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
687}
688
Chris Lattner01211af2007-08-24 21:20:17 +0000689Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
690 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000691 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000692 return CGF.EmitComplexExpr(Op).first;
693 return Visit(Op);
694}
695Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
696 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000697 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000698 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000699
700 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
701 // effects are evaluated.
702 CGF.EmitScalarExpr(Op);
703 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000704}
705
Anders Carlsson52774ad2008-01-29 15:56:48 +0000706Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
707{
708 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
709
710 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
711
Chris Lattner8cd0e932008-03-05 18:54:05 +0000712 uint32_t ResultWidth =
713 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000714 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
715}
Chris Lattner01211af2007-08-24 21:20:17 +0000716
Chris Lattner9fba49a2007-08-24 05:35:26 +0000717//===----------------------------------------------------------------------===//
718// Binary Operators
719//===----------------------------------------------------------------------===//
720
721BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
722 BinOpInfo Result;
723 Result.LHS = Visit(E->getLHS());
724 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000725 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000726 Result.E = E;
727 return Result;
728}
729
Chris Lattner0d965302007-08-26 21:41:21 +0000730Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000731 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
732 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
733
734 BinOpInfo OpInfo;
735
736 // Load the LHS and RHS operands.
737 LValue LHSLV = EmitLValue(E->getLHS());
738 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000739
740 // Determine the computation type. If the RHS is complex, then this is one of
741 // the add/sub/mul/div operators. All of these operators can be computed in
742 // with just their real component even though the computation domain really is
743 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000744 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000745
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000746 // If the computation type is complex, then the RHS is complex. Emit the RHS.
747 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
748 ComputeType = CT->getElementType();
749
750 // Emit the RHS, only keeping the real component.
751 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
752 RHSTy = RHSTy->getAsComplexType()->getElementType();
753 } else {
754 // Otherwise the RHS is a simple scalar value.
755 OpInfo.RHS = Visit(E->getRHS());
756 }
757
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000758 QualType LComputeTy, RComputeTy, ResultTy;
759
760 // Compound assignment does not contain enough information about all
761 // the types involved for pointer arithmetic cases. Figure it out
762 // here for now.
763 if (E->getLHS()->getType()->isPointerType()) {
764 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
765 assert((E->getOpcode() == BinaryOperator::AddAssign ||
766 E->getOpcode() == BinaryOperator::SubAssign) &&
767 "Invalid compound assignment operator on pointer type.");
768 LComputeTy = E->getLHS()->getType();
769
770 if (E->getRHS()->getType()->isPointerType()) {
771 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
772 // extension, the conversion from the pointer difference back to
773 // the LHS type is handled at the end.
774 assert(E->getOpcode() == BinaryOperator::SubAssign &&
775 "Invalid compound assignment operator on pointer type.");
776 RComputeTy = E->getLHS()->getType();
777 ResultTy = CGF.getContext().getPointerDiffType();
778 } else {
779 RComputeTy = E->getRHS()->getType();
780 ResultTy = LComputeTy;
781 }
782 } else if (E->getRHS()->getType()->isPointerType()) {
783 // Degenerate case of (int += ptr) allowed by GCC implicit cast
784 // extension.
785 assert(E->getOpcode() == BinaryOperator::AddAssign &&
786 "Invalid compound assignment operator on pointer type.");
787 LComputeTy = E->getLHS()->getType();
788 RComputeTy = E->getRHS()->getType();
789 ResultTy = RComputeTy;
790 } else {
791 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000792 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000793
794 // Convert the LHS/RHS values to the computation type.
795 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
796 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
797 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000798 OpInfo.E = E;
799
800 // Expand the binary operator.
801 Value *Result = (this->*Func)(OpInfo);
802
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000803 // Convert the result back to the LHS type.
804 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000805
806 // Store the result value into the LHS lvalue.
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000807 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000808
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000809 // For bitfields, we need the value in the bitfield
810 // FIXME: This adds an extra bitfield load
811 if (LHSLV.isBitfield())
812 Result = EmitLoadOfLValue(LHSLV, LHSTy);
813
Chris Lattner660e31d2007-08-24 21:00:35 +0000814 return Result;
815}
816
817
Chris Lattner9fba49a2007-08-24 05:35:26 +0000818Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000819 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000820 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000821 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000822 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
823 else
824 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
825}
826
827Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
828 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000829 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000830 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
831 else
832 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
833}
834
835
836Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000837 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000838 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000839
840 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000841 Value *Ptr, *Idx;
842 Expr *IdxExp;
843 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
844 Ptr = Ops.LHS;
845 Idx = Ops.RHS;
846 IdxExp = Ops.E->getRHS();
847 } else { // int + pointer
848 Ptr = Ops.RHS;
849 Idx = Ops.LHS;
850 IdxExp = Ops.E->getLHS();
851 }
852
853 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
854 if (Width < CGF.LLVMPointerWidth) {
855 // Zero or sign extend the pointer value based on whether the index is
856 // signed or not.
857 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000858 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000859 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
860 else
861 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
862 }
863
864 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000865}
866
867Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
868 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
869 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000870
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000871 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
872 // pointer - int
873 Value *Idx = Ops.RHS;
874 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
875 if (Width < CGF.LLVMPointerWidth) {
876 // Zero or sign extend the pointer value based on whether the index is
877 // signed or not.
878 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
879 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
880 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
881 else
882 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
883 }
884 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
885
886 // FIXME: The pointer could point to a VLA.
887 // The GNU void* - int case is automatically handled here because
888 // our LLVM type for void* is i8*.
889 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000890 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000891 // pointer - pointer
892 Value *LHS = Ops.LHS;
893 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000894
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000895 const QualType LHSType = Ops.E->getLHS()->getType();
896 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
897 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000898
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000899 // Handle GCC extension for pointer arithmetic on void* types.
900 if (LHSElementType->isVoidType()) {
901 ElementSize = 1;
902 } else {
903 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
904 }
905
906 const llvm::Type *ResultType = ConvertType(Ops.Ty);
907 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
908 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
909 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
910
911 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
912 // remainder. As such, we handle common power-of-two cases here to generate
913 // better code. See PR2247.
914 if (llvm::isPowerOf2_64(ElementSize)) {
915 Value *ShAmt =
916 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
917 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
918 }
919
920 // Otherwise, do a full sdiv.
921 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
922 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000923 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000924}
925
926Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
927 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
928 // RHS to the same size as the LHS.
929 Value *RHS = Ops.RHS;
930 if (Ops.LHS->getType() != RHS->getType())
931 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
932
933 return Builder.CreateShl(Ops.LHS, RHS, "shl");
934}
935
936Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
937 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
938 // RHS to the same size as the LHS.
939 Value *RHS = Ops.RHS;
940 if (Ops.LHS->getType() != RHS->getType())
941 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
942
Chris Lattner660e31d2007-08-24 21:00:35 +0000943 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000944 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
945 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
946}
947
948Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
949 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000950 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000951 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +0000952 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000953 Value *LHS = Visit(E->getLHS());
954 Value *RHS = Visit(E->getRHS());
955
956 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +0000957 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000958 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000959 } else if (LHSTy->isSignedIntegerType()) {
960 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000961 LHS, RHS, "cmp");
962 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000963 // Unsigned integers and pointers.
964 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000965 LHS, RHS, "cmp");
966 }
Nate Begeman1591bc52008-07-25 20:16:05 +0000967 } else if (LHSTy->isVectorType()) {
968 Value *LHS = Visit(E->getLHS());
969 Value *RHS = Visit(E->getRHS());
970
971 if (LHS->getType()->isFPOrFPVector()) {
972 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
973 LHS, RHS, "cmp");
974 } else if (LHSTy->isUnsignedIntegerType()) {
975 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
976 LHS, RHS, "cmp");
977 } else {
978 // Signed integers and pointers.
979 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
980 LHS, RHS, "cmp");
981 }
982 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000983 } else {
984 // Complex Comparison: can only be an equality comparison.
985 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
986 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
987
Chris Lattnerc154ac12008-07-26 22:37:01 +0000988 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000989
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000990 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000991 if (CETy->isRealFloatingType()) {
992 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
993 LHS.first, RHS.first, "cmp.r");
994 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
995 LHS.second, RHS.second, "cmp.i");
996 } else {
997 // Complex comparisons can only be equality comparisons. As such, signed
998 // and unsigned opcodes are the same.
999 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1000 LHS.first, RHS.first, "cmp.r");
1001 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1002 LHS.second, RHS.second, "cmp.i");
1003 }
1004
1005 if (E->getOpcode() == BinaryOperator::EQ) {
1006 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1007 } else {
1008 assert(E->getOpcode() == BinaryOperator::NE &&
1009 "Complex comparison other than == or != ?");
1010 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1011 }
1012 }
1013
1014 // ZExt result to int.
1015 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1016}
1017
1018Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1019 LValue LHS = EmitLValue(E->getLHS());
1020 Value *RHS = Visit(E->getRHS());
1021
1022 // Store the value into the LHS.
1023 // FIXME: Volatility!
1024 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001025
1026 // For bitfields, we need the value in the bitfield
1027 // FIXME: This adds an extra bitfield load
1028 if (LHS.isBitfield())
1029 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001030 // Return the RHS.
1031 return RHS;
1032}
1033
1034Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1035 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1036
Gabor Greif815e2c12008-04-06 20:42:52 +00001037 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1038 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001039
1040 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1041 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1042
1043 CGF.EmitBlock(RHSBlock);
1044 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1045
1046 // Reaquire the RHS block, as there may be subblocks inserted.
1047 RHSBlock = Builder.GetInsertBlock();
1048 CGF.EmitBlock(ContBlock);
1049
1050 // Create a PHI node. If we just evaluted the LHS condition, the result is
1051 // false. If we evaluated both, the result is the RHS condition.
1052 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1053 PN->reserveOperandSpace(2);
1054 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1055 PN->addIncoming(RHSCond, RHSBlock);
1056
1057 // ZExt result to int.
1058 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1059}
1060
1061Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1062 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1063
Gabor Greif815e2c12008-04-06 20:42:52 +00001064 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1065 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001066
1067 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1068 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1069
1070 CGF.EmitBlock(RHSBlock);
1071 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1072
1073 // Reaquire the RHS block, as there may be subblocks inserted.
1074 RHSBlock = Builder.GetInsertBlock();
1075 CGF.EmitBlock(ContBlock);
1076
1077 // Create a PHI node. If we just evaluted the LHS condition, the result is
1078 // true. If we evaluated both, the result is the RHS condition.
1079 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1080 PN->reserveOperandSpace(2);
1081 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1082 PN->addIncoming(RHSCond, RHSBlock);
1083
1084 // ZExt result to int.
1085 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1086}
1087
1088Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1089 CGF.EmitStmt(E->getLHS());
1090 return Visit(E->getRHS());
1091}
1092
1093//===----------------------------------------------------------------------===//
1094// Other Operators
1095//===----------------------------------------------------------------------===//
1096
1097Value *ScalarExprEmitter::
1098VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001099 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1100 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1101 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001102
Chris Lattner98a425c2007-11-26 01:40:58 +00001103 // Evaluate the conditional, then convert it to bool. We do this explicitly
1104 // because we need the unconverted value if this is a GNU ?: expression with
1105 // missing middle value.
1106 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001107 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1108 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001109 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001110
1111 CGF.EmitBlock(LHSBlock);
1112
1113 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001114 Value *LHS;
1115 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001116 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001117 else // Perform promotions, to handle cases like "short ?: int"
1118 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1119
Chris Lattner9fba49a2007-08-24 05:35:26 +00001120 Builder.CreateBr(ContBlock);
1121 LHSBlock = Builder.GetInsertBlock();
1122
1123 CGF.EmitBlock(RHSBlock);
1124
Eli Friedmance8d7032008-05-16 20:38:39 +00001125 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001126 Builder.CreateBr(ContBlock);
1127 RHSBlock = Builder.GetInsertBlock();
1128
1129 CGF.EmitBlock(ContBlock);
1130
Nuno Lopesb62ff242008-06-04 19:15:45 +00001131 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001132 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1133 return 0;
1134 }
1135
Chris Lattner9fba49a2007-08-24 05:35:26 +00001136 // Create a PHI node for the real part.
1137 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1138 PN->reserveOperandSpace(2);
1139 PN->addIncoming(LHS, LHSBlock);
1140 PN->addIncoming(RHS, RHSBlock);
1141 return PN;
1142}
1143
1144Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001145 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001146 return
1147 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001148}
1149
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001150Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001151 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001152 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001153}
1154
Chris Lattner307da022007-11-30 17:56:23 +00001155Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001156 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1157
1158 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1159 return V;
1160}
1161
Chris Lattner307da022007-11-30 17:56:23 +00001162Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001163 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001164 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1165 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1166 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001167
1168 llvm::Constant *C = llvm::ConstantArray::get(str);
1169 C = new llvm::GlobalVariable(C->getType(), true,
1170 llvm::GlobalValue::InternalLinkage,
1171 C, ".str", &CGF.CGM.getModule());
1172 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1173 llvm::Constant *Zeros[] = { Zero, Zero };
1174 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1175
1176 return C;
1177}
1178
Chris Lattner9fba49a2007-08-24 05:35:26 +00001179//===----------------------------------------------------------------------===//
1180// Entry Point into this File
1181//===----------------------------------------------------------------------===//
1182
1183/// EmitComplexExpr - Emit the computation of the specified expression of
1184/// complex type, ignoring the result.
1185Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1186 assert(E && !hasAggregateLLVMType(E->getType()) &&
1187 "Invalid scalar expression to emit");
1188
1189 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1190}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001191
1192/// EmitScalarConversion - Emit a conversion from the specified type to the
1193/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001194Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1195 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001196 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1197 "Invalid scalar expression to emit");
1198 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1199}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001200
1201/// EmitComplexToScalarConversion - Emit a conversion from the specified
1202/// complex type to the specified destination type, where the destination
1203/// type is an LLVM scalar type.
1204Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1205 QualType SrcTy,
1206 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001207 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001208 "Invalid complex -> scalar conversion");
1209 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1210 DstTy);
1211}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001212
1213Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1214 assert(V1->getType() == V2->getType() &&
1215 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001216 unsigned NumElements =
1217 cast<llvm::VectorType>(V1->getType())->getNumElements();
1218
1219 va_list va;
1220 va_start(va, V2);
1221
1222 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001223 for (unsigned i = 0; i < NumElements; i++) {
1224 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001225 assert(n >= 0 && n < (int)NumElements * 2 &&
1226 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001227 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1228 }
1229
1230 const char *Name = va_arg(va, const char *);
1231 va_end(va);
1232
1233 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1234
1235 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1236}
1237
Anders Carlsson68b8be92007-12-15 21:23:30 +00001238llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001239 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001240 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001241 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001242
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001243 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001244 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001245 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001246 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001247 }
1248
1249 return Vec;
1250}