blob: 70a44625f9cb81b735e6d8e7413a3f09e00289ed [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
66 /// boolean (i1) truth value. This is equivalent to "Val == 0".
67 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);
191 Value *EmitCompoundAssign(const BinaryOperator *E,
192 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
193
194 // Binary operators and binary compound assignment operators.
195#define HANDLEBINOP(OP) \
196 Value *VisitBin ## OP(const BinaryOperator *E) { \
197 return Emit ## OP(EmitBinOps(E)); \
198 } \
199 Value *VisitBin ## OP ## Assign(const BinaryOperator *E) { \
200 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
201 }
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);
214 Value *VisitBinSubAssign(const BinaryOperator *E) {
215 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);
237
238 // FIXME: Compound assignment operators.
239 Value *VisitBinComma (const BinaryOperator *E);
240
241 // Other Operators.
242 Value *VisitConditionalOperator(const ConditionalOperator *CO);
243 Value *VisitChooseExpr(ChooseExpr *CE);
244 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
245 return CGF.EmitObjCStringLiteral(E);
246 }
247};
248} // end anonymous namespace.
249
250//===----------------------------------------------------------------------===//
251// Utilities
252//===----------------------------------------------------------------------===//
253
Chris Lattnerd8d44222007-08-26 16:42:57 +0000254/// EmitConversionToBool - Convert the specified expression value to a
255/// boolean (i1) truth value. This is equivalent to "Val == 0".
256Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
257 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
258
259 if (SrcType->isRealFloatingType()) {
260 // Compare against 0.0 for fp scalars.
261 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
262 // FIXME: llvm-gcc produces a une comparison: validate this is right.
263 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
264 }
265
266 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
267 "Unknown scalar type to convert");
268
269 // Because of the type rules of C, we often end up computing a logical value,
270 // then zero extending it to int, then wanting it as a logical value again.
271 // Optimize this common case.
272 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
273 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
274 Value *Result = ZI->getOperand(0);
275 ZI->eraseFromParent();
276 return Result;
277 }
278 }
279
280 // Compare against an integer or pointer null.
281 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
282 return Builder.CreateICmpNE(Src, Zero, "tobool");
283}
284
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000285/// EmitScalarConversion - Emit a conversion from the specified type to the
286/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000287Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
288 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000289 SrcType = SrcType.getCanonicalType();
290 DstType = DstType.getCanonicalType();
291 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000292
293 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000294
295 // Handle conversions to bool first, they are special: comparisons against 0.
296 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstType))
297 if (DestBT->getKind() == BuiltinType::Bool)
Chris Lattnerd8d44222007-08-26 16:42:57 +0000298 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000299
300 const llvm::Type *DstTy = ConvertType(DstType);
301
302 // Ignore conversions like int -> uint.
303 if (Src->getType() == DstTy)
304 return Src;
305
306 // Handle pointer conversions next: pointers can only be converted to/from
307 // other pointers and integers.
308 if (isa<PointerType>(DstType)) {
309 // The source value may be an integer, or a pointer.
310 if (isa<llvm::PointerType>(Src->getType()))
311 return Builder.CreateBitCast(Src, DstTy, "conv");
312 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
313 return Builder.CreateIntToPtr(Src, DstTy, "conv");
314 }
315
316 if (isa<PointerType>(SrcType)) {
317 // Must be an ptr to int cast.
318 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
319 return Builder.CreateIntToPtr(Src, DstTy, "conv");
320 }
321
322 // Finally, we have the arithmetic types: real int/float.
323 if (isa<llvm::IntegerType>(Src->getType())) {
324 bool InputSigned = SrcType->isSignedIntegerType();
325 if (isa<llvm::IntegerType>(DstTy))
326 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
327 else if (InputSigned)
328 return Builder.CreateSIToFP(Src, DstTy, "conv");
329 else
330 return Builder.CreateUIToFP(Src, DstTy, "conv");
331 }
332
333 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
334 if (isa<llvm::IntegerType>(DstTy)) {
335 if (DstType->isSignedIntegerType())
336 return Builder.CreateFPToSI(Src, DstTy, "conv");
337 else
338 return Builder.CreateFPToUI(Src, DstTy, "conv");
339 }
340
341 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
342 if (DstTy->getTypeID() < Src->getType()->getTypeID())
343 return Builder.CreateFPTrunc(Src, DstTy, "conv");
344 else
345 return Builder.CreateFPExt(Src, DstTy, "conv");
346}
347
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000348/// EmitComplexToScalarConversion - Emit a conversion from the specified
349/// complex type to the specified destination type, where the destination
350/// type is an LLVM scalar type.
351Value *ScalarExprEmitter::
352EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
353 QualType SrcTy, QualType DstTy) {
354 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
355 // the imaginary part of the complex value is discarded and the value of the
356 // real part is converted according to the conversion rules for the
357 // corresponding real type.
358 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
359 return EmitScalarConversion(Src.first, SrcTy, DstTy);
360}
361
362
Chris Lattner9fba49a2007-08-24 05:35:26 +0000363//===----------------------------------------------------------------------===//
364// Visitor Methods
365//===----------------------------------------------------------------------===//
366
367Value *ScalarExprEmitter::VisitExpr(Expr *E) {
368 fprintf(stderr, "Unimplemented scalar expr!\n");
369 E->dump();
370 if (E->getType()->isVoidType())
371 return 0;
372 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
373}
374
375Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
376 // Emit subscript expressions in rvalue context's. For most cases, this just
377 // loads the lvalue formed by the subscript expr. However, we have to be
378 // careful, because the base of a vector subscript is occasionally an rvalue,
379 // so we can't get it as an lvalue.
380 if (!E->getBase()->getType()->isVectorType())
381 return EmitLoadOfLValue(E);
382
383 // Handle the vector case. The base must be a vector, the index must be an
384 // integer value.
385 Value *Base = Visit(E->getBase());
386 Value *Idx = Visit(E->getIdx());
387
388 // FIXME: Convert Idx to i32 type.
389 return Builder.CreateExtractElement(Base, Idx, "vecext");
390}
391
392/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
393/// also handle things like function to pointer-to-function decay, and array to
394/// pointer decay.
395Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
396 const Expr *Op = E->getSubExpr();
397
398 // If this is due to array->pointer conversion, emit the array expression as
399 // an l-value.
400 if (Op->getType()->isArrayType()) {
401 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
402 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000403 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000404
405 assert(isa<llvm::PointerType>(V->getType()) &&
406 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
407 ->getElementType()) &&
408 "Doesn't support VLAs yet!");
409 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
410 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
411 }
412
413 return EmitCastExpr(Op, E->getType());
414}
415
416
417// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
418// have to handle a more broad range of conversions than explicit casts, as they
419// handle things like function to ptr-to-function decay etc.
420Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000421 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000422 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000423 Value *Src = Visit(const_cast<Expr*>(E));
424
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000425 // Use EmitScalarConversion to perform the conversion.
426 return EmitScalarConversion(Src, E->getType(), DestTy);
427 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000428
Chris Lattner82e10392007-08-26 07:26:12 +0000429 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000430 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
431 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000432}
433
434//===----------------------------------------------------------------------===//
435// Unary Operators
436//===----------------------------------------------------------------------===//
437
438Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000439 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000440 LValue LV = EmitLValue(E->getSubExpr());
441 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000442 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
443 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000444
445 int AmountVal = isInc ? 1 : -1;
446
447 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000448 if (isa<llvm::PointerType>(InVal->getType())) {
449 // FIXME: This isn't right for VLAs.
450 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
451 NextVal = Builder.CreateGEP(InVal, NextVal);
452 } else {
453 // Add the inc/dec to the real part.
454 if (isa<llvm::IntegerType>(InVal->getType()))
455 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
456 else
457 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
458 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
459 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000460
461 // Store the updated result through the lvalue.
462 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
463 E->getSubExpr()->getType());
464
465 // If this is a postinc, return the value read from memory, otherwise use the
466 // updated value.
467 return isPre ? NextVal : InVal;
468}
469
470
471Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
472 Value *Op = Visit(E->getSubExpr());
473 return Builder.CreateNeg(Op, "neg");
474}
475
476Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
477 Value *Op = Visit(E->getSubExpr());
478 return Builder.CreateNot(Op, "neg");
479}
480
481Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
482 // Compare operand to zero.
483 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
484
485 // Invert value.
486 // TODO: Could dynamically modify easy computations here. For example, if
487 // the operand is an icmp ne, turn into icmp eq.
488 BoolVal = Builder.CreateNot(BoolVal, "lnot");
489
490 // ZExt result to int.
491 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
492}
493
494/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
495/// an integer (RetType).
496Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000497 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000498 /// FIXME: This doesn't handle VLAs yet!
499 std::pair<uint64_t, unsigned> Info =
500 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
501
502 uint64_t Val = isSizeOf ? Info.first : Info.second;
503 Val /= 8; // Return size in bytes, not bits.
504
505 assert(RetType->isIntegerType() && "Result type must be an integer!");
506
507 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
508 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
509}
510
Chris Lattner01211af2007-08-24 21:20:17 +0000511Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
512 Expr *Op = E->getSubExpr();
513 if (Op->getType()->isComplexType())
514 return CGF.EmitComplexExpr(Op).first;
515 return Visit(Op);
516}
517Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
518 Expr *Op = E->getSubExpr();
519 if (Op->getType()->isComplexType())
520 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000521
522 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
523 // effects are evaluated.
524 CGF.EmitScalarExpr(Op);
525 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000526}
527
528
Chris Lattner9fba49a2007-08-24 05:35:26 +0000529//===----------------------------------------------------------------------===//
530// Binary Operators
531//===----------------------------------------------------------------------===//
532
533BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
534 BinOpInfo Result;
535 Result.LHS = Visit(E->getLHS());
536 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000537 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000538 Result.E = E;
539 return Result;
540}
541
Chris Lattner660e31d2007-08-24 21:00:35 +0000542Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
543 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
544 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
545
546 BinOpInfo OpInfo;
547
548 // Load the LHS and RHS operands.
549 LValue LHSLV = EmitLValue(E->getLHS());
550 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
551
552 // FIXME: It is possible for the RHS to be complex.
553 OpInfo.RHS = Visit(E->getRHS());
554
555 // Convert the LHS/RHS values to the computation type.
556 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
557 QualType ComputeType = CAO->getComputationType();
558
559 // FIXME: it's possible for the computation type to be complex if the RHS
560 // is complex. Handle this!
Chris Lattnerb1497062007-08-26 07:08:39 +0000561 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000562
563 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000564 if (E->getOpcode() != BinaryOperator::SubAssign ||
565 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000566 // FIXME: the computation type may be complex.
567 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000568 }
569 OpInfo.Ty = ComputeType;
570 OpInfo.E = E;
571
572 // Expand the binary operator.
573 Value *Result = (this->*Func)(OpInfo);
574
575 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000576 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000577
578 // Store the result value into the LHS lvalue.
579 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
580
581 return Result;
582}
583
584
Chris Lattner9fba49a2007-08-24 05:35:26 +0000585Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
586 if (Ops.LHS->getType()->isFloatingPoint())
587 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000588 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000589 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
590 else
591 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
592}
593
594Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
595 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000596 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000597 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
598 else
599 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
600}
601
602
603Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000604 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000605 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000606
607 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000608 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
609 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
610 // int + pointer
611 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
612}
613
614Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
615 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
616 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
617
Chris Lattner660e31d2007-08-24 21:00:35 +0000618 // pointer - int
619 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
620 "ptr-ptr shouldn't get here");
621 // FIXME: The pointer could point to a VLA.
622 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
623 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
624}
625
626Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
627 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
628 // the compound assignment case it is invalid, so just handle it here.
629 if (!E->getRHS()->getType()->isPointerType())
630 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000631
632 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000633 Value *LHS = Visit(E->getLHS());
634 Value *RHS = Visit(E->getRHS());
635
636 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
637 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
638 "Can't subtract different pointer types");
639
Chris Lattner9fba49a2007-08-24 05:35:26 +0000640 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000641 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
642 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000643
644 const llvm::Type *ResultType = ConvertType(E->getType());
645 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
646 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
647 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000648
649 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
650 // remainder. As such, we handle common power-of-two cases here to generate
651 // better code.
652 if (llvm::isPowerOf2_64(ElementSize)) {
653 Value *ShAmt =
654 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
655 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
656 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000657
Chris Lattner9fba49a2007-08-24 05:35:26 +0000658 // Otherwise, do a full sdiv.
659 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
660 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
661}
662
Chris Lattner660e31d2007-08-24 21:00:35 +0000663
Chris Lattner9fba49a2007-08-24 05:35:26 +0000664Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
665 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
666 // RHS to the same size as the LHS.
667 Value *RHS = Ops.RHS;
668 if (Ops.LHS->getType() != RHS->getType())
669 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
670
671 return Builder.CreateShl(Ops.LHS, RHS, "shl");
672}
673
674Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
675 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
676 // RHS to the same size as the LHS.
677 Value *RHS = Ops.RHS;
678 if (Ops.LHS->getType() != RHS->getType())
679 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
680
Chris Lattner660e31d2007-08-24 21:00:35 +0000681 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000682 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
683 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
684}
685
686Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
687 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000688 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000689 QualType LHSTy = E->getLHS()->getType();
690 if (!LHSTy->isComplexType()) {
691 Value *LHS = Visit(E->getLHS());
692 Value *RHS = Visit(E->getRHS());
693
694 if (LHS->getType()->isFloatingPoint()) {
695 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
696 LHS, RHS, "cmp");
697 } else if (LHSTy->isUnsignedIntegerType()) {
698 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
699 LHS, RHS, "cmp");
700 } else {
701 // Signed integers and pointers.
702 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
703 LHS, RHS, "cmp");
704 }
705 } else {
706 // Complex Comparison: can only be an equality comparison.
707 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
708 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
709
710 QualType CETy =
711 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
712
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000713 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000714 if (CETy->isRealFloatingType()) {
715 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
716 LHS.first, RHS.first, "cmp.r");
717 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
718 LHS.second, RHS.second, "cmp.i");
719 } else {
720 // Complex comparisons can only be equality comparisons. As such, signed
721 // and unsigned opcodes are the same.
722 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
723 LHS.first, RHS.first, "cmp.r");
724 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
725 LHS.second, RHS.second, "cmp.i");
726 }
727
728 if (E->getOpcode() == BinaryOperator::EQ) {
729 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
730 } else {
731 assert(E->getOpcode() == BinaryOperator::NE &&
732 "Complex comparison other than == or != ?");
733 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
734 }
735 }
736
737 // ZExt result to int.
738 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
739}
740
741Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
742 LValue LHS = EmitLValue(E->getLHS());
743 Value *RHS = Visit(E->getRHS());
744
745 // Store the value into the LHS.
746 // FIXME: Volatility!
747 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
748
749 // Return the RHS.
750 return RHS;
751}
752
753Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
754 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
755
756 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
757 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
758
759 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
760 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
761
762 CGF.EmitBlock(RHSBlock);
763 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
764
765 // Reaquire the RHS block, as there may be subblocks inserted.
766 RHSBlock = Builder.GetInsertBlock();
767 CGF.EmitBlock(ContBlock);
768
769 // Create a PHI node. If we just evaluted the LHS condition, the result is
770 // false. If we evaluated both, the result is the RHS condition.
771 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
772 PN->reserveOperandSpace(2);
773 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
774 PN->addIncoming(RHSCond, RHSBlock);
775
776 // ZExt result to int.
777 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
778}
779
780Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
781 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
782
783 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
784 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
785
786 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
787 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
788
789 CGF.EmitBlock(RHSBlock);
790 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
791
792 // Reaquire the RHS block, as there may be subblocks inserted.
793 RHSBlock = Builder.GetInsertBlock();
794 CGF.EmitBlock(ContBlock);
795
796 // Create a PHI node. If we just evaluted the LHS condition, the result is
797 // true. If we evaluated both, the result is the RHS condition.
798 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
799 PN->reserveOperandSpace(2);
800 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
801 PN->addIncoming(RHSCond, RHSBlock);
802
803 // ZExt result to int.
804 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
805}
806
807Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
808 CGF.EmitStmt(E->getLHS());
809 return Visit(E->getRHS());
810}
811
812//===----------------------------------------------------------------------===//
813// Other Operators
814//===----------------------------------------------------------------------===//
815
816Value *ScalarExprEmitter::
817VisitConditionalOperator(const ConditionalOperator *E) {
818 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
819 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
820 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
821
822 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
823 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
824
825 CGF.EmitBlock(LHSBlock);
826
827 // Handle the GNU extension for missing LHS.
828 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
829 Builder.CreateBr(ContBlock);
830 LHSBlock = Builder.GetInsertBlock();
831
832 CGF.EmitBlock(RHSBlock);
833
834 Value *RHS = Visit(E->getRHS());
835 Builder.CreateBr(ContBlock);
836 RHSBlock = Builder.GetInsertBlock();
837
838 CGF.EmitBlock(ContBlock);
839
840 // Create a PHI node for the real part.
841 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
842 PN->reserveOperandSpace(2);
843 PN->addIncoming(LHS, LHSBlock);
844 PN->addIncoming(RHS, RHSBlock);
845 return PN;
846}
847
848Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
849 llvm::APSInt CondVal(32);
850 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
851 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
852
853 // Emit the LHS or RHS as appropriate.
854 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
855}
856
857//===----------------------------------------------------------------------===//
858// Entry Point into this File
859//===----------------------------------------------------------------------===//
860
861/// EmitComplexExpr - Emit the computation of the specified expression of
862/// complex type, ignoring the result.
863Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
864 assert(E && !hasAggregateLLVMType(E->getType()) &&
865 "Invalid scalar expression to emit");
866
867 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
868}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000869
870/// EmitScalarConversion - Emit a conversion from the specified type to the
871/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000872Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
873 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000874 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
875 "Invalid scalar expression to emit");
876 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
877}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000878
879/// EmitComplexToScalarConversion - Emit a conversion from the specified
880/// complex type to the specified destination type, where the destination
881/// type is an LLVM scalar type.
882Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
883 QualType SrcTy,
884 QualType DstTy) {
885 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
886 "Invalid complex -> scalar conversion");
887 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
888 DstTy);
889}