blob: cd9ecf477e4f8229fe8f5e96795f90f61befe9d6 [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 Lattner4e05d1e2007-08-26 06:48:56 +000065 /// EmitScalarConversion - Emit a conversion from the specified type to the
66 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000067 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
68
69 /// EmitComplexToScalarConversion - Emit a conversion from the specified
70 /// complex type to the specified destination type, where the destination
71 /// type is an LLVM scalar type.
72 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
73 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000074
Chris Lattner9fba49a2007-08-24 05:35:26 +000075 //===--------------------------------------------------------------------===//
76 // Visitor Methods
77 //===--------------------------------------------------------------------===//
78
79 Value *VisitStmt(Stmt *S) {
80 S->dump();
81 assert(0 && "Stmt can't have complex result type!");
82 return 0;
83 }
84 Value *VisitExpr(Expr *S);
85 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
86
87 // Leaves.
88 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
89 return llvm::ConstantInt::get(E->getValue());
90 }
91 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
92 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
93 }
94 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
95 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
96 }
97 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
98 return llvm::ConstantInt::get(ConvertType(E->getType()),
99 E->typesAreCompatible());
100 }
101 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
102 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
103 }
104
105 // l-values.
106 Value *VisitDeclRefExpr(DeclRefExpr *E) {
107 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
108 return llvm::ConstantInt::get(EC->getInitVal());
109 return EmitLoadOfLValue(E);
110 }
111 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
112 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
113 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
114 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
115 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
116
117 // FIXME: CompoundLiteralExpr
118 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
119 Value *VisitCastExpr(const CastExpr *E) {
120 return EmitCastExpr(E->getSubExpr(), E->getType());
121 }
122 Value *EmitCastExpr(const Expr *E, QualType T);
123
124 Value *VisitCallExpr(const CallExpr *E) {
125 return CGF.EmitCallExpr(E).getVal();
126 }
127
128 // Unary Operators.
129 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
130 Value *VisitUnaryPostDec(const UnaryOperator *E) {
131 return VisitPrePostIncDec(E, false, false);
132 }
133 Value *VisitUnaryPostInc(const UnaryOperator *E) {
134 return VisitPrePostIncDec(E, true, false);
135 }
136 Value *VisitUnaryPreDec(const UnaryOperator *E) {
137 return VisitPrePostIncDec(E, false, true);
138 }
139 Value *VisitUnaryPreInc(const UnaryOperator *E) {
140 return VisitPrePostIncDec(E, true, true);
141 }
142 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
143 return EmitLValue(E->getSubExpr()).getAddress();
144 }
145 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
146 Value *VisitUnaryPlus(const UnaryOperator *E) {
147 return Visit(E->getSubExpr());
148 }
149 Value *VisitUnaryMinus (const UnaryOperator *E);
150 Value *VisitUnaryNot (const UnaryOperator *E);
151 Value *VisitUnaryLNot (const UnaryOperator *E);
152 Value *VisitUnarySizeOf (const UnaryOperator *E) {
153 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
154 }
155 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
156 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
157 }
158 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
159 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000160 Value *VisitUnaryReal (const UnaryOperator *E);
161 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000162 Value *VisitUnaryExtension(const UnaryOperator *E) {
163 return Visit(E->getSubExpr());
164 }
165
166 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000167 Value *EmitMul(const BinOpInfo &Ops) {
168 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
169 }
170 Value *EmitDiv(const BinOpInfo &Ops);
171 Value *EmitRem(const BinOpInfo &Ops);
172 Value *EmitAdd(const BinOpInfo &Ops);
173 Value *EmitSub(const BinOpInfo &Ops);
174 Value *EmitShl(const BinOpInfo &Ops);
175 Value *EmitShr(const BinOpInfo &Ops);
176 Value *EmitAnd(const BinOpInfo &Ops) {
177 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
178 }
179 Value *EmitXor(const BinOpInfo &Ops) {
180 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
181 }
182 Value *EmitOr (const BinOpInfo &Ops) {
183 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
184 }
185
Chris Lattner660e31d2007-08-24 21:00:35 +0000186 BinOpInfo EmitBinOps(const BinaryOperator *E);
187 Value *EmitCompoundAssign(const BinaryOperator *E,
188 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
189
190 // Binary operators and binary compound assignment operators.
191#define HANDLEBINOP(OP) \
192 Value *VisitBin ## OP(const BinaryOperator *E) { \
193 return Emit ## OP(EmitBinOps(E)); \
194 } \
195 Value *VisitBin ## OP ## Assign(const BinaryOperator *E) { \
196 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
197 }
198 HANDLEBINOP(Mul);
199 HANDLEBINOP(Div);
200 HANDLEBINOP(Rem);
201 HANDLEBINOP(Add);
202 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
203 HANDLEBINOP(Shl);
204 HANDLEBINOP(Shr);
205 HANDLEBINOP(And);
206 HANDLEBINOP(Xor);
207 HANDLEBINOP(Or);
208#undef HANDLEBINOP
209 Value *VisitBinSub(const BinaryOperator *E);
210 Value *VisitBinSubAssign(const BinaryOperator *E) {
211 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
212 }
213
Chris Lattner9fba49a2007-08-24 05:35:26 +0000214 // Comparisons.
215 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
216 unsigned SICmpOpc, unsigned FCmpOpc);
217#define VISITCOMP(CODE, UI, SI, FP) \
218 Value *VisitBin##CODE(const BinaryOperator *E) { \
219 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
220 llvm::FCmpInst::FP); }
221 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
222 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
223 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
224 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
225 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
226 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
227#undef VISITCOMP
228
229 Value *VisitBinAssign (const BinaryOperator *E);
230
231 Value *VisitBinLAnd (const BinaryOperator *E);
232 Value *VisitBinLOr (const BinaryOperator *E);
233
234 // FIXME: Compound assignment operators.
235 Value *VisitBinComma (const BinaryOperator *E);
236
237 // Other Operators.
238 Value *VisitConditionalOperator(const ConditionalOperator *CO);
239 Value *VisitChooseExpr(ChooseExpr *CE);
240 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
241 return CGF.EmitObjCStringLiteral(E);
242 }
243};
244} // end anonymous namespace.
245
246//===----------------------------------------------------------------------===//
247// Utilities
248//===----------------------------------------------------------------------===//
249
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000250/// EmitScalarConversion - Emit a conversion from the specified type to the
251/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000252Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
253 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000254 SrcType = SrcType.getCanonicalType();
255 DstType = DstType.getCanonicalType();
256 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000257
258 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000259
260 // Handle conversions to bool first, they are special: comparisons against 0.
261 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstType))
262 if (DestBT->getKind() == BuiltinType::Bool)
263 return CGF.ConvertScalarValueToBool(RValue::get(Src), SrcType);
264
265 const llvm::Type *DstTy = ConvertType(DstType);
266
267 // Ignore conversions like int -> uint.
268 if (Src->getType() == DstTy)
269 return Src;
270
271 // Handle pointer conversions next: pointers can only be converted to/from
272 // other pointers and integers.
273 if (isa<PointerType>(DstType)) {
274 // The source value may be an integer, or a pointer.
275 if (isa<llvm::PointerType>(Src->getType()))
276 return Builder.CreateBitCast(Src, DstTy, "conv");
277 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
278 return Builder.CreateIntToPtr(Src, DstTy, "conv");
279 }
280
281 if (isa<PointerType>(SrcType)) {
282 // Must be an ptr to int cast.
283 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
284 return Builder.CreateIntToPtr(Src, DstTy, "conv");
285 }
286
287 // Finally, we have the arithmetic types: real int/float.
288 if (isa<llvm::IntegerType>(Src->getType())) {
289 bool InputSigned = SrcType->isSignedIntegerType();
290 if (isa<llvm::IntegerType>(DstTy))
291 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
292 else if (InputSigned)
293 return Builder.CreateSIToFP(Src, DstTy, "conv");
294 else
295 return Builder.CreateUIToFP(Src, DstTy, "conv");
296 }
297
298 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
299 if (isa<llvm::IntegerType>(DstTy)) {
300 if (DstType->isSignedIntegerType())
301 return Builder.CreateFPToSI(Src, DstTy, "conv");
302 else
303 return Builder.CreateFPToUI(Src, DstTy, "conv");
304 }
305
306 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
307 if (DstTy->getTypeID() < Src->getType()->getTypeID())
308 return Builder.CreateFPTrunc(Src, DstTy, "conv");
309 else
310 return Builder.CreateFPExt(Src, DstTy, "conv");
311}
312
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000313/// EmitComplexToScalarConversion - Emit a conversion from the specified
314/// complex type to the specified destination type, where the destination
315/// type is an LLVM scalar type.
316Value *ScalarExprEmitter::
317EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
318 QualType SrcTy, QualType DstTy) {
319 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
320 // the imaginary part of the complex value is discarded and the value of the
321 // real part is converted according to the conversion rules for the
322 // corresponding real type.
323 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
324 return EmitScalarConversion(Src.first, SrcTy, DstTy);
325}
326
327
Chris Lattner9fba49a2007-08-24 05:35:26 +0000328//===----------------------------------------------------------------------===//
329// Visitor Methods
330//===----------------------------------------------------------------------===//
331
332Value *ScalarExprEmitter::VisitExpr(Expr *E) {
333 fprintf(stderr, "Unimplemented scalar expr!\n");
334 E->dump();
335 if (E->getType()->isVoidType())
336 return 0;
337 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
338}
339
340Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
341 // Emit subscript expressions in rvalue context's. For most cases, this just
342 // loads the lvalue formed by the subscript expr. However, we have to be
343 // careful, because the base of a vector subscript is occasionally an rvalue,
344 // so we can't get it as an lvalue.
345 if (!E->getBase()->getType()->isVectorType())
346 return EmitLoadOfLValue(E);
347
348 // Handle the vector case. The base must be a vector, the index must be an
349 // integer value.
350 Value *Base = Visit(E->getBase());
351 Value *Idx = Visit(E->getIdx());
352
353 // FIXME: Convert Idx to i32 type.
354 return Builder.CreateExtractElement(Base, Idx, "vecext");
355}
356
357/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
358/// also handle things like function to pointer-to-function decay, and array to
359/// pointer decay.
360Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
361 const Expr *Op = E->getSubExpr();
362
363 // If this is due to array->pointer conversion, emit the array expression as
364 // an l-value.
365 if (Op->getType()->isArrayType()) {
366 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
367 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000368 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000369
370 assert(isa<llvm::PointerType>(V->getType()) &&
371 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
372 ->getElementType()) &&
373 "Doesn't support VLAs yet!");
374 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
375 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
376 }
377
378 return EmitCastExpr(Op, E->getType());
379}
380
381
382// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
383// have to handle a more broad range of conversions than explicit casts, as they
384// handle things like function to ptr-to-function decay etc.
385Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000386 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000387 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000388 Value *Src = Visit(const_cast<Expr*>(E));
389
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000390 // Use EmitScalarConversion to perform the conversion.
391 return EmitScalarConversion(Src, E->getType(), DestTy);
392 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000393
Chris Lattner82e10392007-08-26 07:26:12 +0000394 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000395 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
396 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000397}
398
399//===----------------------------------------------------------------------===//
400// Unary Operators
401//===----------------------------------------------------------------------===//
402
403Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000404 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000405 LValue LV = EmitLValue(E->getSubExpr());
406 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000407 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
408 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000409
410 int AmountVal = isInc ? 1 : -1;
411
412 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000413 if (isa<llvm::PointerType>(InVal->getType())) {
414 // FIXME: This isn't right for VLAs.
415 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
416 NextVal = Builder.CreateGEP(InVal, NextVal);
417 } else {
418 // Add the inc/dec to the real part.
419 if (isa<llvm::IntegerType>(InVal->getType()))
420 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
421 else
422 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
423 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
424 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000425
426 // Store the updated result through the lvalue.
427 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
428 E->getSubExpr()->getType());
429
430 // If this is a postinc, return the value read from memory, otherwise use the
431 // updated value.
432 return isPre ? NextVal : InVal;
433}
434
435
436Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
437 Value *Op = Visit(E->getSubExpr());
438 return Builder.CreateNeg(Op, "neg");
439}
440
441Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
442 Value *Op = Visit(E->getSubExpr());
443 return Builder.CreateNot(Op, "neg");
444}
445
446Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
447 // Compare operand to zero.
448 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
449
450 // Invert value.
451 // TODO: Could dynamically modify easy computations here. For example, if
452 // the operand is an icmp ne, turn into icmp eq.
453 BoolVal = Builder.CreateNot(BoolVal, "lnot");
454
455 // ZExt result to int.
456 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
457}
458
459/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
460/// an integer (RetType).
461Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000462 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000463 /// FIXME: This doesn't handle VLAs yet!
464 std::pair<uint64_t, unsigned> Info =
465 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
466
467 uint64_t Val = isSizeOf ? Info.first : Info.second;
468 Val /= 8; // Return size in bytes, not bits.
469
470 assert(RetType->isIntegerType() && "Result type must be an integer!");
471
472 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
473 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
474}
475
Chris Lattner01211af2007-08-24 21:20:17 +0000476Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
477 Expr *Op = E->getSubExpr();
478 if (Op->getType()->isComplexType())
479 return CGF.EmitComplexExpr(Op).first;
480 return Visit(Op);
481}
482Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
483 Expr *Op = E->getSubExpr();
484 if (Op->getType()->isComplexType())
485 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000486
487 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
488 // effects are evaluated.
489 CGF.EmitScalarExpr(Op);
490 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000491}
492
493
Chris Lattner9fba49a2007-08-24 05:35:26 +0000494//===----------------------------------------------------------------------===//
495// Binary Operators
496//===----------------------------------------------------------------------===//
497
498BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
499 BinOpInfo Result;
500 Result.LHS = Visit(E->getLHS());
501 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000502 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000503 Result.E = E;
504 return Result;
505}
506
Chris Lattner660e31d2007-08-24 21:00:35 +0000507Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
508 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
509 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
510
511 BinOpInfo OpInfo;
512
513 // Load the LHS and RHS operands.
514 LValue LHSLV = EmitLValue(E->getLHS());
515 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
516
517 // FIXME: It is possible for the RHS to be complex.
518 OpInfo.RHS = Visit(E->getRHS());
519
520 // Convert the LHS/RHS values to the computation type.
521 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
522 QualType ComputeType = CAO->getComputationType();
523
524 // FIXME: it's possible for the computation type to be complex if the RHS
525 // is complex. Handle this!
Chris Lattnerb1497062007-08-26 07:08:39 +0000526 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000527
528 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000529 if (E->getOpcode() != BinaryOperator::SubAssign ||
530 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000531 // FIXME: the computation type may be complex.
532 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000533 }
534 OpInfo.Ty = ComputeType;
535 OpInfo.E = E;
536
537 // Expand the binary operator.
538 Value *Result = (this->*Func)(OpInfo);
539
540 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000541 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000542
543 // Store the result value into the LHS lvalue.
544 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
545
546 return Result;
547}
548
549
Chris Lattner9fba49a2007-08-24 05:35:26 +0000550Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
551 if (Ops.LHS->getType()->isFloatingPoint())
552 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000553 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000554 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
555 else
556 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
557}
558
559Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
560 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000561 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000562 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
563 else
564 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
565}
566
567
568Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000569 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000570 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000571
572 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000573 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
574 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
575 // int + pointer
576 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
577}
578
579Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
580 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
581 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
582
Chris Lattner660e31d2007-08-24 21:00:35 +0000583 // pointer - int
584 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
585 "ptr-ptr shouldn't get here");
586 // FIXME: The pointer could point to a VLA.
587 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
588 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
589}
590
591Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
592 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
593 // the compound assignment case it is invalid, so just handle it here.
594 if (!E->getRHS()->getType()->isPointerType())
595 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000596
597 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000598 Value *LHS = Visit(E->getLHS());
599 Value *RHS = Visit(E->getRHS());
600
601 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
602 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
603 "Can't subtract different pointer types");
604
Chris Lattner9fba49a2007-08-24 05:35:26 +0000605 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000606 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
607 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000608
609 const llvm::Type *ResultType = ConvertType(E->getType());
610 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
611 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
612 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000613
614 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
615 // remainder. As such, we handle common power-of-two cases here to generate
616 // better code.
617 if (llvm::isPowerOf2_64(ElementSize)) {
618 Value *ShAmt =
619 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
620 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
621 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000622
Chris Lattner9fba49a2007-08-24 05:35:26 +0000623 // Otherwise, do a full sdiv.
624 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
625 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
626}
627
Chris Lattner660e31d2007-08-24 21:00:35 +0000628
Chris Lattner9fba49a2007-08-24 05:35:26 +0000629Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
630 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
631 // RHS to the same size as the LHS.
632 Value *RHS = Ops.RHS;
633 if (Ops.LHS->getType() != RHS->getType())
634 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
635
636 return Builder.CreateShl(Ops.LHS, RHS, "shl");
637}
638
639Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
640 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
641 // RHS to the same size as the LHS.
642 Value *RHS = Ops.RHS;
643 if (Ops.LHS->getType() != RHS->getType())
644 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
645
Chris Lattner660e31d2007-08-24 21:00:35 +0000646 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000647 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
648 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
649}
650
651Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
652 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000653 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000654 QualType LHSTy = E->getLHS()->getType();
655 if (!LHSTy->isComplexType()) {
656 Value *LHS = Visit(E->getLHS());
657 Value *RHS = Visit(E->getRHS());
658
659 if (LHS->getType()->isFloatingPoint()) {
660 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
661 LHS, RHS, "cmp");
662 } else if (LHSTy->isUnsignedIntegerType()) {
663 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
664 LHS, RHS, "cmp");
665 } else {
666 // Signed integers and pointers.
667 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
668 LHS, RHS, "cmp");
669 }
670 } else {
671 // Complex Comparison: can only be an equality comparison.
672 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
673 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
674
675 QualType CETy =
676 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
677
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000678 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000679 if (CETy->isRealFloatingType()) {
680 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
681 LHS.first, RHS.first, "cmp.r");
682 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
683 LHS.second, RHS.second, "cmp.i");
684 } else {
685 // Complex comparisons can only be equality comparisons. As such, signed
686 // and unsigned opcodes are the same.
687 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
688 LHS.first, RHS.first, "cmp.r");
689 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
690 LHS.second, RHS.second, "cmp.i");
691 }
692
693 if (E->getOpcode() == BinaryOperator::EQ) {
694 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
695 } else {
696 assert(E->getOpcode() == BinaryOperator::NE &&
697 "Complex comparison other than == or != ?");
698 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
699 }
700 }
701
702 // ZExt result to int.
703 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
704}
705
706Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
707 LValue LHS = EmitLValue(E->getLHS());
708 Value *RHS = Visit(E->getRHS());
709
710 // Store the value into the LHS.
711 // FIXME: Volatility!
712 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
713
714 // Return the RHS.
715 return RHS;
716}
717
718Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
719 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
720
721 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
722 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
723
724 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
725 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
726
727 CGF.EmitBlock(RHSBlock);
728 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
729
730 // Reaquire the RHS block, as there may be subblocks inserted.
731 RHSBlock = Builder.GetInsertBlock();
732 CGF.EmitBlock(ContBlock);
733
734 // Create a PHI node. If we just evaluted the LHS condition, the result is
735 // false. If we evaluated both, the result is the RHS condition.
736 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
737 PN->reserveOperandSpace(2);
738 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
739 PN->addIncoming(RHSCond, RHSBlock);
740
741 // ZExt result to int.
742 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
743}
744
745Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
746 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
747
748 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
749 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
750
751 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
752 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
753
754 CGF.EmitBlock(RHSBlock);
755 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
756
757 // Reaquire the RHS block, as there may be subblocks inserted.
758 RHSBlock = Builder.GetInsertBlock();
759 CGF.EmitBlock(ContBlock);
760
761 // Create a PHI node. If we just evaluted the LHS condition, the result is
762 // true. If we evaluated both, the result is the RHS condition.
763 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
764 PN->reserveOperandSpace(2);
765 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
766 PN->addIncoming(RHSCond, RHSBlock);
767
768 // ZExt result to int.
769 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
770}
771
772Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
773 CGF.EmitStmt(E->getLHS());
774 return Visit(E->getRHS());
775}
776
777//===----------------------------------------------------------------------===//
778// Other Operators
779//===----------------------------------------------------------------------===//
780
781Value *ScalarExprEmitter::
782VisitConditionalOperator(const ConditionalOperator *E) {
783 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
784 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
785 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
786
787 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
788 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
789
790 CGF.EmitBlock(LHSBlock);
791
792 // Handle the GNU extension for missing LHS.
793 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
794 Builder.CreateBr(ContBlock);
795 LHSBlock = Builder.GetInsertBlock();
796
797 CGF.EmitBlock(RHSBlock);
798
799 Value *RHS = Visit(E->getRHS());
800 Builder.CreateBr(ContBlock);
801 RHSBlock = Builder.GetInsertBlock();
802
803 CGF.EmitBlock(ContBlock);
804
805 // Create a PHI node for the real part.
806 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
807 PN->reserveOperandSpace(2);
808 PN->addIncoming(LHS, LHSBlock);
809 PN->addIncoming(RHS, RHSBlock);
810 return PN;
811}
812
813Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
814 llvm::APSInt CondVal(32);
815 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
816 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
817
818 // Emit the LHS or RHS as appropriate.
819 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
820}
821
822//===----------------------------------------------------------------------===//
823// Entry Point into this File
824//===----------------------------------------------------------------------===//
825
826/// EmitComplexExpr - Emit the computation of the specified expression of
827/// complex type, ignoring the result.
828Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
829 assert(E && !hasAggregateLLVMType(E->getType()) &&
830 "Invalid scalar expression to emit");
831
832 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
833}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000834
835/// EmitScalarConversion - Emit a conversion from the specified type to the
836/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000837Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
838 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000839 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
840 "Invalid scalar expression to emit");
841 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
842}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000843
844/// EmitComplexToScalarConversion - Emit a conversion from the specified
845/// complex type to the specified destination type, where the destination
846/// type is an LLVM scalar type.
847Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
848 QualType SrcTy,
849 QualType DstTy) {
850 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
851 "Invalid complex -> scalar conversion");
852 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
853 DstTy);
854}