blob: a7ca2da04e34835f2efdd8f5e49ffd6552fbdb35 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
22using namespace clang;
23using namespace CodeGen;
24using llvm::Value;
25
26//===----------------------------------------------------------------------===//
27// Scalar Expression Emitter
28//===----------------------------------------------------------------------===//
29
30struct BinOpInfo {
31 Value *LHS;
32 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000033 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000034 const BinaryOperator *E;
35};
36
37namespace {
38class VISIBILITY_HIDDEN ScalarExprEmitter
39 : public StmtVisitor<ScalarExprEmitter, Value*> {
40 CodeGenFunction &CGF;
Devang Patel638b64c2007-10-09 19:49:58 +000041 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner9fba49a2007-08-24 05:35:26 +000042public:
43
44 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
45 }
46
47
48 //===--------------------------------------------------------------------===//
49 // Utilities
50 //===--------------------------------------------------------------------===//
51
52 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
53 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
54
55 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000056 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000057 }
58
59 /// EmitLoadOfLValue - Given an expression with complex type that represents a
60 /// value l-value, this method emits the address of the l-value, then loads
61 /// and returns the result.
62 Value *EmitLoadOfLValue(const Expr *E) {
63 // FIXME: Volatile
64 return EmitLoadOfLValue(EmitLValue(E), E->getType());
65 }
66
Chris Lattnerd8d44222007-08-26 16:42:57 +000067 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000068 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000069 Value *EmitConversionToBool(Value *Src, QualType DstTy);
70
Chris Lattner4e05d1e2007-08-26 06:48:56 +000071 /// EmitScalarConversion - Emit a conversion from the specified type to the
72 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000073 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
74
75 /// EmitComplexToScalarConversion - Emit a conversion from the specified
76 /// complex type to the specified destination type, where the destination
77 /// type is an LLVM scalar type.
78 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
79 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080
Chris Lattner9fba49a2007-08-24 05:35:26 +000081 //===--------------------------------------------------------------------===//
82 // Visitor Methods
83 //===--------------------------------------------------------------------===//
84
85 Value *VisitStmt(Stmt *S) {
Chris Lattner1aef6212007-09-13 01:17:29 +000086 S->dump(CGF.getContext().SourceMgr);
Chris Lattner9fba49a2007-08-24 05:35:26 +000087 assert(0 && "Stmt can't have complex result type!");
88 return 0;
89 }
90 Value *VisitExpr(Expr *S);
91 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
92
93 // Leaves.
94 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
95 return llvm::ConstantInt::get(E->getValue());
96 }
97 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +000098 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +000099 }
100 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
101 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
102 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000103 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
104 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
105 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000106 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
107 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000108 CGF.getContext().typesAreCompatible(
109 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000110 }
111 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
112 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
113 }
114
115 // l-values.
116 Value *VisitDeclRefExpr(DeclRefExpr *E) {
117 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
118 return llvm::ConstantInt::get(EC->getInitVal());
119 return EmitLoadOfLValue(E);
120 }
121 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
122 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
123 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
124 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
125 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000126
127 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000128 unsigned NumInitElements = E->getNumInits();
129
130 std::vector<llvm::Constant*> VectorElts;
131 const llvm::VectorType *VType =
132 cast<llvm::VectorType>(ConvertType(E->getType()));
133
134 // Copy initializer elements.
135 bool AllConstElements = true;
136 unsigned i = 0;
137 for (i = 0; i < NumInitElements; ++i) {
138 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Visit(E->getInit(i))))
139 VectorElts.push_back(C);
140 else {
141 AllConstElements = false;
142 break;
143 }
144 }
145
146 unsigned NumVectorElements = VType->getNumElements();
147 const llvm::Type *ElementType = VType->getElementType();
148 if (AllConstElements) {
149 // Initialize remaining array elements.
150 for (/*Do not initialize i*/; i < NumVectorElements; ++i)
151 VectorElts.push_back(llvm::Constant::getNullValue(ElementType));
152
153 return llvm::ConstantVector::get(VectorElts);
154 }
155
156 // Emit individual vector element stores.
157 llvm::Value *V = llvm::UndefValue::get(VType);
158
159 // Emit already seen constants initializers.
160 for (i = 0; i < VectorElts.size(); i++) {
161 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
162 V = Builder.CreateInsertElement(V, VectorElts[i], Idx);
163 }
164
165 // Emit remaining initializers
166 for (/*Do not initialize i*/; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000167 Value *NewV = Visit(E->getInit(i));
168 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
169 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000170 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000171
172 // Emit remaining default initializers
173 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
174 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
175 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
176 V = Builder.CreateInsertElement(V, NewV, Idx);
177 }
178
Devang Patel32c39832007-10-24 18:05:48 +0000179 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000180 }
181
182 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
183 return Visit(E->getInitializer());
184 }
185
Chris Lattner9fba49a2007-08-24 05:35:26 +0000186 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
187 Value *VisitCastExpr(const CastExpr *E) {
188 return EmitCastExpr(E->getSubExpr(), E->getType());
189 }
190 Value *EmitCastExpr(const Expr *E, QualType T);
191
192 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000193 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000194 }
195
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000196 Value *VisitStmtExpr(const StmtExpr *E);
197
Chris Lattner9fba49a2007-08-24 05:35:26 +0000198 // Unary Operators.
199 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
200 Value *VisitUnaryPostDec(const UnaryOperator *E) {
201 return VisitPrePostIncDec(E, false, false);
202 }
203 Value *VisitUnaryPostInc(const UnaryOperator *E) {
204 return VisitPrePostIncDec(E, true, false);
205 }
206 Value *VisitUnaryPreDec(const UnaryOperator *E) {
207 return VisitPrePostIncDec(E, false, true);
208 }
209 Value *VisitUnaryPreInc(const UnaryOperator *E) {
210 return VisitPrePostIncDec(E, true, true);
211 }
212 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
213 return EmitLValue(E->getSubExpr()).getAddress();
214 }
215 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
216 Value *VisitUnaryPlus(const UnaryOperator *E) {
217 return Visit(E->getSubExpr());
218 }
219 Value *VisitUnaryMinus (const UnaryOperator *E);
220 Value *VisitUnaryNot (const UnaryOperator *E);
221 Value *VisitUnaryLNot (const UnaryOperator *E);
222 Value *VisitUnarySizeOf (const UnaryOperator *E) {
223 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
224 }
225 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
226 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
227 }
228 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
229 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000230 Value *VisitUnaryReal (const UnaryOperator *E);
231 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000232 Value *VisitUnaryExtension(const UnaryOperator *E) {
233 return Visit(E->getSubExpr());
234 }
235
236 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000237 Value *EmitMul(const BinOpInfo &Ops) {
238 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
239 }
240 Value *EmitDiv(const BinOpInfo &Ops);
241 Value *EmitRem(const BinOpInfo &Ops);
242 Value *EmitAdd(const BinOpInfo &Ops);
243 Value *EmitSub(const BinOpInfo &Ops);
244 Value *EmitShl(const BinOpInfo &Ops);
245 Value *EmitShr(const BinOpInfo &Ops);
246 Value *EmitAnd(const BinOpInfo &Ops) {
247 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
248 }
249 Value *EmitXor(const BinOpInfo &Ops) {
250 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
251 }
252 Value *EmitOr (const BinOpInfo &Ops) {
253 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
254 }
255
Chris Lattner660e31d2007-08-24 21:00:35 +0000256 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000257 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000258 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
259
260 // Binary operators and binary compound assignment operators.
261#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000262 Value *VisitBin ## OP(const BinaryOperator *E) { \
263 return Emit ## OP(EmitBinOps(E)); \
264 } \
265 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
266 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000267 }
268 HANDLEBINOP(Mul);
269 HANDLEBINOP(Div);
270 HANDLEBINOP(Rem);
271 HANDLEBINOP(Add);
272 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
273 HANDLEBINOP(Shl);
274 HANDLEBINOP(Shr);
275 HANDLEBINOP(And);
276 HANDLEBINOP(Xor);
277 HANDLEBINOP(Or);
278#undef HANDLEBINOP
279 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000280 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000281 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
282 }
283
Chris Lattner9fba49a2007-08-24 05:35:26 +0000284 // Comparisons.
285 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
286 unsigned SICmpOpc, unsigned FCmpOpc);
287#define VISITCOMP(CODE, UI, SI, FP) \
288 Value *VisitBin##CODE(const BinaryOperator *E) { \
289 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
290 llvm::FCmpInst::FP); }
291 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
292 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
293 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
294 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
295 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
296 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
297#undef VISITCOMP
298
299 Value *VisitBinAssign (const BinaryOperator *E);
300
301 Value *VisitBinLAnd (const BinaryOperator *E);
302 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000303 Value *VisitBinComma (const BinaryOperator *E);
304
305 // Other Operators.
306 Value *VisitConditionalOperator(const ConditionalOperator *CO);
307 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000308 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000309 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
310 return CGF.EmitObjCStringLiteral(E);
311 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000312 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000313};
314} // end anonymous namespace.
315
316//===----------------------------------------------------------------------===//
317// Utilities
318//===----------------------------------------------------------------------===//
319
Chris Lattnerd8d44222007-08-26 16:42:57 +0000320/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000321/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000322Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
323 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
324
325 if (SrcType->isRealFloatingType()) {
326 // Compare against 0.0 for fp scalars.
327 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000328 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
329 }
330
331 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
332 "Unknown scalar type to convert");
333
334 // Because of the type rules of C, we often end up computing a logical value,
335 // then zero extending it to int, then wanting it as a logical value again.
336 // Optimize this common case.
337 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
338 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
339 Value *Result = ZI->getOperand(0);
340 ZI->eraseFromParent();
341 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 Lattner4e05d1e2007-08-26 06:48:56 +0000354 SrcType = SrcType.getCanonicalType();
355 DstType = DstType.getCanonicalType();
356 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
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000386 if (isa<llvm::VectorType>(Src->getType()) ||
387 isa<llvm::VectorType>(DstTy)) {
388 return Builder.CreateBitCast(Src, DstTy, "conv");
389 }
390
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000391 // Finally, we have the arithmetic types: real int/float.
392 if (isa<llvm::IntegerType>(Src->getType())) {
393 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000394 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
395 if (isa<llvm::IntegerType>(DstTy))
396 return llvm::ConstantExpr::getIntegerCast(C, DstTy, InputSigned);
397 else if (InputSigned)
398 return llvm::ConstantExpr::getSIToFP(C, DstTy);
399 else
400 return llvm::ConstantExpr::getUIToFP(C, DstTy);
401 } else {
402 if (isa<llvm::IntegerType>(DstTy))
403 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
404 else if (InputSigned)
405 return Builder.CreateSIToFP(Src, DstTy, "conv");
406 else
407 return Builder.CreateUIToFP(Src, DstTy, "conv");
408 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000409 }
410
411 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
412 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000413 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
414 if (DstType->isSignedIntegerType())
415 return llvm::ConstantExpr::getFPToSI(C, DstTy);
416 else
417 return llvm::ConstantExpr::getFPToUI(C, DstTy);
418 } else {
419 if (DstType->isSignedIntegerType())
420 return Builder.CreateFPToSI(Src, DstTy, "conv");
421 else
422 return Builder.CreateFPToUI(Src, DstTy, "conv");
423 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000424 }
425
426 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000427 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
428 if (DstTy->getTypeID() < Src->getType()->getTypeID())
429 return llvm::ConstantExpr::getFPTrunc(C, DstTy);
430 else
431 return llvm::ConstantExpr::getFPExtend(C, DstTy);
432 } else {
433 if (DstTy->getTypeID() < Src->getType()->getTypeID())
434 return Builder.CreateFPTrunc(Src, DstTy, "conv");
435 else
436 return Builder.CreateFPExt(Src, DstTy, "conv");
437 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000438}
439
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000440/// EmitComplexToScalarConversion - Emit a conversion from the specified
441/// complex type to the specified destination type, where the destination
442/// type is an LLVM scalar type.
443Value *ScalarExprEmitter::
444EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
445 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000446 // Get the source element type.
447 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
448
449 // Handle conversions to bool first, they are special: comparisons against 0.
450 if (DstTy->isBooleanType()) {
451 // Complex != 0 -> (Real != 0) | (Imag != 0)
452 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
453 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
454 return Builder.CreateOr(Src.first, Src.second, "tobool");
455 }
456
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000457 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
458 // the imaginary part of the complex value is discarded and the value of the
459 // real part is converted according to the conversion rules for the
460 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000461 return EmitScalarConversion(Src.first, SrcTy, DstTy);
462}
463
464
Chris Lattner9fba49a2007-08-24 05:35:26 +0000465//===----------------------------------------------------------------------===//
466// Visitor Methods
467//===----------------------------------------------------------------------===//
468
469Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000470 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000471 if (E->getType()->isVoidType())
472 return 0;
473 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
474}
475
476Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
477 // Emit subscript expressions in rvalue context's. For most cases, this just
478 // loads the lvalue formed by the subscript expr. However, we have to be
479 // careful, because the base of a vector subscript is occasionally an rvalue,
480 // so we can't get it as an lvalue.
481 if (!E->getBase()->getType()->isVectorType())
482 return EmitLoadOfLValue(E);
483
484 // Handle the vector case. The base must be a vector, the index must be an
485 // integer value.
486 Value *Base = Visit(E->getBase());
487 Value *Idx = Visit(E->getIdx());
488
489 // FIXME: Convert Idx to i32 type.
490 return Builder.CreateExtractElement(Base, Idx, "vecext");
491}
492
493/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
494/// also handle things like function to pointer-to-function decay, and array to
495/// pointer decay.
496Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
497 const Expr *Op = E->getSubExpr();
498
499 // If this is due to array->pointer conversion, emit the array expression as
500 // an l-value.
501 if (Op->getType()->isArrayType()) {
502 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
503 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000504 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000505
506 assert(isa<llvm::PointerType>(V->getType()) &&
507 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
508 ->getElementType()) &&
509 "Doesn't support VLAs yet!");
510 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000511
512 llvm::Value *Ops[] = {Idx0, Idx0};
513 return Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000514 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000515 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
516 getReferenceeType() ==
517 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000518
519 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000520 }
521
522 return EmitCastExpr(Op, E->getType());
523}
524
525
526// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
527// have to handle a more broad range of conversions than explicit casts, as they
528// handle things like function to ptr-to-function decay etc.
529Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000530 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000531 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000532 Value *Src = Visit(const_cast<Expr*>(E));
533
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000534 // Use EmitScalarConversion to perform the conversion.
535 return EmitScalarConversion(Src, E->getType(), DestTy);
536 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000537
Chris Lattner82e10392007-08-26 07:26:12 +0000538 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000539 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
540 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000541}
542
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000543Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000544 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000545}
546
547
Chris Lattner9fba49a2007-08-24 05:35:26 +0000548//===----------------------------------------------------------------------===//
549// Unary Operators
550//===----------------------------------------------------------------------===//
551
552Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000553 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000554 LValue LV = EmitLValue(E->getSubExpr());
555 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000556 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000557 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000558
559 int AmountVal = isInc ? 1 : -1;
560
561 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000562 if (isa<llvm::PointerType>(InVal->getType())) {
563 // FIXME: This isn't right for VLAs.
564 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
565 NextVal = Builder.CreateGEP(InVal, NextVal);
566 } else {
567 // Add the inc/dec to the real part.
568 if (isa<llvm::IntegerType>(InVal->getType()))
569 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000570 else if (InVal->getType() == llvm::Type::FloatTy)
571 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000572 NextVal =
573 llvm::ConstantFP::get(InVal->getType(),
574 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000575 else {
576 // FIXME: Handle long double.
577 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000578 NextVal =
579 llvm::ConstantFP::get(InVal->getType(),
580 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000581 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000582 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
583 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000584
585 // Store the updated result through the lvalue.
586 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
587 E->getSubExpr()->getType());
588
589 // If this is a postinc, return the value read from memory, otherwise use the
590 // updated value.
591 return isPre ? NextVal : InVal;
592}
593
594
595Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
596 Value *Op = Visit(E->getSubExpr());
597 return Builder.CreateNeg(Op, "neg");
598}
599
600Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
601 Value *Op = Visit(E->getSubExpr());
602 return Builder.CreateNot(Op, "neg");
603}
604
605Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
606 // Compare operand to zero.
607 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
608
609 // Invert value.
610 // TODO: Could dynamically modify easy computations here. For example, if
611 // the operand is an icmp ne, turn into icmp eq.
612 BoolVal = Builder.CreateNot(BoolVal, "lnot");
613
614 // ZExt result to int.
615 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
616}
617
618/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
619/// an integer (RetType).
620Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000621 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000622 /// FIXME: This doesn't handle VLAs yet!
623 std::pair<uint64_t, unsigned> Info =
624 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
625
626 uint64_t Val = isSizeOf ? Info.first : Info.second;
627 Val /= 8; // Return size in bytes, not bits.
628
629 assert(RetType->isIntegerType() && "Result type must be an integer!");
630
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000631 uint32_t ResultWidth = static_cast<uint32_t>(
632 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000633 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
634}
635
Chris Lattner01211af2007-08-24 21:20:17 +0000636Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
637 Expr *Op = E->getSubExpr();
638 if (Op->getType()->isComplexType())
639 return CGF.EmitComplexExpr(Op).first;
640 return Visit(Op);
641}
642Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
643 Expr *Op = E->getSubExpr();
644 if (Op->getType()->isComplexType())
645 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000646
647 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
648 // effects are evaluated.
649 CGF.EmitScalarExpr(Op);
650 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000651}
652
653
Chris Lattner9fba49a2007-08-24 05:35:26 +0000654//===----------------------------------------------------------------------===//
655// Binary Operators
656//===----------------------------------------------------------------------===//
657
658BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
659 BinOpInfo Result;
660 Result.LHS = Visit(E->getLHS());
661 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000662 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000663 Result.E = E;
664 return Result;
665}
666
Chris Lattner0d965302007-08-26 21:41:21 +0000667Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000668 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
669 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
670
671 BinOpInfo OpInfo;
672
673 // Load the LHS and RHS operands.
674 LValue LHSLV = EmitLValue(E->getLHS());
675 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000676
677 // Determine the computation type. If the RHS is complex, then this is one of
678 // the add/sub/mul/div operators. All of these operators can be computed in
679 // with just their real component even though the computation domain really is
680 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000681 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000682
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000683 // If the computation type is complex, then the RHS is complex. Emit the RHS.
684 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
685 ComputeType = CT->getElementType();
686
687 // Emit the RHS, only keeping the real component.
688 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
689 RHSTy = RHSTy->getAsComplexType()->getElementType();
690 } else {
691 // Otherwise the RHS is a simple scalar value.
692 OpInfo.RHS = Visit(E->getRHS());
693 }
694
695 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000696 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000697
Devang Patel04011802007-10-25 22:19:13 +0000698 // Do not merge types for -= or += where the LHS is a pointer.
699 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000700 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000701 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000702 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000703 }
704 OpInfo.Ty = ComputeType;
705 OpInfo.E = E;
706
707 // Expand the binary operator.
708 Value *Result = (this->*Func)(OpInfo);
709
710 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000711 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000712
713 // Store the result value into the LHS lvalue.
714 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
715
716 return Result;
717}
718
719
Chris Lattner9fba49a2007-08-24 05:35:26 +0000720Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
721 if (Ops.LHS->getType()->isFloatingPoint())
722 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000723 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000724 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
725 else
726 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
727}
728
729Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
730 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000731 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000732 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
733 else
734 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
735}
736
737
738Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000739 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000740 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000741
742 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000743 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
744 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
745 // int + pointer
746 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
747}
748
749Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
750 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
751 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
752
Chris Lattner660e31d2007-08-24 21:00:35 +0000753 // pointer - int
754 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
755 "ptr-ptr shouldn't get here");
756 // FIXME: The pointer could point to a VLA.
757 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
758 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
759}
760
761Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
762 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
763 // the compound assignment case it is invalid, so just handle it here.
764 if (!E->getRHS()->getType()->isPointerType())
765 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000766
767 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000768 Value *LHS = Visit(E->getLHS());
769 Value *RHS = Visit(E->getRHS());
770
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000771 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
772 const QualType RHSType = E->getRHS()->getType().getCanonicalType();
773 assert(LHSType == RHSType && "Can't subtract different pointer types");
Chris Lattner660e31d2007-08-24 21:00:35 +0000774
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000775 QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000776 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
777 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000778
779 const llvm::Type *ResultType = ConvertType(E->getType());
780 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
781 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
782 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000783
784 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
785 // remainder. As such, we handle common power-of-two cases here to generate
786 // better code.
787 if (llvm::isPowerOf2_64(ElementSize)) {
788 Value *ShAmt =
789 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
790 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
791 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000792
Chris Lattner9fba49a2007-08-24 05:35:26 +0000793 // Otherwise, do a full sdiv.
794 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
795 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
796}
797
Chris Lattner660e31d2007-08-24 21:00:35 +0000798
Chris Lattner9fba49a2007-08-24 05:35:26 +0000799Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
800 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
801 // RHS to the same size as the LHS.
802 Value *RHS = Ops.RHS;
803 if (Ops.LHS->getType() != RHS->getType())
804 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
805
806 return Builder.CreateShl(Ops.LHS, RHS, "shl");
807}
808
809Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
810 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
811 // RHS to the same size as the LHS.
812 Value *RHS = Ops.RHS;
813 if (Ops.LHS->getType() != RHS->getType())
814 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
815
Chris Lattner660e31d2007-08-24 21:00:35 +0000816 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000817 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
818 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
819}
820
821Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
822 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000823 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000824 QualType LHSTy = E->getLHS()->getType();
825 if (!LHSTy->isComplexType()) {
826 Value *LHS = Visit(E->getLHS());
827 Value *RHS = Visit(E->getRHS());
828
829 if (LHS->getType()->isFloatingPoint()) {
830 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
831 LHS, RHS, "cmp");
832 } else if (LHSTy->isUnsignedIntegerType()) {
833 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
834 LHS, RHS, "cmp");
835 } else {
836 // Signed integers and pointers.
837 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
838 LHS, RHS, "cmp");
839 }
840 } else {
841 // Complex Comparison: can only be an equality comparison.
842 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
843 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
844
845 QualType CETy =
846 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
847
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000848 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000849 if (CETy->isRealFloatingType()) {
850 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
851 LHS.first, RHS.first, "cmp.r");
852 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
853 LHS.second, RHS.second, "cmp.i");
854 } else {
855 // Complex comparisons can only be equality comparisons. As such, signed
856 // and unsigned opcodes are the same.
857 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
858 LHS.first, RHS.first, "cmp.r");
859 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
860 LHS.second, RHS.second, "cmp.i");
861 }
862
863 if (E->getOpcode() == BinaryOperator::EQ) {
864 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
865 } else {
866 assert(E->getOpcode() == BinaryOperator::NE &&
867 "Complex comparison other than == or != ?");
868 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
869 }
870 }
871
872 // ZExt result to int.
873 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
874}
875
876Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
877 LValue LHS = EmitLValue(E->getLHS());
878 Value *RHS = Visit(E->getRHS());
879
880 // Store the value into the LHS.
881 // FIXME: Volatility!
882 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
883
884 // Return the RHS.
885 return RHS;
886}
887
888Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
889 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
890
891 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
892 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
893
894 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
895 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
896
897 CGF.EmitBlock(RHSBlock);
898 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
899
900 // Reaquire the RHS block, as there may be subblocks inserted.
901 RHSBlock = Builder.GetInsertBlock();
902 CGF.EmitBlock(ContBlock);
903
904 // Create a PHI node. If we just evaluted the LHS condition, the result is
905 // false. If we evaluated both, the result is the RHS condition.
906 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
907 PN->reserveOperandSpace(2);
908 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
909 PN->addIncoming(RHSCond, RHSBlock);
910
911 // ZExt result to int.
912 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
913}
914
915Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
916 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
917
918 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
919 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
920
921 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
922 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
923
924 CGF.EmitBlock(RHSBlock);
925 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
926
927 // Reaquire the RHS block, as there may be subblocks inserted.
928 RHSBlock = Builder.GetInsertBlock();
929 CGF.EmitBlock(ContBlock);
930
931 // Create a PHI node. If we just evaluted the LHS condition, the result is
932 // true. If we evaluated both, the result is the RHS condition.
933 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
934 PN->reserveOperandSpace(2);
935 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
936 PN->addIncoming(RHSCond, RHSBlock);
937
938 // ZExt result to int.
939 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
940}
941
942Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
943 CGF.EmitStmt(E->getLHS());
944 return Visit(E->getRHS());
945}
946
947//===----------------------------------------------------------------------===//
948// Other Operators
949//===----------------------------------------------------------------------===//
950
951Value *ScalarExprEmitter::
952VisitConditionalOperator(const ConditionalOperator *E) {
953 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
954 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
955 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
956
Chris Lattner98a425c2007-11-26 01:40:58 +0000957 // Evaluate the conditional, then convert it to bool. We do this explicitly
958 // because we need the unconverted value if this is a GNU ?: expression with
959 // missing middle value.
960 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
961 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
962 CGF.getContext().BoolTy);
963 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000964
965 CGF.EmitBlock(LHSBlock);
966
967 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000968 Value *LHS;
969 if (E->getLHS())
970 LHS = Visit(E->getLHS());
971 else // Perform promotions, to handle cases like "short ?: int"
972 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
973
Chris Lattner9fba49a2007-08-24 05:35:26 +0000974 Builder.CreateBr(ContBlock);
975 LHSBlock = Builder.GetInsertBlock();
976
977 CGF.EmitBlock(RHSBlock);
978
979 Value *RHS = Visit(E->getRHS());
980 Builder.CreateBr(ContBlock);
981 RHSBlock = Builder.GetInsertBlock();
982
983 CGF.EmitBlock(ContBlock);
984
Chris Lattner307da022007-11-30 17:56:23 +0000985 if (!LHS) {
986 assert(E->getType()->isVoidType() && "Non-void value should have a value");
987 return 0;
988 }
989
Chris Lattner9fba49a2007-08-24 05:35:26 +0000990 // Create a PHI node for the real part.
991 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
992 PN->reserveOperandSpace(2);
993 PN->addIncoming(LHS, LHSBlock);
994 PN->addIncoming(RHS, RHSBlock);
995 return PN;
996}
997
998Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000999 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001000 return
1001 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001002}
1003
Chris Lattner307da022007-11-30 17:56:23 +00001004Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001005 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1006
1007 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1008 return V;
1009}
1010
Chris Lattner307da022007-11-30 17:56:23 +00001011Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001012 std::string str;
1013
1014 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
1015
1016 llvm::Constant *C = llvm::ConstantArray::get(str);
1017 C = new llvm::GlobalVariable(C->getType(), true,
1018 llvm::GlobalValue::InternalLinkage,
1019 C, ".str", &CGF.CGM.getModule());
1020 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1021 llvm::Constant *Zeros[] = { Zero, Zero };
1022 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1023
1024 return C;
1025}
1026
Chris Lattner9fba49a2007-08-24 05:35:26 +00001027//===----------------------------------------------------------------------===//
1028// Entry Point into this File
1029//===----------------------------------------------------------------------===//
1030
1031/// EmitComplexExpr - Emit the computation of the specified expression of
1032/// complex type, ignoring the result.
1033Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1034 assert(E && !hasAggregateLLVMType(E->getType()) &&
1035 "Invalid scalar expression to emit");
1036
1037 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1038}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001039
1040/// EmitScalarConversion - Emit a conversion from the specified type to the
1041/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001042Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1043 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001044 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1045 "Invalid scalar expression to emit");
1046 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1047}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001048
1049/// EmitComplexToScalarConversion - Emit a conversion from the specified
1050/// complex type to the specified destination type, where the destination
1051/// type is an LLVM scalar type.
1052Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1053 QualType SrcTy,
1054 QualType DstTy) {
1055 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1056 "Invalid complex -> scalar conversion");
1057 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1058 DstTy);
1059}