blob: 9bd5b3f1ccbc678b642e0b9fecda5505e6662ac0 [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;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000396
397 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
398 // effects are evaluated.
399 CGF.EmitScalarExpr(Op);
400 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000401}
402
403
Chris Lattner9fba49a2007-08-24 05:35:26 +0000404//===----------------------------------------------------------------------===//
405// Binary Operators
406//===----------------------------------------------------------------------===//
407
408BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
409 BinOpInfo Result;
410 Result.LHS = Visit(E->getLHS());
411 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000412 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000413 Result.E = E;
414 return Result;
415}
416
Chris Lattner660e31d2007-08-24 21:00:35 +0000417Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
418 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
419 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
420
421 BinOpInfo OpInfo;
422
423 // Load the LHS and RHS operands.
424 LValue LHSLV = EmitLValue(E->getLHS());
425 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
426
427 // FIXME: It is possible for the RHS to be complex.
428 OpInfo.RHS = Visit(E->getRHS());
429
430 // Convert the LHS/RHS values to the computation type.
431 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
432 QualType ComputeType = CAO->getComputationType();
433
434 // FIXME: it's possible for the computation type to be complex if the RHS
435 // is complex. Handle this!
436 OpInfo.LHS = CGF.EmitConversion(RValue::get(OpInfo.LHS), LHSTy,
437 ComputeType).getVal();
438
439 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000440 if (E->getOpcode() != BinaryOperator::SubAssign ||
441 !E->getLHS()->getType()->isPointerType()) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000442 OpInfo.RHS = CGF.EmitConversion(RValue::get(OpInfo.RHS), RHSTy,
443 ComputeType).getVal();
444 }
445 OpInfo.Ty = ComputeType;
446 OpInfo.E = E;
447
448 // Expand the binary operator.
449 Value *Result = (this->*Func)(OpInfo);
450
451 // Truncate the result back to the LHS type.
452 Result = CGF.EmitConversion(RValue::get(Result), ComputeType, LHSTy).getVal();
453
454 // Store the result value into the LHS lvalue.
455 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
456
457 return Result;
458}
459
460
Chris Lattner9fba49a2007-08-24 05:35:26 +0000461Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
462 if (Ops.LHS->getType()->isFloatingPoint())
463 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000464 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000465 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
466 else
467 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
468}
469
470Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
471 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000472 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000473 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
474 else
475 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
476}
477
478
479Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000480 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000481 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000482
483 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000484 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
485 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
486 // int + pointer
487 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
488}
489
490Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
491 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
492 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
493
Chris Lattner660e31d2007-08-24 21:00:35 +0000494 // pointer - int
495 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
496 "ptr-ptr shouldn't get here");
497 // FIXME: The pointer could point to a VLA.
498 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
499 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
500}
501
502Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
503 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
504 // the compound assignment case it is invalid, so just handle it here.
505 if (!E->getRHS()->getType()->isPointerType())
506 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000507
508 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000509 Value *LHS = Visit(E->getLHS());
510 Value *RHS = Visit(E->getRHS());
511
512 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
513 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
514 "Can't subtract different pointer types");
515
Chris Lattner9fba49a2007-08-24 05:35:26 +0000516 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000517 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
518 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000519
520 const llvm::Type *ResultType = ConvertType(E->getType());
521 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
522 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
523 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000524
525 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
526 // remainder. As such, we handle common power-of-two cases here to generate
527 // better code.
528 if (llvm::isPowerOf2_64(ElementSize)) {
529 Value *ShAmt =
530 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
531 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
532 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000533
Chris Lattner9fba49a2007-08-24 05:35:26 +0000534 // Otherwise, do a full sdiv.
535 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
536 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
537}
538
Chris Lattner660e31d2007-08-24 21:00:35 +0000539
Chris Lattner9fba49a2007-08-24 05:35:26 +0000540Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
541 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
542 // RHS to the same size as the LHS.
543 Value *RHS = Ops.RHS;
544 if (Ops.LHS->getType() != RHS->getType())
545 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
546
547 return Builder.CreateShl(Ops.LHS, RHS, "shl");
548}
549
550Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
551 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
552 // RHS to the same size as the LHS.
553 Value *RHS = Ops.RHS;
554 if (Ops.LHS->getType() != RHS->getType())
555 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
556
Chris Lattner660e31d2007-08-24 21:00:35 +0000557 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000558 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
559 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
560}
561
562Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
563 unsigned SICmpOpc, unsigned FCmpOpc) {
564 llvm::Value *Result;
565 QualType LHSTy = E->getLHS()->getType();
566 if (!LHSTy->isComplexType()) {
567 Value *LHS = Visit(E->getLHS());
568 Value *RHS = Visit(E->getRHS());
569
570 if (LHS->getType()->isFloatingPoint()) {
571 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
572 LHS, RHS, "cmp");
573 } else if (LHSTy->isUnsignedIntegerType()) {
574 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
575 LHS, RHS, "cmp");
576 } else {
577 // Signed integers and pointers.
578 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
579 LHS, RHS, "cmp");
580 }
581 } else {
582 // Complex Comparison: can only be an equality comparison.
583 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
584 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
585
586 QualType CETy =
587 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
588
589 llvm::Value *ResultR, *ResultI;
590 if (CETy->isRealFloatingType()) {
591 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
592 LHS.first, RHS.first, "cmp.r");
593 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
594 LHS.second, RHS.second, "cmp.i");
595 } else {
596 // Complex comparisons can only be equality comparisons. As such, signed
597 // and unsigned opcodes are the same.
598 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
599 LHS.first, RHS.first, "cmp.r");
600 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
601 LHS.second, RHS.second, "cmp.i");
602 }
603
604 if (E->getOpcode() == BinaryOperator::EQ) {
605 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
606 } else {
607 assert(E->getOpcode() == BinaryOperator::NE &&
608 "Complex comparison other than == or != ?");
609 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
610 }
611 }
612
613 // ZExt result to int.
614 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
615}
616
617Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
618 LValue LHS = EmitLValue(E->getLHS());
619 Value *RHS = Visit(E->getRHS());
620
621 // Store the value into the LHS.
622 // FIXME: Volatility!
623 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
624
625 // Return the RHS.
626 return RHS;
627}
628
629Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
630 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
631
632 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
633 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
634
635 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
636 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
637
638 CGF.EmitBlock(RHSBlock);
639 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
640
641 // Reaquire the RHS block, as there may be subblocks inserted.
642 RHSBlock = Builder.GetInsertBlock();
643 CGF.EmitBlock(ContBlock);
644
645 // Create a PHI node. If we just evaluted the LHS condition, the result is
646 // false. If we evaluated both, the result is the RHS condition.
647 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
648 PN->reserveOperandSpace(2);
649 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
650 PN->addIncoming(RHSCond, RHSBlock);
651
652 // ZExt result to int.
653 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
654}
655
656Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
657 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
658
659 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
660 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
661
662 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
663 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
664
665 CGF.EmitBlock(RHSBlock);
666 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
667
668 // Reaquire the RHS block, as there may be subblocks inserted.
669 RHSBlock = Builder.GetInsertBlock();
670 CGF.EmitBlock(ContBlock);
671
672 // Create a PHI node. If we just evaluted the LHS condition, the result is
673 // true. If we evaluated both, the result is the RHS condition.
674 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
675 PN->reserveOperandSpace(2);
676 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
677 PN->addIncoming(RHSCond, RHSBlock);
678
679 // ZExt result to int.
680 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
681}
682
683Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
684 CGF.EmitStmt(E->getLHS());
685 return Visit(E->getRHS());
686}
687
688//===----------------------------------------------------------------------===//
689// Other Operators
690//===----------------------------------------------------------------------===//
691
692Value *ScalarExprEmitter::
693VisitConditionalOperator(const ConditionalOperator *E) {
694 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
695 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
696 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
697
698 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
699 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
700
701 CGF.EmitBlock(LHSBlock);
702
703 // Handle the GNU extension for missing LHS.
704 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
705 Builder.CreateBr(ContBlock);
706 LHSBlock = Builder.GetInsertBlock();
707
708 CGF.EmitBlock(RHSBlock);
709
710 Value *RHS = Visit(E->getRHS());
711 Builder.CreateBr(ContBlock);
712 RHSBlock = Builder.GetInsertBlock();
713
714 CGF.EmitBlock(ContBlock);
715
716 // Create a PHI node for the real part.
717 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
718 PN->reserveOperandSpace(2);
719 PN->addIncoming(LHS, LHSBlock);
720 PN->addIncoming(RHS, RHSBlock);
721 return PN;
722}
723
724Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
725 llvm::APSInt CondVal(32);
726 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
727 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
728
729 // Emit the LHS or RHS as appropriate.
730 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
731}
732
733//===----------------------------------------------------------------------===//
734// Entry Point into this File
735//===----------------------------------------------------------------------===//
736
737/// EmitComplexExpr - Emit the computation of the specified expression of
738/// complex type, ignoring the result.
739Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
740 assert(E && !hasAggregateLLVMType(E->getType()) &&
741 "Invalid scalar expression to emit");
742
743 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
744}