blob: 91e76aaf84f682871062ecd7972b10cf061a27e9 [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
65 //===--------------------------------------------------------------------===//
66 // Visitor Methods
67 //===--------------------------------------------------------------------===//
68
69 Value *VisitStmt(Stmt *S) {
70 S->dump();
71 assert(0 && "Stmt can't have complex result type!");
72 return 0;
73 }
74 Value *VisitExpr(Expr *S);
75 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
76
77 // Leaves.
78 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
79 return llvm::ConstantInt::get(E->getValue());
80 }
81 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
82 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
83 }
84 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
85 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
86 }
87 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
88 return llvm::ConstantInt::get(ConvertType(E->getType()),
89 E->typesAreCompatible());
90 }
91 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
92 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
93 }
94
95 // l-values.
96 Value *VisitDeclRefExpr(DeclRefExpr *E) {
97 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
98 return llvm::ConstantInt::get(EC->getInitVal());
99 return EmitLoadOfLValue(E);
100 }
101 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
102 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
103 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
104 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
105 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
106
107 // FIXME: CompoundLiteralExpr
108 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
109 Value *VisitCastExpr(const CastExpr *E) {
110 return EmitCastExpr(E->getSubExpr(), E->getType());
111 }
112 Value *EmitCastExpr(const Expr *E, QualType T);
113
114 Value *VisitCallExpr(const CallExpr *E) {
115 return CGF.EmitCallExpr(E).getVal();
116 }
117
118 // Unary Operators.
119 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
120 Value *VisitUnaryPostDec(const UnaryOperator *E) {
121 return VisitPrePostIncDec(E, false, false);
122 }
123 Value *VisitUnaryPostInc(const UnaryOperator *E) {
124 return VisitPrePostIncDec(E, true, false);
125 }
126 Value *VisitUnaryPreDec(const UnaryOperator *E) {
127 return VisitPrePostIncDec(E, false, true);
128 }
129 Value *VisitUnaryPreInc(const UnaryOperator *E) {
130 return VisitPrePostIncDec(E, true, true);
131 }
132 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
133 return EmitLValue(E->getSubExpr()).getAddress();
134 }
135 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
136 Value *VisitUnaryPlus(const UnaryOperator *E) {
137 return Visit(E->getSubExpr());
138 }
139 Value *VisitUnaryMinus (const UnaryOperator *E);
140 Value *VisitUnaryNot (const UnaryOperator *E);
141 Value *VisitUnaryLNot (const UnaryOperator *E);
142 Value *VisitUnarySizeOf (const UnaryOperator *E) {
143 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
144 }
145 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
146 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
147 }
148 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
149 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000150 Value *VisitUnaryReal (const UnaryOperator *E);
151 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000152 Value *VisitUnaryExtension(const UnaryOperator *E) {
153 return Visit(E->getSubExpr());
154 }
155
156 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000157 Value *EmitMul(const BinOpInfo &Ops) {
158 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
159 }
160 Value *EmitDiv(const BinOpInfo &Ops);
161 Value *EmitRem(const BinOpInfo &Ops);
162 Value *EmitAdd(const BinOpInfo &Ops);
163 Value *EmitSub(const BinOpInfo &Ops);
164 Value *EmitShl(const BinOpInfo &Ops);
165 Value *EmitShr(const BinOpInfo &Ops);
166 Value *EmitAnd(const BinOpInfo &Ops) {
167 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
168 }
169 Value *EmitXor(const BinOpInfo &Ops) {
170 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
171 }
172 Value *EmitOr (const BinOpInfo &Ops) {
173 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
174 }
175
Chris Lattner660e31d2007-08-24 21:00:35 +0000176 BinOpInfo EmitBinOps(const BinaryOperator *E);
177 Value *EmitCompoundAssign(const BinaryOperator *E,
178 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
179
180 // Binary operators and binary compound assignment operators.
181#define HANDLEBINOP(OP) \
182 Value *VisitBin ## OP(const BinaryOperator *E) { \
183 return Emit ## OP(EmitBinOps(E)); \
184 } \
185 Value *VisitBin ## OP ## Assign(const BinaryOperator *E) { \
186 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
187 }
188 HANDLEBINOP(Mul);
189 HANDLEBINOP(Div);
190 HANDLEBINOP(Rem);
191 HANDLEBINOP(Add);
192 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
193 HANDLEBINOP(Shl);
194 HANDLEBINOP(Shr);
195 HANDLEBINOP(And);
196 HANDLEBINOP(Xor);
197 HANDLEBINOP(Or);
198#undef HANDLEBINOP
199 Value *VisitBinSub(const BinaryOperator *E);
200 Value *VisitBinSubAssign(const BinaryOperator *E) {
201 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
202 }
203
Chris Lattner9fba49a2007-08-24 05:35:26 +0000204 // Comparisons.
205 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
206 unsigned SICmpOpc, unsigned FCmpOpc);
207#define VISITCOMP(CODE, UI, SI, FP) \
208 Value *VisitBin##CODE(const BinaryOperator *E) { \
209 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
210 llvm::FCmpInst::FP); }
211 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
212 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
213 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
214 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
215 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
216 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
217#undef VISITCOMP
218
219 Value *VisitBinAssign (const BinaryOperator *E);
220
221 Value *VisitBinLAnd (const BinaryOperator *E);
222 Value *VisitBinLOr (const BinaryOperator *E);
223
224 // FIXME: Compound assignment operators.
225 Value *VisitBinComma (const BinaryOperator *E);
226
227 // Other Operators.
228 Value *VisitConditionalOperator(const ConditionalOperator *CO);
229 Value *VisitChooseExpr(ChooseExpr *CE);
230 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
231 return CGF.EmitObjCStringLiteral(E);
232 }
233};
234} // end anonymous namespace.
235
236//===----------------------------------------------------------------------===//
237// Utilities
238//===----------------------------------------------------------------------===//
239
240//===----------------------------------------------------------------------===//
241// Visitor Methods
242//===----------------------------------------------------------------------===//
243
244Value *ScalarExprEmitter::VisitExpr(Expr *E) {
245 fprintf(stderr, "Unimplemented scalar expr!\n");
246 E->dump();
247 if (E->getType()->isVoidType())
248 return 0;
249 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
250}
251
252Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
253 // Emit subscript expressions in rvalue context's. For most cases, this just
254 // loads the lvalue formed by the subscript expr. However, we have to be
255 // careful, because the base of a vector subscript is occasionally an rvalue,
256 // so we can't get it as an lvalue.
257 if (!E->getBase()->getType()->isVectorType())
258 return EmitLoadOfLValue(E);
259
260 // Handle the vector case. The base must be a vector, the index must be an
261 // integer value.
262 Value *Base = Visit(E->getBase());
263 Value *Idx = Visit(E->getIdx());
264
265 // FIXME: Convert Idx to i32 type.
266 return Builder.CreateExtractElement(Base, Idx, "vecext");
267}
268
269/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
270/// also handle things like function to pointer-to-function decay, and array to
271/// pointer decay.
272Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
273 const Expr *Op = E->getSubExpr();
274
275 // If this is due to array->pointer conversion, emit the array expression as
276 // an l-value.
277 if (Op->getType()->isArrayType()) {
278 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
279 // will not true when we add support for VLAs.
280 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
281
282 assert(isa<llvm::PointerType>(V->getType()) &&
283 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
284 ->getElementType()) &&
285 "Doesn't support VLAs yet!");
286 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
287 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
288 }
289
290 return EmitCastExpr(Op, E->getType());
291}
292
293
294// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
295// have to handle a more broad range of conversions than explicit casts, as they
296// handle things like function to ptr-to-function decay etc.
297Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
298 RValue Src = CGF.EmitAnyExpr(E);
299
300 // If the destination is void, just evaluate the source.
301 if (DestTy->isVoidType())
302 return 0;
303
304 // FIXME: Refactor EmitConversion to not return an RValue. Sink it into this
305 // method.
306 return CGF.EmitConversion(Src, E->getType(), DestTy).getVal();
307}
308
309//===----------------------------------------------------------------------===//
310// Unary Operators
311//===----------------------------------------------------------------------===//
312
313Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000314 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000315 LValue LV = EmitLValue(E->getSubExpr());
316 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000317 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
318 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000319
320 int AmountVal = isInc ? 1 : -1;
321
322 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000323 if (isa<llvm::PointerType>(InVal->getType())) {
324 // FIXME: This isn't right for VLAs.
325 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
326 NextVal = Builder.CreateGEP(InVal, NextVal);
327 } else {
328 // Add the inc/dec to the real part.
329 if (isa<llvm::IntegerType>(InVal->getType()))
330 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
331 else
332 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
333 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
334 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000335
336 // Store the updated result through the lvalue.
337 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
338 E->getSubExpr()->getType());
339
340 // If this is a postinc, return the value read from memory, otherwise use the
341 // updated value.
342 return isPre ? NextVal : InVal;
343}
344
345
346Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
347 Value *Op = Visit(E->getSubExpr());
348 return Builder.CreateNeg(Op, "neg");
349}
350
351Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
352 Value *Op = Visit(E->getSubExpr());
353 return Builder.CreateNot(Op, "neg");
354}
355
356Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
357 // Compare operand to zero.
358 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
359
360 // Invert value.
361 // TODO: Could dynamically modify easy computations here. For example, if
362 // the operand is an icmp ne, turn into icmp eq.
363 BoolVal = Builder.CreateNot(BoolVal, "lnot");
364
365 // ZExt result to int.
366 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
367}
368
369/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
370/// an integer (RetType).
371Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000372 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000373 /// FIXME: This doesn't handle VLAs yet!
374 std::pair<uint64_t, unsigned> Info =
375 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
376
377 uint64_t Val = isSizeOf ? Info.first : Info.second;
378 Val /= 8; // Return size in bytes, not bits.
379
380 assert(RetType->isIntegerType() && "Result type must be an integer!");
381
382 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
383 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
384}
385
Chris Lattner01211af2007-08-24 21:20:17 +0000386Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
387 Expr *Op = E->getSubExpr();
388 if (Op->getType()->isComplexType())
389 return CGF.EmitComplexExpr(Op).first;
390 return Visit(Op);
391}
392Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
393 Expr *Op = E->getSubExpr();
394 if (Op->getType()->isComplexType())
395 return CGF.EmitComplexExpr(Op).second;
396
397 // FIXME: does this evaluate the subexpr??
398 return 0; // FIXME: Return zero of the right int/fp type.
399}
400
401
Chris Lattner9fba49a2007-08-24 05:35:26 +0000402//===----------------------------------------------------------------------===//
403// Binary Operators
404//===----------------------------------------------------------------------===//
405
406BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
407 BinOpInfo Result;
408 Result.LHS = Visit(E->getLHS());
409 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000410 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000411 Result.E = E;
412 return Result;
413}
414
Chris Lattner660e31d2007-08-24 21:00:35 +0000415Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
416 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
417 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
418
419 BinOpInfo OpInfo;
420
421 // Load the LHS and RHS operands.
422 LValue LHSLV = EmitLValue(E->getLHS());
423 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
424
425 // FIXME: It is possible for the RHS to be complex.
426 OpInfo.RHS = Visit(E->getRHS());
427
428 // Convert the LHS/RHS values to the computation type.
429 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
430 QualType ComputeType = CAO->getComputationType();
431
432 // FIXME: it's possible for the computation type to be complex if the RHS
433 // is complex. Handle this!
434 OpInfo.LHS = CGF.EmitConversion(RValue::get(OpInfo.LHS), LHSTy,
435 ComputeType).getVal();
436
437 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000438 if (E->getOpcode() != BinaryOperator::SubAssign ||
439 !E->getLHS()->getType()->isPointerType()) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000440 OpInfo.RHS = CGF.EmitConversion(RValue::get(OpInfo.RHS), RHSTy,
441 ComputeType).getVal();
442 }
443 OpInfo.Ty = ComputeType;
444 OpInfo.E = E;
445
446 // Expand the binary operator.
447 Value *Result = (this->*Func)(OpInfo);
448
449 // Truncate the result back to the LHS type.
450 Result = CGF.EmitConversion(RValue::get(Result), ComputeType, LHSTy).getVal();
451
452 // Store the result value into the LHS lvalue.
453 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
454
455 return Result;
456}
457
458
Chris Lattner9fba49a2007-08-24 05:35:26 +0000459Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
460 if (Ops.LHS->getType()->isFloatingPoint())
461 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000462 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000463 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
464 else
465 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
466}
467
468Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
469 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000470 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000471 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
472 else
473 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
474}
475
476
477Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000478 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000479 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000480
481 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000482 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
483 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
484 // int + pointer
485 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
486}
487
488Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
489 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
490 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
491
Chris Lattner660e31d2007-08-24 21:00:35 +0000492 // pointer - int
493 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
494 "ptr-ptr shouldn't get here");
495 // FIXME: The pointer could point to a VLA.
496 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
497 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
498}
499
500Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
501 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
502 // the compound assignment case it is invalid, so just handle it here.
503 if (!E->getRHS()->getType()->isPointerType())
504 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000505
506 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000507 Value *LHS = Visit(E->getLHS());
508 Value *RHS = Visit(E->getRHS());
509
510 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
511 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
512 "Can't subtract different pointer types");
513
Chris Lattner9fba49a2007-08-24 05:35:26 +0000514 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000515 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
516 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000517
518 const llvm::Type *ResultType = ConvertType(E->getType());
519 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
520 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
521 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000522
523 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
524 // remainder. As such, we handle common power-of-two cases here to generate
525 // better code.
526 if (llvm::isPowerOf2_64(ElementSize)) {
527 Value *ShAmt =
528 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
529 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
530 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000531
Chris Lattner9fba49a2007-08-24 05:35:26 +0000532 // Otherwise, do a full sdiv.
533 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
534 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
535}
536
Chris Lattner660e31d2007-08-24 21:00:35 +0000537
Chris Lattner9fba49a2007-08-24 05:35:26 +0000538Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
539 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
540 // RHS to the same size as the LHS.
541 Value *RHS = Ops.RHS;
542 if (Ops.LHS->getType() != RHS->getType())
543 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
544
545 return Builder.CreateShl(Ops.LHS, RHS, "shl");
546}
547
548Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
549 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
550 // RHS to the same size as the LHS.
551 Value *RHS = Ops.RHS;
552 if (Ops.LHS->getType() != RHS->getType())
553 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
554
Chris Lattner660e31d2007-08-24 21:00:35 +0000555 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000556 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
557 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
558}
559
560Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
561 unsigned SICmpOpc, unsigned FCmpOpc) {
562 llvm::Value *Result;
563 QualType LHSTy = E->getLHS()->getType();
564 if (!LHSTy->isComplexType()) {
565 Value *LHS = Visit(E->getLHS());
566 Value *RHS = Visit(E->getRHS());
567
568 if (LHS->getType()->isFloatingPoint()) {
569 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
570 LHS, RHS, "cmp");
571 } else if (LHSTy->isUnsignedIntegerType()) {
572 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
573 LHS, RHS, "cmp");
574 } else {
575 // Signed integers and pointers.
576 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
577 LHS, RHS, "cmp");
578 }
579 } else {
580 // Complex Comparison: can only be an equality comparison.
581 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
582 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
583
584 QualType CETy =
585 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
586
587 llvm::Value *ResultR, *ResultI;
588 if (CETy->isRealFloatingType()) {
589 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
590 LHS.first, RHS.first, "cmp.r");
591 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
592 LHS.second, RHS.second, "cmp.i");
593 } else {
594 // Complex comparisons can only be equality comparisons. As such, signed
595 // and unsigned opcodes are the same.
596 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
597 LHS.first, RHS.first, "cmp.r");
598 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
599 LHS.second, RHS.second, "cmp.i");
600 }
601
602 if (E->getOpcode() == BinaryOperator::EQ) {
603 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
604 } else {
605 assert(E->getOpcode() == BinaryOperator::NE &&
606 "Complex comparison other than == or != ?");
607 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
608 }
609 }
610
611 // ZExt result to int.
612 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
613}
614
615Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
616 LValue LHS = EmitLValue(E->getLHS());
617 Value *RHS = Visit(E->getRHS());
618
619 // Store the value into the LHS.
620 // FIXME: Volatility!
621 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
622
623 // Return the RHS.
624 return RHS;
625}
626
627Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
628 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
629
630 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
631 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
632
633 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
634 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
635
636 CGF.EmitBlock(RHSBlock);
637 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
638
639 // Reaquire the RHS block, as there may be subblocks inserted.
640 RHSBlock = Builder.GetInsertBlock();
641 CGF.EmitBlock(ContBlock);
642
643 // Create a PHI node. If we just evaluted the LHS condition, the result is
644 // false. If we evaluated both, the result is the RHS condition.
645 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
646 PN->reserveOperandSpace(2);
647 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
648 PN->addIncoming(RHSCond, RHSBlock);
649
650 // ZExt result to int.
651 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
652}
653
654Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
655 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
656
657 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
658 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
659
660 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
661 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
662
663 CGF.EmitBlock(RHSBlock);
664 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
665
666 // Reaquire the RHS block, as there may be subblocks inserted.
667 RHSBlock = Builder.GetInsertBlock();
668 CGF.EmitBlock(ContBlock);
669
670 // Create a PHI node. If we just evaluted the LHS condition, the result is
671 // true. If we evaluated both, the result is the RHS condition.
672 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
673 PN->reserveOperandSpace(2);
674 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
675 PN->addIncoming(RHSCond, RHSBlock);
676
677 // ZExt result to int.
678 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
679}
680
681Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
682 CGF.EmitStmt(E->getLHS());
683 return Visit(E->getRHS());
684}
685
686//===----------------------------------------------------------------------===//
687// Other Operators
688//===----------------------------------------------------------------------===//
689
690Value *ScalarExprEmitter::
691VisitConditionalOperator(const ConditionalOperator *E) {
692 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
693 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
694 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
695
696 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
697 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
698
699 CGF.EmitBlock(LHSBlock);
700
701 // Handle the GNU extension for missing LHS.
702 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
703 Builder.CreateBr(ContBlock);
704 LHSBlock = Builder.GetInsertBlock();
705
706 CGF.EmitBlock(RHSBlock);
707
708 Value *RHS = Visit(E->getRHS());
709 Builder.CreateBr(ContBlock);
710 RHSBlock = Builder.GetInsertBlock();
711
712 CGF.EmitBlock(ContBlock);
713
714 // Create a PHI node for the real part.
715 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
716 PN->reserveOperandSpace(2);
717 PN->addIncoming(LHS, LHSBlock);
718 PN->addIncoming(RHS, RHSBlock);
719 return PN;
720}
721
722Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
723 llvm::APSInt CondVal(32);
724 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
725 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
726
727 // Emit the LHS or RHS as appropriate.
728 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
729}
730
731//===----------------------------------------------------------------------===//
732// Entry Point into this File
733//===----------------------------------------------------------------------===//
734
735/// EmitComplexExpr - Emit the computation of the specified expression of
736/// complex type, ignoring the result.
737Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
738 assert(E && !hasAggregateLLVMType(E->getType()) &&
739 "Invalid scalar expression to emit");
740
741 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
742}