blob: c10e5106d84b66969e7692d4b1a87e84ffc84d9a [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!
317 Value *InVal = CGF.EmitLoadOfLValue(LV/* false*/,
318 E->getSubExpr()->getType()).getVal();
319
320 int AmountVal = isInc ? 1 : -1;
321
322 Value *NextVal;
323 if (isa<llvm::IntegerType>(InVal->getType()))
324 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
325 else
326 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
327
328 // Add the inc/dec to the real part.
329 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
330
331 // Store the updated result through the lvalue.
332 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
333 E->getSubExpr()->getType());
334
335 // If this is a postinc, return the value read from memory, otherwise use the
336 // updated value.
337 return isPre ? NextVal : InVal;
338}
339
340
341Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
342 Value *Op = Visit(E->getSubExpr());
343 return Builder.CreateNeg(Op, "neg");
344}
345
346Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
347 Value *Op = Visit(E->getSubExpr());
348 return Builder.CreateNot(Op, "neg");
349}
350
351Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
352 // Compare operand to zero.
353 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
354
355 // Invert value.
356 // TODO: Could dynamically modify easy computations here. For example, if
357 // the operand is an icmp ne, turn into icmp eq.
358 BoolVal = Builder.CreateNot(BoolVal, "lnot");
359
360 // ZExt result to int.
361 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
362}
363
364/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
365/// an integer (RetType).
366Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000367 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000368 /// FIXME: This doesn't handle VLAs yet!
369 std::pair<uint64_t, unsigned> Info =
370 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
371
372 uint64_t Val = isSizeOf ? Info.first : Info.second;
373 Val /= 8; // Return size in bytes, not bits.
374
375 assert(RetType->isIntegerType() && "Result type must be an integer!");
376
377 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
378 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
379}
380
Chris Lattner01211af2007-08-24 21:20:17 +0000381Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
382 Expr *Op = E->getSubExpr();
383 if (Op->getType()->isComplexType())
384 return CGF.EmitComplexExpr(Op).first;
385 return Visit(Op);
386}
387Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
388 Expr *Op = E->getSubExpr();
389 if (Op->getType()->isComplexType())
390 return CGF.EmitComplexExpr(Op).second;
391
392 // FIXME: does this evaluate the subexpr??
393 return 0; // FIXME: Return zero of the right int/fp type.
394}
395
396
Chris Lattner9fba49a2007-08-24 05:35:26 +0000397//===----------------------------------------------------------------------===//
398// Binary Operators
399//===----------------------------------------------------------------------===//
400
401BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
402 BinOpInfo Result;
403 Result.LHS = Visit(E->getLHS());
404 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000405 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000406 Result.E = E;
407 return Result;
408}
409
Chris Lattner660e31d2007-08-24 21:00:35 +0000410Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
411 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
412 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
413
414 BinOpInfo OpInfo;
415
416 // Load the LHS and RHS operands.
417 LValue LHSLV = EmitLValue(E->getLHS());
418 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
419
420 // FIXME: It is possible for the RHS to be complex.
421 OpInfo.RHS = Visit(E->getRHS());
422
423 // Convert the LHS/RHS values to the computation type.
424 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
425 QualType ComputeType = CAO->getComputationType();
426
427 // FIXME: it's possible for the computation type to be complex if the RHS
428 // is complex. Handle this!
429 OpInfo.LHS = CGF.EmitConversion(RValue::get(OpInfo.LHS), LHSTy,
430 ComputeType).getVal();
431
432 // Do not merge types for -= where the LHS is a pointer.
433 if (E->getOpcode() != BinaryOperator::SubAssign &&
434 E->getLHS()->getType()->isPointerType()) {
435 OpInfo.RHS = CGF.EmitConversion(RValue::get(OpInfo.RHS), RHSTy,
436 ComputeType).getVal();
437 }
438 OpInfo.Ty = ComputeType;
439 OpInfo.E = E;
440
441 // Expand the binary operator.
442 Value *Result = (this->*Func)(OpInfo);
443
444 // Truncate the result back to the LHS type.
445 Result = CGF.EmitConversion(RValue::get(Result), ComputeType, LHSTy).getVal();
446
447 // Store the result value into the LHS lvalue.
448 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
449
450 return Result;
451}
452
453
Chris Lattner9fba49a2007-08-24 05:35:26 +0000454Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
455 if (Ops.LHS->getType()->isFloatingPoint())
456 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000457 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000458 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
459 else
460 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
461}
462
463Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
464 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000465 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000466 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
467 else
468 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
469}
470
471
472Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000473 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000474 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000475
476 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000477 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
478 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
479 // int + pointer
480 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
481}
482
483Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
484 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
485 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
486
Chris Lattner660e31d2007-08-24 21:00:35 +0000487 // pointer - int
488 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
489 "ptr-ptr shouldn't get here");
490 // FIXME: The pointer could point to a VLA.
491 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
492 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
493}
494
495Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
496 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
497 // the compound assignment case it is invalid, so just handle it here.
498 if (!E->getRHS()->getType()->isPointerType())
499 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000500
501 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000502 Value *LHS = Visit(E->getLHS());
503 Value *RHS = Visit(E->getRHS());
504
505 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
506 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
507 "Can't subtract different pointer types");
508
Chris Lattner9fba49a2007-08-24 05:35:26 +0000509 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000510 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
511 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000512
513 const llvm::Type *ResultType = ConvertType(E->getType());
514 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
515 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
516 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000517
518 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
519 // remainder. As such, we handle common power-of-two cases here to generate
520 // better code.
521 if (llvm::isPowerOf2_64(ElementSize)) {
522 Value *ShAmt =
523 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
524 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
525 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000526
Chris Lattner9fba49a2007-08-24 05:35:26 +0000527 // Otherwise, do a full sdiv.
528 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
529 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
530}
531
Chris Lattner660e31d2007-08-24 21:00:35 +0000532
Chris Lattner9fba49a2007-08-24 05:35:26 +0000533Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
534 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
535 // RHS to the same size as the LHS.
536 Value *RHS = Ops.RHS;
537 if (Ops.LHS->getType() != RHS->getType())
538 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
539
540 return Builder.CreateShl(Ops.LHS, RHS, "shl");
541}
542
543Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
544 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
545 // RHS to the same size as the LHS.
546 Value *RHS = Ops.RHS;
547 if (Ops.LHS->getType() != RHS->getType())
548 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
549
Chris Lattner660e31d2007-08-24 21:00:35 +0000550 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000551 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
552 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
553}
554
555Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
556 unsigned SICmpOpc, unsigned FCmpOpc) {
557 llvm::Value *Result;
558 QualType LHSTy = E->getLHS()->getType();
559 if (!LHSTy->isComplexType()) {
560 Value *LHS = Visit(E->getLHS());
561 Value *RHS = Visit(E->getRHS());
562
563 if (LHS->getType()->isFloatingPoint()) {
564 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
565 LHS, RHS, "cmp");
566 } else if (LHSTy->isUnsignedIntegerType()) {
567 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
568 LHS, RHS, "cmp");
569 } else {
570 // Signed integers and pointers.
571 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
572 LHS, RHS, "cmp");
573 }
574 } else {
575 // Complex Comparison: can only be an equality comparison.
576 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
577 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
578
579 QualType CETy =
580 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
581
582 llvm::Value *ResultR, *ResultI;
583 if (CETy->isRealFloatingType()) {
584 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
585 LHS.first, RHS.first, "cmp.r");
586 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
587 LHS.second, RHS.second, "cmp.i");
588 } else {
589 // Complex comparisons can only be equality comparisons. As such, signed
590 // and unsigned opcodes are the same.
591 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
592 LHS.first, RHS.first, "cmp.r");
593 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
594 LHS.second, RHS.second, "cmp.i");
595 }
596
597 if (E->getOpcode() == BinaryOperator::EQ) {
598 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
599 } else {
600 assert(E->getOpcode() == BinaryOperator::NE &&
601 "Complex comparison other than == or != ?");
602 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
603 }
604 }
605
606 // ZExt result to int.
607 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
608}
609
610Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
611 LValue LHS = EmitLValue(E->getLHS());
612 Value *RHS = Visit(E->getRHS());
613
614 // Store the value into the LHS.
615 // FIXME: Volatility!
616 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
617
618 // Return the RHS.
619 return RHS;
620}
621
622Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
623 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
624
625 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
626 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
627
628 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
629 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
630
631 CGF.EmitBlock(RHSBlock);
632 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
633
634 // Reaquire the RHS block, as there may be subblocks inserted.
635 RHSBlock = Builder.GetInsertBlock();
636 CGF.EmitBlock(ContBlock);
637
638 // Create a PHI node. If we just evaluted the LHS condition, the result is
639 // false. If we evaluated both, the result is the RHS condition.
640 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
641 PN->reserveOperandSpace(2);
642 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
643 PN->addIncoming(RHSCond, RHSBlock);
644
645 // ZExt result to int.
646 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
647}
648
649Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
650 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
651
652 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
653 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
654
655 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
656 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
657
658 CGF.EmitBlock(RHSBlock);
659 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
660
661 // Reaquire the RHS block, as there may be subblocks inserted.
662 RHSBlock = Builder.GetInsertBlock();
663 CGF.EmitBlock(ContBlock);
664
665 // Create a PHI node. If we just evaluted the LHS condition, the result is
666 // true. If we evaluated both, the result is the RHS condition.
667 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
668 PN->reserveOperandSpace(2);
669 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
670 PN->addIncoming(RHSCond, RHSBlock);
671
672 // ZExt result to int.
673 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
674}
675
676Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
677 CGF.EmitStmt(E->getLHS());
678 return Visit(E->getRHS());
679}
680
681//===----------------------------------------------------------------------===//
682// Other Operators
683//===----------------------------------------------------------------------===//
684
685Value *ScalarExprEmitter::
686VisitConditionalOperator(const ConditionalOperator *E) {
687 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
688 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
689 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
690
691 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
692 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
693
694 CGF.EmitBlock(LHSBlock);
695
696 // Handle the GNU extension for missing LHS.
697 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
698 Builder.CreateBr(ContBlock);
699 LHSBlock = Builder.GetInsertBlock();
700
701 CGF.EmitBlock(RHSBlock);
702
703 Value *RHS = Visit(E->getRHS());
704 Builder.CreateBr(ContBlock);
705 RHSBlock = Builder.GetInsertBlock();
706
707 CGF.EmitBlock(ContBlock);
708
709 // Create a PHI node for the real part.
710 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
711 PN->reserveOperandSpace(2);
712 PN->addIncoming(LHS, LHSBlock);
713 PN->addIncoming(RHS, RHSBlock);
714 return PN;
715}
716
717Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
718 llvm::APSInt CondVal(32);
719 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
720 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
721
722 // Emit the LHS or RHS as appropriate.
723 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
724}
725
726//===----------------------------------------------------------------------===//
727// Entry Point into this File
728//===----------------------------------------------------------------------===//
729
730/// EmitComplexExpr - Emit the computation of the specified expression of
731/// complex type, ignoring the result.
732Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
733 assert(E && !hasAggregateLLVMType(E->getType()) &&
734 "Invalid scalar expression to emit");
735
736 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
737}