blob: 1f5324d71d74ea2bf94f04b39751e9027a84e92a [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner9fba49a2007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000018#include "llvm/Constants.h"
19#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000020#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000021#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000022#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000023#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000024
Chris Lattner9fba49a2007-08-24 05:35:26 +000025using namespace clang;
26using namespace CodeGen;
27using llvm::Value;
28
29//===----------------------------------------------------------------------===//
30// Scalar Expression Emitter
31//===----------------------------------------------------------------------===//
32
33struct BinOpInfo {
34 Value *LHS;
35 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000036 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000037 const BinaryOperator *E;
38};
39
40namespace {
41class VISIBILITY_HIDDEN ScalarExprEmitter
42 : public StmtVisitor<ScalarExprEmitter, Value*> {
43 CodeGenFunction &CGF;
Chris Lattner676bf212008-04-13 07:32:11 +000044 llvm::IRBuilder &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000045 CGObjCRuntime *Runtime;
46
Chris Lattner9fba49a2007-08-24 05:35:26 +000047public:
48
Chris Lattnercbfb5512008-03-01 08:45:05 +000049 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
50 Builder(CGF.Builder),
51 Runtime(CGF.CGM.getObjCRuntime()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000052 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000053
54 //===--------------------------------------------------------------------===//
55 // Utilities
56 //===--------------------------------------------------------------------===//
57
58 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
59 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
60
61 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000062 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000063 }
64
65 /// EmitLoadOfLValue - Given an expression with complex type that represents a
66 /// value l-value, this method emits the address of the l-value, then loads
67 /// and returns the result.
68 Value *EmitLoadOfLValue(const Expr *E) {
69 // FIXME: Volatile
70 return EmitLoadOfLValue(EmitLValue(E), E->getType());
71 }
72
Chris Lattnerd8d44222007-08-26 16:42:57 +000073 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000074 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000075 Value *EmitConversionToBool(Value *Src, QualType DstTy);
76
Chris Lattner4e05d1e2007-08-26 06:48:56 +000077 /// EmitScalarConversion - Emit a conversion from the specified type to the
78 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000079 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
80
81 /// EmitComplexToScalarConversion - Emit a conversion from the specified
82 /// complex type to the specified destination type, where the destination
83 /// type is an LLVM scalar type.
84 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
85 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000086
Chris Lattner9fba49a2007-08-24 05:35:26 +000087 //===--------------------------------------------------------------------===//
88 // Visitor Methods
89 //===--------------------------------------------------------------------===//
90
91 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000092 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000093 assert(0 && "Stmt can't have complex result type!");
94 return 0;
95 }
96 Value *VisitExpr(Expr *S);
97 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
98
99 // Leaves.
100 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
101 return llvm::ConstantInt::get(E->getValue());
102 }
103 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000104 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000105 }
106 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
107 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
108 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000109 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000112 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000114 CGF.getContext().typesAreCompatible(
115 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000116 }
117 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
118 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
119 }
Daniel Dunbar879788d2008-08-04 16:51:22 +0000120 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
121 Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
122 CGF.GetIDForAddrOfLabel(E->getLabel()));
123 return Builder.CreateIntToPtr(V,
124 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
125 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000126
127 // l-values.
128 Value *VisitDeclRefExpr(DeclRefExpr *E) {
129 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
130 return llvm::ConstantInt::get(EC->getInitVal());
131 return EmitLoadOfLValue(E);
132 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000133 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000134 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000135 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000136 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000137 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000138 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000139 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000140 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
141 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000142
143 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000144 unsigned NumInitElements = E->getNumInits();
145
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000146 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000147 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
148
149 // We have a scalar in braces. Just use the first element.
150 if (!VType)
151 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000152
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000153 unsigned NumVectorElements = VType->getNumElements();
154 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000155
156 // Emit individual vector element stores.
157 llvm::Value *V = llvm::UndefValue::get(VType);
158
Anders Carlsson323d5682007-12-18 02:45:33 +0000159 // Emit initializers
160 unsigned i;
161 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000162 Value *NewV = Visit(E->getInit(i));
163 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
164 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000165 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000166
167 // Emit remaining default initializers
168 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
169 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
170 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
171 V = Builder.CreateInsertElement(V, NewV, Idx);
172 }
173
Devang Patel32c39832007-10-24 18:05:48 +0000174 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000175 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000176
Chris Lattner9fba49a2007-08-24 05:35:26 +0000177 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
178 Value *VisitCastExpr(const CastExpr *E) {
179 return EmitCastExpr(E->getSubExpr(), E->getType());
180 }
181 Value *EmitCastExpr(const Expr *E, QualType T);
182
183 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000184 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000185 }
186
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000187 Value *VisitStmtExpr(const StmtExpr *E);
188
Chris Lattner9fba49a2007-08-24 05:35:26 +0000189 // Unary Operators.
190 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
191 Value *VisitUnaryPostDec(const UnaryOperator *E) {
192 return VisitPrePostIncDec(E, false, false);
193 }
194 Value *VisitUnaryPostInc(const UnaryOperator *E) {
195 return VisitPrePostIncDec(E, true, false);
196 }
197 Value *VisitUnaryPreDec(const UnaryOperator *E) {
198 return VisitPrePostIncDec(E, false, true);
199 }
200 Value *VisitUnaryPreInc(const UnaryOperator *E) {
201 return VisitPrePostIncDec(E, true, true);
202 }
203 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
204 return EmitLValue(E->getSubExpr()).getAddress();
205 }
206 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
207 Value *VisitUnaryPlus(const UnaryOperator *E) {
208 return Visit(E->getSubExpr());
209 }
210 Value *VisitUnaryMinus (const UnaryOperator *E);
211 Value *VisitUnaryNot (const UnaryOperator *E);
212 Value *VisitUnaryLNot (const UnaryOperator *E);
213 Value *VisitUnarySizeOf (const UnaryOperator *E) {
214 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
215 }
216 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
217 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
218 }
219 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000220 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000221 Value *VisitUnaryReal (const UnaryOperator *E);
222 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000223 Value *VisitUnaryExtension(const UnaryOperator *E) {
224 return Visit(E->getSubExpr());
225 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000226 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000227 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
228 return Visit(DAE->getExpr());
229 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000230
Chris Lattner9fba49a2007-08-24 05:35:26 +0000231 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000232 Value *EmitMul(const BinOpInfo &Ops) {
233 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
234 }
235 Value *EmitDiv(const BinOpInfo &Ops);
236 Value *EmitRem(const BinOpInfo &Ops);
237 Value *EmitAdd(const BinOpInfo &Ops);
238 Value *EmitSub(const BinOpInfo &Ops);
239 Value *EmitShl(const BinOpInfo &Ops);
240 Value *EmitShr(const BinOpInfo &Ops);
241 Value *EmitAnd(const BinOpInfo &Ops) {
242 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
243 }
244 Value *EmitXor(const BinOpInfo &Ops) {
245 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
246 }
247 Value *EmitOr (const BinOpInfo &Ops) {
248 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
249 }
250
Chris Lattner660e31d2007-08-24 21:00:35 +0000251 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000252 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000253 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
254
255 // Binary operators and binary compound assignment operators.
256#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000257 Value *VisitBin ## OP(const BinaryOperator *E) { \
258 return Emit ## OP(EmitBinOps(E)); \
259 } \
260 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
261 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000262 }
263 HANDLEBINOP(Mul);
264 HANDLEBINOP(Div);
265 HANDLEBINOP(Rem);
266 HANDLEBINOP(Add);
267 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
268 HANDLEBINOP(Shl);
269 HANDLEBINOP(Shr);
270 HANDLEBINOP(And);
271 HANDLEBINOP(Xor);
272 HANDLEBINOP(Or);
273#undef HANDLEBINOP
274 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000275 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000276 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
277 }
278
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
Chris Lattner9fba49a2007-08-24 05:35:26 +0000505Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
506 // Emit subscript expressions in rvalue context's. For most cases, this just
507 // loads the lvalue formed by the subscript expr. However, we have to be
508 // careful, because the base of a vector subscript is occasionally an rvalue,
509 // so we can't get it as an lvalue.
510 if (!E->getBase()->getType()->isVectorType())
511 return EmitLoadOfLValue(E);
512
513 // Handle the vector case. The base must be a vector, the index must be an
514 // integer value.
515 Value *Base = Visit(E->getBase());
516 Value *Idx = Visit(E->getIdx());
517
518 // FIXME: Convert Idx to i32 type.
519 return Builder.CreateExtractElement(Base, Idx, "vecext");
520}
521
522/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
523/// also handle things like function to pointer-to-function decay, and array to
524/// pointer decay.
525Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
526 const Expr *Op = E->getSubExpr();
527
528 // If this is due to array->pointer conversion, emit the array expression as
529 // an l-value.
530 if (Op->getType()->isArrayType()) {
531 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
532 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000533 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000534
535 assert(isa<llvm::PointerType>(V->getType()) &&
536 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
537 ->getElementType()) &&
538 "Doesn't support VLAs yet!");
Chris Lattner07307562008-03-19 05:19:41 +0000539 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000540
541 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000542 // types as well (e.g. void*) and can be implicitly converted to integer.
543 const llvm::Type *DestTy = ConvertType(E->getType());
544 if (V->getType() != DestTy) {
545 if (isa<llvm::PointerType>(DestTy))
546 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
547 else {
548 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
549 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
550 }
551 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000552 return V;
553
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000554 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000555 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000556 }
557
558 return EmitCastExpr(Op, E->getType());
559}
560
561
562// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
563// have to handle a more broad range of conversions than explicit casts, as they
564// handle things like function to ptr-to-function decay etc.
565Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000566 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000567
568 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000569 Value *Src = Visit(const_cast<Expr*>(E));
570
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000571 // Use EmitScalarConversion to perform the conversion.
572 return EmitScalarConversion(Src, E->getType(), DestTy);
573 }
Chris Lattner77288792008-02-16 23:55:16 +0000574
Chris Lattnerde0908b2008-04-04 16:54:41 +0000575 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000576 // Handle cases where the source is a complex type.
577 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
578 DestTy);
579 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000580
Chris Lattner77288792008-02-16 23:55:16 +0000581 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
582 // evaluate the result and return.
583 CGF.EmitAggExpr(E, 0, false);
584 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000585}
586
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000587Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000588 return CGF.EmitCompoundStmt(*E->getSubStmt(),
589 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000590}
591
592
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593//===----------------------------------------------------------------------===//
594// Unary Operators
595//===----------------------------------------------------------------------===//
596
597Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000598 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000599 LValue LV = EmitLValue(E->getSubExpr());
600 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000601 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000602 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000603
604 int AmountVal = isInc ? 1 : -1;
605
606 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000607 if (isa<llvm::PointerType>(InVal->getType())) {
608 // FIXME: This isn't right for VLAs.
609 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000610 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000611 } else {
612 // Add the inc/dec to the real part.
613 if (isa<llvm::IntegerType>(InVal->getType()))
614 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000615 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000616 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000617 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000618 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000619 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000620 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000621 else {
622 llvm::APFloat F(static_cast<float>(AmountVal));
Chris Lattner2a674dc2008-06-30 18:32:54 +0000623 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000624 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000625 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000626 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
627 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000628
629 // Store the updated result through the lvalue.
630 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
631 E->getSubExpr()->getType());
632
633 // If this is a postinc, return the value read from memory, otherwise use the
634 // updated value.
635 return isPre ? NextVal : InVal;
636}
637
638
639Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
640 Value *Op = Visit(E->getSubExpr());
641 return Builder.CreateNeg(Op, "neg");
642}
643
644Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
645 Value *Op = Visit(E->getSubExpr());
646 return Builder.CreateNot(Op, "neg");
647}
648
649Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
650 // Compare operand to zero.
651 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
652
653 // Invert value.
654 // TODO: Could dynamically modify easy computations here. For example, if
655 // the operand is an icmp ne, turn into icmp eq.
656 BoolVal = Builder.CreateNot(BoolVal, "lnot");
657
658 // ZExt result to int.
659 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
660}
661
662/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
663/// an integer (RetType).
664Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000665 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000666 assert(RetType->isIntegerType() && "Result type must be an integer!");
667 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000668 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000669
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000670 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
671 // for function types.
Daniel Dunbar1c73aa22008-07-22 19:44:18 +0000672 // FIXME: what is alignof a function type in gcc?
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000673 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattner20515462008-02-21 05:45:29 +0000674 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
675
Chris Lattner9fba49a2007-08-24 05:35:26 +0000676 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000677 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000678
679 uint64_t Val = isSizeOf ? Info.first : Info.second;
680 Val /= 8; // Return size in bytes, not bits.
681
Chris Lattner9fba49a2007-08-24 05:35:26 +0000682 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
683}
684
Chris Lattner01211af2007-08-24 21:20:17 +0000685Value *ScalarExprEmitter::VisitUnaryReal(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).first;
689 return Visit(Op);
690}
691Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
692 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000693 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000694 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000695
696 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
697 // effects are evaluated.
698 CGF.EmitScalarExpr(Op);
699 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000700}
701
Anders Carlsson52774ad2008-01-29 15:56:48 +0000702Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
703{
704 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
705
706 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
707
Chris Lattner8cd0e932008-03-05 18:54:05 +0000708 uint32_t ResultWidth =
709 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000710 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
711}
Chris Lattner01211af2007-08-24 21:20:17 +0000712
Chris Lattner9fba49a2007-08-24 05:35:26 +0000713//===----------------------------------------------------------------------===//
714// Binary Operators
715//===----------------------------------------------------------------------===//
716
717BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
718 BinOpInfo Result;
719 Result.LHS = Visit(E->getLHS());
720 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000721 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000722 Result.E = E;
723 return Result;
724}
725
Chris Lattner0d965302007-08-26 21:41:21 +0000726Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000727 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
728 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
729
730 BinOpInfo OpInfo;
731
732 // Load the LHS and RHS operands.
733 LValue LHSLV = EmitLValue(E->getLHS());
734 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000735
736 // Determine the computation type. If the RHS is complex, then this is one of
737 // the add/sub/mul/div operators. All of these operators can be computed in
738 // with just their real component even though the computation domain really is
739 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000740 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000741
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000742 // If the computation type is complex, then the RHS is complex. Emit the RHS.
743 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
744 ComputeType = CT->getElementType();
745
746 // Emit the RHS, only keeping the real component.
747 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
748 RHSTy = RHSTy->getAsComplexType()->getElementType();
749 } else {
750 // Otherwise the RHS is a simple scalar value.
751 OpInfo.RHS = Visit(E->getRHS());
752 }
753
754 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000755 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000756
Devang Patel04011802007-10-25 22:19:13 +0000757 // Do not merge types for -= or += where the LHS is a pointer.
758 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000759 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000760 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000761 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000762 }
763 OpInfo.Ty = ComputeType;
764 OpInfo.E = E;
765
766 // Expand the binary operator.
767 Value *Result = (this->*Func)(OpInfo);
768
769 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000770 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000771
772 // Store the result value into the LHS lvalue.
773 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
774
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000775 // For bitfields, we need the value in the bitfield
776 // FIXME: This adds an extra bitfield load
777 if (LHSLV.isBitfield())
778 Result = EmitLoadOfLValue(LHSLV, LHSTy);
779
Chris Lattner660e31d2007-08-24 21:00:35 +0000780 return Result;
781}
782
783
Chris Lattner9fba49a2007-08-24 05:35:26 +0000784Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000785 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000786 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000787 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000788 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
789 else
790 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
791}
792
793Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
794 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000795 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000796 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
797 else
798 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
799}
800
801
802Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000803 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000804 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000805
806 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000807 Value *Ptr, *Idx;
808 Expr *IdxExp;
809 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
810 Ptr = Ops.LHS;
811 Idx = Ops.RHS;
812 IdxExp = Ops.E->getRHS();
813 } else { // int + pointer
814 Ptr = Ops.RHS;
815 Idx = Ops.LHS;
816 IdxExp = Ops.E->getLHS();
817 }
818
819 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
820 if (Width < CGF.LLVMPointerWidth) {
821 // Zero or sign extend the pointer value based on whether the index is
822 // signed or not.
823 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000824 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000825 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
826 else
827 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
828 }
829
830 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000831}
832
833Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
834 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
835 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
836
Chris Lattner660e31d2007-08-24 21:00:35 +0000837 // pointer - int
838 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
839 "ptr-ptr shouldn't get here");
840 // FIXME: The pointer could point to a VLA.
Chris Lattnere78c1ea2008-01-31 04:12:50 +0000841 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
842
843 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
844 if (Width < CGF.LLVMPointerWidth) {
845 // Zero or sign extend the pointer value based on whether the index is
846 // signed or not.
847 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000848 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
Chris Lattnere78c1ea2008-01-31 04:12:50 +0000849 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
850 else
851 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
852 }
853
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000854 // The GNU void* - int case is automatically handled here because
855 // our LLVM type for void* is i8*.
Chris Lattnere78c1ea2008-01-31 04:12:50 +0000856 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner660e31d2007-08-24 21:00:35 +0000857}
858
859Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
860 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
861 // the compound assignment case it is invalid, so just handle it here.
862 if (!E->getRHS()->getType()->isPointerType())
863 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000864
865 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000866 Value *LHS = Visit(E->getLHS());
867 Value *RHS = Visit(E->getRHS());
868
Chris Lattnerc154ac12008-07-26 22:37:01 +0000869 const QualType LHSType = E->getLHS()->getType();
870 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000871 uint64_t ElementSize;
872
873 // Handle GCC extension for pointer arithmetic on void* types.
874 if (LHSElementType->isVoidType()) {
875 ElementSize = 1;
876 } else {
877 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
878 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000879
880 const llvm::Type *ResultType = ConvertType(E->getType());
881 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
882 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
883 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000884
Chris Lattner9fba49a2007-08-24 05:35:26 +0000885 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
886 // remainder. As such, we handle common power-of-two cases here to generate
887 // better code.
888 if (llvm::isPowerOf2_64(ElementSize)) {
889 Value *ShAmt =
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000890 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000891 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
892 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000893
Chris Lattner9fba49a2007-08-24 05:35:26 +0000894 // Otherwise, do a full sdiv.
895 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
896 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
897}
898
Chris Lattner660e31d2007-08-24 21:00:35 +0000899
Chris Lattner9fba49a2007-08-24 05:35:26 +0000900Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
901 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
902 // RHS to the same size as the LHS.
903 Value *RHS = Ops.RHS;
904 if (Ops.LHS->getType() != RHS->getType())
905 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
906
907 return Builder.CreateShl(Ops.LHS, RHS, "shl");
908}
909
910Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
911 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
912 // RHS to the same size as the LHS.
913 Value *RHS = Ops.RHS;
914 if (Ops.LHS->getType() != RHS->getType())
915 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
916
Chris Lattner660e31d2007-08-24 21:00:35 +0000917 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000918 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
919 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
920}
921
922Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
923 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000924 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000925 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +0000926 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000927 Value *LHS = Visit(E->getLHS());
928 Value *RHS = Visit(E->getRHS());
929
930 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +0000931 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000932 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000933 } else if (LHSTy->isSignedIntegerType()) {
934 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000935 LHS, RHS, "cmp");
936 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000937 // Unsigned integers and pointers.
938 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000939 LHS, RHS, "cmp");
940 }
Nate Begeman1591bc52008-07-25 20:16:05 +0000941 } else if (LHSTy->isVectorType()) {
942 Value *LHS = Visit(E->getLHS());
943 Value *RHS = Visit(E->getRHS());
944
945 if (LHS->getType()->isFPOrFPVector()) {
946 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
947 LHS, RHS, "cmp");
948 } else if (LHSTy->isUnsignedIntegerType()) {
949 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
950 LHS, RHS, "cmp");
951 } else {
952 // Signed integers and pointers.
953 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
954 LHS, RHS, "cmp");
955 }
956 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000957 } else {
958 // Complex Comparison: can only be an equality comparison.
959 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
960 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
961
Chris Lattnerc154ac12008-07-26 22:37:01 +0000962 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000963
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000964 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000965 if (CETy->isRealFloatingType()) {
966 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
967 LHS.first, RHS.first, "cmp.r");
968 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
969 LHS.second, RHS.second, "cmp.i");
970 } else {
971 // Complex comparisons can only be equality comparisons. As such, signed
972 // and unsigned opcodes are the same.
973 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
974 LHS.first, RHS.first, "cmp.r");
975 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
976 LHS.second, RHS.second, "cmp.i");
977 }
978
979 if (E->getOpcode() == BinaryOperator::EQ) {
980 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
981 } else {
982 assert(E->getOpcode() == BinaryOperator::NE &&
983 "Complex comparison other than == or != ?");
984 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
985 }
986 }
987
988 // ZExt result to int.
989 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
990}
991
992Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
993 LValue LHS = EmitLValue(E->getLHS());
994 Value *RHS = Visit(E->getRHS());
995
996 // Store the value into the LHS.
997 // FIXME: Volatility!
998 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000999
1000 // For bitfields, we need the value in the bitfield
1001 // FIXME: This adds an extra bitfield load
1002 if (LHS.isBitfield())
1003 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001004 // Return the RHS.
1005 return RHS;
1006}
1007
1008Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1009 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1010
Gabor Greif815e2c12008-04-06 20:42:52 +00001011 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1012 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001013
1014 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1015 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1016
1017 CGF.EmitBlock(RHSBlock);
1018 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1019
1020 // Reaquire the RHS block, as there may be subblocks inserted.
1021 RHSBlock = Builder.GetInsertBlock();
1022 CGF.EmitBlock(ContBlock);
1023
1024 // Create a PHI node. If we just evaluted the LHS condition, the result is
1025 // false. If we evaluated both, the result is the RHS condition.
1026 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1027 PN->reserveOperandSpace(2);
1028 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1029 PN->addIncoming(RHSCond, RHSBlock);
1030
1031 // ZExt result to int.
1032 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1033}
1034
1035Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1036 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1037
Gabor Greif815e2c12008-04-06 20:42:52 +00001038 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1039 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001040
1041 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1042 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1043
1044 CGF.EmitBlock(RHSBlock);
1045 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1046
1047 // Reaquire the RHS block, as there may be subblocks inserted.
1048 RHSBlock = Builder.GetInsertBlock();
1049 CGF.EmitBlock(ContBlock);
1050
1051 // Create a PHI node. If we just evaluted the LHS condition, the result is
1052 // true. If we evaluated both, the result is the RHS condition.
1053 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1054 PN->reserveOperandSpace(2);
1055 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1056 PN->addIncoming(RHSCond, RHSBlock);
1057
1058 // ZExt result to int.
1059 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1060}
1061
1062Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1063 CGF.EmitStmt(E->getLHS());
1064 return Visit(E->getRHS());
1065}
1066
1067//===----------------------------------------------------------------------===//
1068// Other Operators
1069//===----------------------------------------------------------------------===//
1070
1071Value *ScalarExprEmitter::
1072VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001073 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1074 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1075 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001076
Chris Lattner98a425c2007-11-26 01:40:58 +00001077 // Evaluate the conditional, then convert it to bool. We do this explicitly
1078 // because we need the unconverted value if this is a GNU ?: expression with
1079 // missing middle value.
1080 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001081 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1082 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001083 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001084
1085 CGF.EmitBlock(LHSBlock);
1086
1087 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001088 Value *LHS;
1089 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001090 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001091 else // Perform promotions, to handle cases like "short ?: int"
1092 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1093
Chris Lattner9fba49a2007-08-24 05:35:26 +00001094 Builder.CreateBr(ContBlock);
1095 LHSBlock = Builder.GetInsertBlock();
1096
1097 CGF.EmitBlock(RHSBlock);
1098
Eli Friedmance8d7032008-05-16 20:38:39 +00001099 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001100 Builder.CreateBr(ContBlock);
1101 RHSBlock = Builder.GetInsertBlock();
1102
1103 CGF.EmitBlock(ContBlock);
1104
Nuno Lopesb62ff242008-06-04 19:15:45 +00001105 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001106 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1107 return 0;
1108 }
1109
Chris Lattner9fba49a2007-08-24 05:35:26 +00001110 // Create a PHI node for the real part.
1111 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1112 PN->reserveOperandSpace(2);
1113 PN->addIncoming(LHS, LHSBlock);
1114 PN->addIncoming(RHS, RHSBlock);
1115 return PN;
1116}
1117
1118Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001119 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001120 return
1121 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001122}
1123
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001124Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001125 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001126 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001127}
1128
Chris Lattner307da022007-11-30 17:56:23 +00001129Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001130 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1131
1132 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1133 return V;
1134}
1135
Chris Lattner307da022007-11-30 17:56:23 +00001136Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001137 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001138 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1139 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1140 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001141
1142 llvm::Constant *C = llvm::ConstantArray::get(str);
1143 C = new llvm::GlobalVariable(C->getType(), true,
1144 llvm::GlobalValue::InternalLinkage,
1145 C, ".str", &CGF.CGM.getModule());
1146 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1147 llvm::Constant *Zeros[] = { Zero, Zero };
1148 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1149
1150 return C;
1151}
1152
Chris Lattner9fba49a2007-08-24 05:35:26 +00001153//===----------------------------------------------------------------------===//
1154// Entry Point into this File
1155//===----------------------------------------------------------------------===//
1156
1157/// EmitComplexExpr - Emit the computation of the specified expression of
1158/// complex type, ignoring the result.
1159Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1160 assert(E && !hasAggregateLLVMType(E->getType()) &&
1161 "Invalid scalar expression to emit");
1162
1163 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1164}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001165
1166/// EmitScalarConversion - Emit a conversion from the specified type to the
1167/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001168Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1169 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001170 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1171 "Invalid scalar expression to emit");
1172 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1173}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001174
1175/// EmitComplexToScalarConversion - Emit a conversion from the specified
1176/// complex type to the specified destination type, where the destination
1177/// type is an LLVM scalar type.
1178Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1179 QualType SrcTy,
1180 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001181 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001182 "Invalid complex -> scalar conversion");
1183 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1184 DstTy);
1185}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001186
1187Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1188 assert(V1->getType() == V2->getType() &&
1189 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001190 unsigned NumElements =
1191 cast<llvm::VectorType>(V1->getType())->getNumElements();
1192
1193 va_list va;
1194 va_start(va, V2);
1195
1196 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001197 for (unsigned i = 0; i < NumElements; i++) {
1198 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001199 assert(n >= 0 && n < (int)NumElements * 2 &&
1200 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001201 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1202 }
1203
1204 const char *Name = va_arg(va, const char *);
1205 va_end(va);
1206
1207 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1208
1209 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1210}
1211
Anders Carlsson68b8be92007-12-15 21:23:30 +00001212llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001213 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001214 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001215 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001216
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001217 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001218 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001219 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001220 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001221 }
1222
1223 return Vec;
1224}