blob: 1499054b6cce8bf7047d7b82378bfb42ae9860fc [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"
19#include "llvm/Support/Compiler.h"
20using namespace clang;
21using namespace CodeGen;
22using llvm::Value;
23
24//===----------------------------------------------------------------------===//
25// Scalar Expression Emitter
26//===----------------------------------------------------------------------===//
27
28struct BinOpInfo {
29 Value *LHS;
30 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000031 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000032 const BinaryOperator *E;
33};
34
35namespace {
36class VISIBILITY_HIDDEN ScalarExprEmitter
37 : public StmtVisitor<ScalarExprEmitter, Value*> {
38 CodeGenFunction &CGF;
39 llvm::LLVMBuilder &Builder;
40public:
41
42 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
43 }
44
45
46 //===--------------------------------------------------------------------===//
47 // Utilities
48 //===--------------------------------------------------------------------===//
49
50 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
51 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
52
53 Value *EmitLoadOfLValue(LValue LV, QualType T) {
54 return CGF.EmitLoadOfLValue(LV, T).getVal();
55 }
56
57 /// EmitLoadOfLValue - Given an expression with complex type that represents a
58 /// value l-value, this method emits the address of the l-value, then loads
59 /// and returns the result.
60 Value *EmitLoadOfLValue(const Expr *E) {
61 // FIXME: Volatile
62 return EmitLoadOfLValue(EmitLValue(E), E->getType());
63 }
64
Chris Lattnerd8d44222007-08-26 16:42:57 +000065 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000066 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000067 Value *EmitConversionToBool(Value *Src, QualType DstTy);
68
Chris Lattner4e05d1e2007-08-26 06:48:56 +000069 /// EmitScalarConversion - Emit a conversion from the specified type to the
70 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000071 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
72
73 /// EmitComplexToScalarConversion - Emit a conversion from the specified
74 /// complex type to the specified destination type, where the destination
75 /// type is an LLVM scalar type.
76 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
77 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000078
Chris Lattner9fba49a2007-08-24 05:35:26 +000079 //===--------------------------------------------------------------------===//
80 // Visitor Methods
81 //===--------------------------------------------------------------------===//
82
83 Value *VisitStmt(Stmt *S) {
84 S->dump();
85 assert(0 && "Stmt can't have complex result type!");
86 return 0;
87 }
88 Value *VisitExpr(Expr *S);
89 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
90
91 // Leaves.
92 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
93 return llvm::ConstantInt::get(E->getValue());
94 }
95 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
96 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
97 }
98 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
99 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
100 }
101 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
102 return llvm::ConstantInt::get(ConvertType(E->getType()),
103 E->typesAreCompatible());
104 }
105 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
106 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
107 }
108
109 // l-values.
110 Value *VisitDeclRefExpr(DeclRefExpr *E) {
111 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
112 return llvm::ConstantInt::get(EC->getInitVal());
113 return EmitLoadOfLValue(E);
114 }
115 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
116 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
117 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
118 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
119 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
120
121 // FIXME: CompoundLiteralExpr
122 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
123 Value *VisitCastExpr(const CastExpr *E) {
124 return EmitCastExpr(E->getSubExpr(), E->getType());
125 }
126 Value *EmitCastExpr(const Expr *E, QualType T);
127
128 Value *VisitCallExpr(const CallExpr *E) {
129 return CGF.EmitCallExpr(E).getVal();
130 }
131
132 // Unary Operators.
133 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
134 Value *VisitUnaryPostDec(const UnaryOperator *E) {
135 return VisitPrePostIncDec(E, false, false);
136 }
137 Value *VisitUnaryPostInc(const UnaryOperator *E) {
138 return VisitPrePostIncDec(E, true, false);
139 }
140 Value *VisitUnaryPreDec(const UnaryOperator *E) {
141 return VisitPrePostIncDec(E, false, true);
142 }
143 Value *VisitUnaryPreInc(const UnaryOperator *E) {
144 return VisitPrePostIncDec(E, true, true);
145 }
146 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
147 return EmitLValue(E->getSubExpr()).getAddress();
148 }
149 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
150 Value *VisitUnaryPlus(const UnaryOperator *E) {
151 return Visit(E->getSubExpr());
152 }
153 Value *VisitUnaryMinus (const UnaryOperator *E);
154 Value *VisitUnaryNot (const UnaryOperator *E);
155 Value *VisitUnaryLNot (const UnaryOperator *E);
156 Value *VisitUnarySizeOf (const UnaryOperator *E) {
157 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
158 }
159 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
160 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
161 }
162 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
163 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000164 Value *VisitUnaryReal (const UnaryOperator *E);
165 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000166 Value *VisitUnaryExtension(const UnaryOperator *E) {
167 return Visit(E->getSubExpr());
168 }
169
170 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000171 Value *EmitMul(const BinOpInfo &Ops) {
172 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
173 }
174 Value *EmitDiv(const BinOpInfo &Ops);
175 Value *EmitRem(const BinOpInfo &Ops);
176 Value *EmitAdd(const BinOpInfo &Ops);
177 Value *EmitSub(const BinOpInfo &Ops);
178 Value *EmitShl(const BinOpInfo &Ops);
179 Value *EmitShr(const BinOpInfo &Ops);
180 Value *EmitAnd(const BinOpInfo &Ops) {
181 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
182 }
183 Value *EmitXor(const BinOpInfo &Ops) {
184 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
185 }
186 Value *EmitOr (const BinOpInfo &Ops) {
187 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
188 }
189
Chris Lattner660e31d2007-08-24 21:00:35 +0000190 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000191 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000192 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
193
194 // Binary operators and binary compound assignment operators.
195#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000196 Value *VisitBin ## OP(const BinaryOperator *E) { \
197 return Emit ## OP(EmitBinOps(E)); \
198 } \
199 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
200 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000201 }
202 HANDLEBINOP(Mul);
203 HANDLEBINOP(Div);
204 HANDLEBINOP(Rem);
205 HANDLEBINOP(Add);
206 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
207 HANDLEBINOP(Shl);
208 HANDLEBINOP(Shr);
209 HANDLEBINOP(And);
210 HANDLEBINOP(Xor);
211 HANDLEBINOP(Or);
212#undef HANDLEBINOP
213 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000214 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000215 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
216 }
217
Chris Lattner9fba49a2007-08-24 05:35:26 +0000218 // Comparisons.
219 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
220 unsigned SICmpOpc, unsigned FCmpOpc);
221#define VISITCOMP(CODE, UI, SI, FP) \
222 Value *VisitBin##CODE(const BinaryOperator *E) { \
223 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
224 llvm::FCmpInst::FP); }
225 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
226 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
227 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
228 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
229 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
230 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
231#undef VISITCOMP
232
233 Value *VisitBinAssign (const BinaryOperator *E);
234
235 Value *VisitBinLAnd (const BinaryOperator *E);
236 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000237 Value *VisitBinComma (const BinaryOperator *E);
238
239 // Other Operators.
240 Value *VisitConditionalOperator(const ConditionalOperator *CO);
241 Value *VisitChooseExpr(ChooseExpr *CE);
242 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
243 return CGF.EmitObjCStringLiteral(E);
244 }
245};
246} // end anonymous namespace.
247
248//===----------------------------------------------------------------------===//
249// Utilities
250//===----------------------------------------------------------------------===//
251
Chris Lattnerd8d44222007-08-26 16:42:57 +0000252/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000253/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000254Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
255 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
256
257 if (SrcType->isRealFloatingType()) {
258 // Compare against 0.0 for fp scalars.
259 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000260 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
261 }
262
263 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
264 "Unknown scalar type to convert");
265
266 // Because of the type rules of C, we often end up computing a logical value,
267 // then zero extending it to int, then wanting it as a logical value again.
268 // Optimize this common case.
269 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
270 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
271 Value *Result = ZI->getOperand(0);
272 ZI->eraseFromParent();
273 return Result;
274 }
275 }
276
277 // Compare against an integer or pointer null.
278 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
279 return Builder.CreateICmpNE(Src, Zero, "tobool");
280}
281
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000282/// EmitScalarConversion - Emit a conversion from the specified type to the
283/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000284Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
285 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000286 SrcType = SrcType.getCanonicalType();
287 DstType = DstType.getCanonicalType();
288 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000289
290 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000291
292 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000293 if (DstType->isBooleanType())
294 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000295
296 const llvm::Type *DstTy = ConvertType(DstType);
297
298 // Ignore conversions like int -> uint.
299 if (Src->getType() == DstTy)
300 return Src;
301
302 // Handle pointer conversions next: pointers can only be converted to/from
303 // other pointers and integers.
304 if (isa<PointerType>(DstType)) {
305 // The source value may be an integer, or a pointer.
306 if (isa<llvm::PointerType>(Src->getType()))
307 return Builder.CreateBitCast(Src, DstTy, "conv");
308 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
309 return Builder.CreateIntToPtr(Src, DstTy, "conv");
310 }
311
312 if (isa<PointerType>(SrcType)) {
313 // Must be an ptr to int cast.
314 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
315 return Builder.CreateIntToPtr(Src, DstTy, "conv");
316 }
317
318 // Finally, we have the arithmetic types: real int/float.
319 if (isa<llvm::IntegerType>(Src->getType())) {
320 bool InputSigned = SrcType->isSignedIntegerType();
321 if (isa<llvm::IntegerType>(DstTy))
322 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
323 else if (InputSigned)
324 return Builder.CreateSIToFP(Src, DstTy, "conv");
325 else
326 return Builder.CreateUIToFP(Src, DstTy, "conv");
327 }
328
329 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
330 if (isa<llvm::IntegerType>(DstTy)) {
331 if (DstType->isSignedIntegerType())
332 return Builder.CreateFPToSI(Src, DstTy, "conv");
333 else
334 return Builder.CreateFPToUI(Src, DstTy, "conv");
335 }
336
337 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
338 if (DstTy->getTypeID() < Src->getType()->getTypeID())
339 return Builder.CreateFPTrunc(Src, DstTy, "conv");
340 else
341 return Builder.CreateFPExt(Src, DstTy, "conv");
342}
343
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000344/// EmitComplexToScalarConversion - Emit a conversion from the specified
345/// complex type to the specified destination type, where the destination
346/// type is an LLVM scalar type.
347Value *ScalarExprEmitter::
348EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
349 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000350 // Get the source element type.
351 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
352
353 // Handle conversions to bool first, they are special: comparisons against 0.
354 if (DstTy->isBooleanType()) {
355 // Complex != 0 -> (Real != 0) | (Imag != 0)
356 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
357 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
358 return Builder.CreateOr(Src.first, Src.second, "tobool");
359 }
360
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000361 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
362 // the imaginary part of the complex value is discarded and the value of the
363 // real part is converted according to the conversion rules for the
364 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000365 return EmitScalarConversion(Src.first, SrcTy, DstTy);
366}
367
368
Chris Lattner9fba49a2007-08-24 05:35:26 +0000369//===----------------------------------------------------------------------===//
370// Visitor Methods
371//===----------------------------------------------------------------------===//
372
373Value *ScalarExprEmitter::VisitExpr(Expr *E) {
374 fprintf(stderr, "Unimplemented scalar expr!\n");
375 E->dump();
376 if (E->getType()->isVoidType())
377 return 0;
378 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
379}
380
381Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
382 // Emit subscript expressions in rvalue context's. For most cases, this just
383 // loads the lvalue formed by the subscript expr. However, we have to be
384 // careful, because the base of a vector subscript is occasionally an rvalue,
385 // so we can't get it as an lvalue.
386 if (!E->getBase()->getType()->isVectorType())
387 return EmitLoadOfLValue(E);
388
389 // Handle the vector case. The base must be a vector, the index must be an
390 // integer value.
391 Value *Base = Visit(E->getBase());
392 Value *Idx = Visit(E->getIdx());
393
394 // FIXME: Convert Idx to i32 type.
395 return Builder.CreateExtractElement(Base, Idx, "vecext");
396}
397
398/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
399/// also handle things like function to pointer-to-function decay, and array to
400/// pointer decay.
401Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
402 const Expr *Op = E->getSubExpr();
403
404 // If this is due to array->pointer conversion, emit the array expression as
405 // an l-value.
406 if (Op->getType()->isArrayType()) {
407 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
408 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000409 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000410
411 assert(isa<llvm::PointerType>(V->getType()) &&
412 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
413 ->getElementType()) &&
414 "Doesn't support VLAs yet!");
415 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
416 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
417 }
418
419 return EmitCastExpr(Op, E->getType());
420}
421
422
423// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
424// have to handle a more broad range of conversions than explicit casts, as they
425// handle things like function to ptr-to-function decay etc.
426Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000427 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000428 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000429 Value *Src = Visit(const_cast<Expr*>(E));
430
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000431 // Use EmitScalarConversion to perform the conversion.
432 return EmitScalarConversion(Src, E->getType(), DestTy);
433 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000434
Chris Lattner82e10392007-08-26 07:26:12 +0000435 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000436 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
437 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000438}
439
440//===----------------------------------------------------------------------===//
441// Unary Operators
442//===----------------------------------------------------------------------===//
443
444Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000445 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000446 LValue LV = EmitLValue(E->getSubExpr());
447 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000448 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
449 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000450
451 int AmountVal = isInc ? 1 : -1;
452
453 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000454 if (isa<llvm::PointerType>(InVal->getType())) {
455 // FIXME: This isn't right for VLAs.
456 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
457 NextVal = Builder.CreateGEP(InVal, NextVal);
458 } else {
459 // Add the inc/dec to the real part.
460 if (isa<llvm::IntegerType>(InVal->getType()))
461 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
462 else
463 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
464 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
465 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000466
467 // Store the updated result through the lvalue.
468 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
469 E->getSubExpr()->getType());
470
471 // If this is a postinc, return the value read from memory, otherwise use the
472 // updated value.
473 return isPre ? NextVal : InVal;
474}
475
476
477Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
478 Value *Op = Visit(E->getSubExpr());
479 return Builder.CreateNeg(Op, "neg");
480}
481
482Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
483 Value *Op = Visit(E->getSubExpr());
484 return Builder.CreateNot(Op, "neg");
485}
486
487Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
488 // Compare operand to zero.
489 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
490
491 // Invert value.
492 // TODO: Could dynamically modify easy computations here. For example, if
493 // the operand is an icmp ne, turn into icmp eq.
494 BoolVal = Builder.CreateNot(BoolVal, "lnot");
495
496 // ZExt result to int.
497 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
498}
499
500/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
501/// an integer (RetType).
502Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000503 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000504 /// FIXME: This doesn't handle VLAs yet!
505 std::pair<uint64_t, unsigned> Info =
506 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
507
508 uint64_t Val = isSizeOf ? Info.first : Info.second;
509 Val /= 8; // Return size in bytes, not bits.
510
511 assert(RetType->isIntegerType() && "Result type must be an integer!");
512
513 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
514 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
515}
516
Chris Lattner01211af2007-08-24 21:20:17 +0000517Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
518 Expr *Op = E->getSubExpr();
519 if (Op->getType()->isComplexType())
520 return CGF.EmitComplexExpr(Op).first;
521 return Visit(Op);
522}
523Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
524 Expr *Op = E->getSubExpr();
525 if (Op->getType()->isComplexType())
526 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000527
528 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
529 // effects are evaluated.
530 CGF.EmitScalarExpr(Op);
531 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000532}
533
534
Chris Lattner9fba49a2007-08-24 05:35:26 +0000535//===----------------------------------------------------------------------===//
536// Binary Operators
537//===----------------------------------------------------------------------===//
538
539BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
540 BinOpInfo Result;
541 Result.LHS = Visit(E->getLHS());
542 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000543 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000544 Result.E = E;
545 return Result;
546}
547
Chris Lattner0d965302007-08-26 21:41:21 +0000548Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000549 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
550 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
551
552 BinOpInfo OpInfo;
553
554 // Load the LHS and RHS operands.
555 LValue LHSLV = EmitLValue(E->getLHS());
556 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000557
558 // Determine the computation type. If the RHS is complex, then this is one of
559 // the add/sub/mul/div operators. All of these operators can be computed in
560 // with just their real component even though the computation domain really is
561 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000562 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000563
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000564 // If the computation type is complex, then the RHS is complex. Emit the RHS.
565 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
566 ComputeType = CT->getElementType();
567
568 // Emit the RHS, only keeping the real component.
569 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
570 RHSTy = RHSTy->getAsComplexType()->getElementType();
571 } else {
572 // Otherwise the RHS is a simple scalar value.
573 OpInfo.RHS = Visit(E->getRHS());
574 }
575
576 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000577 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000578
579 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000580 if (E->getOpcode() != BinaryOperator::SubAssign ||
581 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000582 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000583 }
584 OpInfo.Ty = ComputeType;
585 OpInfo.E = E;
586
587 // Expand the binary operator.
588 Value *Result = (this->*Func)(OpInfo);
589
590 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000591 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000592
593 // Store the result value into the LHS lvalue.
594 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
595
596 return Result;
597}
598
599
Chris Lattner9fba49a2007-08-24 05:35:26 +0000600Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
601 if (Ops.LHS->getType()->isFloatingPoint())
602 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000603 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000604 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
605 else
606 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
607}
608
609Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
610 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000611 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000612 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
613 else
614 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
615}
616
617
618Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000619 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000620 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000621
622 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000623 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
624 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
625 // int + pointer
626 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
627}
628
629Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
630 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
631 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
632
Chris Lattner660e31d2007-08-24 21:00:35 +0000633 // pointer - int
634 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
635 "ptr-ptr shouldn't get here");
636 // FIXME: The pointer could point to a VLA.
637 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
638 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
639}
640
641Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
642 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
643 // the compound assignment case it is invalid, so just handle it here.
644 if (!E->getRHS()->getType()->isPointerType())
645 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000646
647 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000648 Value *LHS = Visit(E->getLHS());
649 Value *RHS = Visit(E->getRHS());
650
651 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
652 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
653 "Can't subtract different pointer types");
654
Chris Lattner9fba49a2007-08-24 05:35:26 +0000655 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000656 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
657 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000658
659 const llvm::Type *ResultType = ConvertType(E->getType());
660 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
661 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
662 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000663
664 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
665 // remainder. As such, we handle common power-of-two cases here to generate
666 // better code.
667 if (llvm::isPowerOf2_64(ElementSize)) {
668 Value *ShAmt =
669 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
670 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
671 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000672
Chris Lattner9fba49a2007-08-24 05:35:26 +0000673 // Otherwise, do a full sdiv.
674 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
675 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
676}
677
Chris Lattner660e31d2007-08-24 21:00:35 +0000678
Chris Lattner9fba49a2007-08-24 05:35:26 +0000679Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
680 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
681 // RHS to the same size as the LHS.
682 Value *RHS = Ops.RHS;
683 if (Ops.LHS->getType() != RHS->getType())
684 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
685
686 return Builder.CreateShl(Ops.LHS, RHS, "shl");
687}
688
689Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
690 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
691 // RHS to the same size as the LHS.
692 Value *RHS = Ops.RHS;
693 if (Ops.LHS->getType() != RHS->getType())
694 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
695
Chris Lattner660e31d2007-08-24 21:00:35 +0000696 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000697 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
698 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
699}
700
701Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
702 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000703 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000704 QualType LHSTy = E->getLHS()->getType();
705 if (!LHSTy->isComplexType()) {
706 Value *LHS = Visit(E->getLHS());
707 Value *RHS = Visit(E->getRHS());
708
709 if (LHS->getType()->isFloatingPoint()) {
710 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
711 LHS, RHS, "cmp");
712 } else if (LHSTy->isUnsignedIntegerType()) {
713 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
714 LHS, RHS, "cmp");
715 } else {
716 // Signed integers and pointers.
717 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
718 LHS, RHS, "cmp");
719 }
720 } else {
721 // Complex Comparison: can only be an equality comparison.
722 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
723 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
724
725 QualType CETy =
726 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
727
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000728 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000729 if (CETy->isRealFloatingType()) {
730 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
731 LHS.first, RHS.first, "cmp.r");
732 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
733 LHS.second, RHS.second, "cmp.i");
734 } else {
735 // Complex comparisons can only be equality comparisons. As such, signed
736 // and unsigned opcodes are the same.
737 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
738 LHS.first, RHS.first, "cmp.r");
739 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
740 LHS.second, RHS.second, "cmp.i");
741 }
742
743 if (E->getOpcode() == BinaryOperator::EQ) {
744 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
745 } else {
746 assert(E->getOpcode() == BinaryOperator::NE &&
747 "Complex comparison other than == or != ?");
748 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
749 }
750 }
751
752 // ZExt result to int.
753 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
754}
755
756Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
757 LValue LHS = EmitLValue(E->getLHS());
758 Value *RHS = Visit(E->getRHS());
759
760 // Store the value into the LHS.
761 // FIXME: Volatility!
762 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
763
764 // Return the RHS.
765 return RHS;
766}
767
768Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
769 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
770
771 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
772 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
773
774 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
775 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
776
777 CGF.EmitBlock(RHSBlock);
778 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
779
780 // Reaquire the RHS block, as there may be subblocks inserted.
781 RHSBlock = Builder.GetInsertBlock();
782 CGF.EmitBlock(ContBlock);
783
784 // Create a PHI node. If we just evaluted the LHS condition, the result is
785 // false. If we evaluated both, the result is the RHS condition.
786 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
787 PN->reserveOperandSpace(2);
788 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
789 PN->addIncoming(RHSCond, RHSBlock);
790
791 // ZExt result to int.
792 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
793}
794
795Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
796 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
797
798 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
799 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
800
801 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
802 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
803
804 CGF.EmitBlock(RHSBlock);
805 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
806
807 // Reaquire the RHS block, as there may be subblocks inserted.
808 RHSBlock = Builder.GetInsertBlock();
809 CGF.EmitBlock(ContBlock);
810
811 // Create a PHI node. If we just evaluted the LHS condition, the result is
812 // true. If we evaluated both, the result is the RHS condition.
813 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
814 PN->reserveOperandSpace(2);
815 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
816 PN->addIncoming(RHSCond, RHSBlock);
817
818 // ZExt result to int.
819 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
820}
821
822Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
823 CGF.EmitStmt(E->getLHS());
824 return Visit(E->getRHS());
825}
826
827//===----------------------------------------------------------------------===//
828// Other Operators
829//===----------------------------------------------------------------------===//
830
831Value *ScalarExprEmitter::
832VisitConditionalOperator(const ConditionalOperator *E) {
833 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
834 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
835 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
836
837 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
838 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
839
840 CGF.EmitBlock(LHSBlock);
841
842 // Handle the GNU extension for missing LHS.
843 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
844 Builder.CreateBr(ContBlock);
845 LHSBlock = Builder.GetInsertBlock();
846
847 CGF.EmitBlock(RHSBlock);
848
849 Value *RHS = Visit(E->getRHS());
850 Builder.CreateBr(ContBlock);
851 RHSBlock = Builder.GetInsertBlock();
852
853 CGF.EmitBlock(ContBlock);
854
855 // Create a PHI node for the real part.
856 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
857 PN->reserveOperandSpace(2);
858 PN->addIncoming(LHS, LHSBlock);
859 PN->addIncoming(RHS, RHSBlock);
860 return PN;
861}
862
863Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
864 llvm::APSInt CondVal(32);
865 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
866 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
867
868 // Emit the LHS or RHS as appropriate.
869 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
870}
871
872//===----------------------------------------------------------------------===//
873// Entry Point into this File
874//===----------------------------------------------------------------------===//
875
876/// EmitComplexExpr - Emit the computation of the specified expression of
877/// complex type, ignoring the result.
878Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
879 assert(E && !hasAggregateLLVMType(E->getType()) &&
880 "Invalid scalar expression to emit");
881
882 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
883}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000884
885/// EmitScalarConversion - Emit a conversion from the specified type to the
886/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000887Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
888 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000889 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
890 "Invalid scalar expression to emit");
891 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
892}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000893
894/// EmitComplexToScalarConversion - Emit a conversion from the specified
895/// complex type to the specified destination type, where the destination
896/// type is an LLVM scalar type.
897Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
898 QualType SrcTy,
899 QualType DstTy) {
900 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
901 "Invalid complex -> scalar conversion");
902 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
903 DstTy);
904}