blob: bdaf1795de45c340ee040a7b98ac8575ae2f2b3d [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);
150 // FIXME: Real,Imag.
151 Value *VisitUnaryExtension(const UnaryOperator *E) {
152 return Visit(E->getSubExpr());
153 }
154
155 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000156 Value *EmitMul(const BinOpInfo &Ops) {
157 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
158 }
159 Value *EmitDiv(const BinOpInfo &Ops);
160 Value *EmitRem(const BinOpInfo &Ops);
161 Value *EmitAdd(const BinOpInfo &Ops);
162 Value *EmitSub(const BinOpInfo &Ops);
163 Value *EmitShl(const BinOpInfo &Ops);
164 Value *EmitShr(const BinOpInfo &Ops);
165 Value *EmitAnd(const BinOpInfo &Ops) {
166 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
167 }
168 Value *EmitXor(const BinOpInfo &Ops) {
169 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
170 }
171 Value *EmitOr (const BinOpInfo &Ops) {
172 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
173 }
174
Chris Lattner660e31d2007-08-24 21:00:35 +0000175 BinOpInfo EmitBinOps(const BinaryOperator *E);
176 Value *EmitCompoundAssign(const BinaryOperator *E,
177 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
178
179 // Binary operators and binary compound assignment operators.
180#define HANDLEBINOP(OP) \
181 Value *VisitBin ## OP(const BinaryOperator *E) { \
182 return Emit ## OP(EmitBinOps(E)); \
183 } \
184 Value *VisitBin ## OP ## Assign(const BinaryOperator *E) { \
185 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
186 }
187 HANDLEBINOP(Mul);
188 HANDLEBINOP(Div);
189 HANDLEBINOP(Rem);
190 HANDLEBINOP(Add);
191 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
192 HANDLEBINOP(Shl);
193 HANDLEBINOP(Shr);
194 HANDLEBINOP(And);
195 HANDLEBINOP(Xor);
196 HANDLEBINOP(Or);
197#undef HANDLEBINOP
198 Value *VisitBinSub(const BinaryOperator *E);
199 Value *VisitBinSubAssign(const BinaryOperator *E) {
200 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
201 }
202
Chris Lattner9fba49a2007-08-24 05:35:26 +0000203 // Comparisons.
204 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
205 unsigned SICmpOpc, unsigned FCmpOpc);
206#define VISITCOMP(CODE, UI, SI, FP) \
207 Value *VisitBin##CODE(const BinaryOperator *E) { \
208 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
209 llvm::FCmpInst::FP); }
210 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
211 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
212 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
213 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
214 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
215 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
216#undef VISITCOMP
217
218 Value *VisitBinAssign (const BinaryOperator *E);
219
220 Value *VisitBinLAnd (const BinaryOperator *E);
221 Value *VisitBinLOr (const BinaryOperator *E);
222
223 // FIXME: Compound assignment operators.
224 Value *VisitBinComma (const BinaryOperator *E);
225
226 // Other Operators.
227 Value *VisitConditionalOperator(const ConditionalOperator *CO);
228 Value *VisitChooseExpr(ChooseExpr *CE);
229 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
230 return CGF.EmitObjCStringLiteral(E);
231 }
232};
233} // end anonymous namespace.
234
235//===----------------------------------------------------------------------===//
236// Utilities
237//===----------------------------------------------------------------------===//
238
239//===----------------------------------------------------------------------===//
240// Visitor Methods
241//===----------------------------------------------------------------------===//
242
243Value *ScalarExprEmitter::VisitExpr(Expr *E) {
244 fprintf(stderr, "Unimplemented scalar expr!\n");
245 E->dump();
246 if (E->getType()->isVoidType())
247 return 0;
248 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
249}
250
251Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
252 // Emit subscript expressions in rvalue context's. For most cases, this just
253 // loads the lvalue formed by the subscript expr. However, we have to be
254 // careful, because the base of a vector subscript is occasionally an rvalue,
255 // so we can't get it as an lvalue.
256 if (!E->getBase()->getType()->isVectorType())
257 return EmitLoadOfLValue(E);
258
259 // Handle the vector case. The base must be a vector, the index must be an
260 // integer value.
261 Value *Base = Visit(E->getBase());
262 Value *Idx = Visit(E->getIdx());
263
264 // FIXME: Convert Idx to i32 type.
265 return Builder.CreateExtractElement(Base, Idx, "vecext");
266}
267
268/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
269/// also handle things like function to pointer-to-function decay, and array to
270/// pointer decay.
271Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
272 const Expr *Op = E->getSubExpr();
273
274 // If this is due to array->pointer conversion, emit the array expression as
275 // an l-value.
276 if (Op->getType()->isArrayType()) {
277 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
278 // will not true when we add support for VLAs.
279 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
280
281 assert(isa<llvm::PointerType>(V->getType()) &&
282 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
283 ->getElementType()) &&
284 "Doesn't support VLAs yet!");
285 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
286 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
287 }
288
289 return EmitCastExpr(Op, E->getType());
290}
291
292
293// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
294// have to handle a more broad range of conversions than explicit casts, as they
295// handle things like function to ptr-to-function decay etc.
296Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
297 RValue Src = CGF.EmitAnyExpr(E);
298
299 // If the destination is void, just evaluate the source.
300 if (DestTy->isVoidType())
301 return 0;
302
303 // FIXME: Refactor EmitConversion to not return an RValue. Sink it into this
304 // method.
305 return CGF.EmitConversion(Src, E->getType(), DestTy).getVal();
306}
307
308//===----------------------------------------------------------------------===//
309// Unary Operators
310//===----------------------------------------------------------------------===//
311
312Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000313 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000314 LValue LV = EmitLValue(E->getSubExpr());
315 // FIXME: Handle volatile!
316 Value *InVal = CGF.EmitLoadOfLValue(LV/* false*/,
317 E->getSubExpr()->getType()).getVal();
318
319 int AmountVal = isInc ? 1 : -1;
320
321 Value *NextVal;
322 if (isa<llvm::IntegerType>(InVal->getType()))
323 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
324 else
325 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
326
327 // Add the inc/dec to the real part.
328 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
329
330 // Store the updated result through the lvalue.
331 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
332 E->getSubExpr()->getType());
333
334 // If this is a postinc, return the value read from memory, otherwise use the
335 // updated value.
336 return isPre ? NextVal : InVal;
337}
338
339
340Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
341 Value *Op = Visit(E->getSubExpr());
342 return Builder.CreateNeg(Op, "neg");
343}
344
345Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
346 Value *Op = Visit(E->getSubExpr());
347 return Builder.CreateNot(Op, "neg");
348}
349
350Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
351 // Compare operand to zero.
352 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
353
354 // Invert value.
355 // TODO: Could dynamically modify easy computations here. For example, if
356 // the operand is an icmp ne, turn into icmp eq.
357 BoolVal = Builder.CreateNot(BoolVal, "lnot");
358
359 // ZExt result to int.
360 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
361}
362
363/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
364/// an integer (RetType).
365Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
366 QualType RetType,bool isSizeOf){
367 /// FIXME: This doesn't handle VLAs yet!
368 std::pair<uint64_t, unsigned> Info =
369 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
370
371 uint64_t Val = isSizeOf ? Info.first : Info.second;
372 Val /= 8; // Return size in bytes, not bits.
373
374 assert(RetType->isIntegerType() && "Result type must be an integer!");
375
376 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
377 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
378}
379
380//===----------------------------------------------------------------------===//
381// Binary Operators
382//===----------------------------------------------------------------------===//
383
384BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
385 BinOpInfo Result;
386 Result.LHS = Visit(E->getLHS());
387 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000388 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000389 Result.E = E;
390 return Result;
391}
392
Chris Lattner660e31d2007-08-24 21:00:35 +0000393Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
394 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
395 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
396
397 BinOpInfo OpInfo;
398
399 // Load the LHS and RHS operands.
400 LValue LHSLV = EmitLValue(E->getLHS());
401 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
402
403 // FIXME: It is possible for the RHS to be complex.
404 OpInfo.RHS = Visit(E->getRHS());
405
406 // Convert the LHS/RHS values to the computation type.
407 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
408 QualType ComputeType = CAO->getComputationType();
409
410 // FIXME: it's possible for the computation type to be complex if the RHS
411 // is complex. Handle this!
412 OpInfo.LHS = CGF.EmitConversion(RValue::get(OpInfo.LHS), LHSTy,
413 ComputeType).getVal();
414
415 // Do not merge types for -= where the LHS is a pointer.
416 if (E->getOpcode() != BinaryOperator::SubAssign &&
417 E->getLHS()->getType()->isPointerType()) {
418 OpInfo.RHS = CGF.EmitConversion(RValue::get(OpInfo.RHS), RHSTy,
419 ComputeType).getVal();
420 }
421 OpInfo.Ty = ComputeType;
422 OpInfo.E = E;
423
424 // Expand the binary operator.
425 Value *Result = (this->*Func)(OpInfo);
426
427 // Truncate the result back to the LHS type.
428 Result = CGF.EmitConversion(RValue::get(Result), ComputeType, LHSTy).getVal();
429
430 // Store the result value into the LHS lvalue.
431 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
432
433 return Result;
434}
435
436
Chris Lattner9fba49a2007-08-24 05:35:26 +0000437Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
438 if (Ops.LHS->getType()->isFloatingPoint())
439 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000440 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000441 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
442 else
443 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
444}
445
446Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
447 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000448 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000449 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
450 else
451 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
452}
453
454
455Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000456 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000457 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000458
459 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000460 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
461 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
462 // int + pointer
463 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
464}
465
466Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
467 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
468 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
469
Chris Lattner660e31d2007-08-24 21:00:35 +0000470 // pointer - int
471 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
472 "ptr-ptr shouldn't get here");
473 // FIXME: The pointer could point to a VLA.
474 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
475 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
476}
477
478Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
479 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
480 // the compound assignment case it is invalid, so just handle it here.
481 if (!E->getRHS()->getType()->isPointerType())
482 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000483
484 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000485 Value *LHS = Visit(E->getLHS());
486 Value *RHS = Visit(E->getRHS());
487
488 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
489 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
490 "Can't subtract different pointer types");
491
Chris Lattner9fba49a2007-08-24 05:35:26 +0000492 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000493 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
494 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000495
496 const llvm::Type *ResultType = ConvertType(E->getType());
497 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
498 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
499 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000500
501 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
502 // remainder. As such, we handle common power-of-two cases here to generate
503 // better code.
504 if (llvm::isPowerOf2_64(ElementSize)) {
505 Value *ShAmt =
506 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
507 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
508 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000509
Chris Lattner9fba49a2007-08-24 05:35:26 +0000510 // Otherwise, do a full sdiv.
511 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
512 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
513}
514
Chris Lattner660e31d2007-08-24 21:00:35 +0000515
Chris Lattner9fba49a2007-08-24 05:35:26 +0000516Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
517 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
518 // RHS to the same size as the LHS.
519 Value *RHS = Ops.RHS;
520 if (Ops.LHS->getType() != RHS->getType())
521 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
522
523 return Builder.CreateShl(Ops.LHS, RHS, "shl");
524}
525
526Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
527 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
528 // RHS to the same size as the LHS.
529 Value *RHS = Ops.RHS;
530 if (Ops.LHS->getType() != RHS->getType())
531 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
532
Chris Lattner660e31d2007-08-24 21:00:35 +0000533 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000534 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
535 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
536}
537
538Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
539 unsigned SICmpOpc, unsigned FCmpOpc) {
540 llvm::Value *Result;
541 QualType LHSTy = E->getLHS()->getType();
542 if (!LHSTy->isComplexType()) {
543 Value *LHS = Visit(E->getLHS());
544 Value *RHS = Visit(E->getRHS());
545
546 if (LHS->getType()->isFloatingPoint()) {
547 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
548 LHS, RHS, "cmp");
549 } else if (LHSTy->isUnsignedIntegerType()) {
550 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
551 LHS, RHS, "cmp");
552 } else {
553 // Signed integers and pointers.
554 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
555 LHS, RHS, "cmp");
556 }
557 } else {
558 // Complex Comparison: can only be an equality comparison.
559 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
560 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
561
562 QualType CETy =
563 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
564
565 llvm::Value *ResultR, *ResultI;
566 if (CETy->isRealFloatingType()) {
567 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
568 LHS.first, RHS.first, "cmp.r");
569 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
570 LHS.second, RHS.second, "cmp.i");
571 } else {
572 // Complex comparisons can only be equality comparisons. As such, signed
573 // and unsigned opcodes are the same.
574 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
575 LHS.first, RHS.first, "cmp.r");
576 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
577 LHS.second, RHS.second, "cmp.i");
578 }
579
580 if (E->getOpcode() == BinaryOperator::EQ) {
581 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
582 } else {
583 assert(E->getOpcode() == BinaryOperator::NE &&
584 "Complex comparison other than == or != ?");
585 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
586 }
587 }
588
589 // ZExt result to int.
590 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
591}
592
593Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
594 LValue LHS = EmitLValue(E->getLHS());
595 Value *RHS = Visit(E->getRHS());
596
597 // Store the value into the LHS.
598 // FIXME: Volatility!
599 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
600
601 // Return the RHS.
602 return RHS;
603}
604
605Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
606 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
607
608 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
609 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
610
611 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
612 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
613
614 CGF.EmitBlock(RHSBlock);
615 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
616
617 // Reaquire the RHS block, as there may be subblocks inserted.
618 RHSBlock = Builder.GetInsertBlock();
619 CGF.EmitBlock(ContBlock);
620
621 // Create a PHI node. If we just evaluted the LHS condition, the result is
622 // false. If we evaluated both, the result is the RHS condition.
623 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
624 PN->reserveOperandSpace(2);
625 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
626 PN->addIncoming(RHSCond, RHSBlock);
627
628 // ZExt result to int.
629 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
630}
631
632Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
633 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
634
635 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
636 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
637
638 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
639 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
640
641 CGF.EmitBlock(RHSBlock);
642 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
643
644 // Reaquire the RHS block, as there may be subblocks inserted.
645 RHSBlock = Builder.GetInsertBlock();
646 CGF.EmitBlock(ContBlock);
647
648 // Create a PHI node. If we just evaluted the LHS condition, the result is
649 // true. If we evaluated both, the result is the RHS condition.
650 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
651 PN->reserveOperandSpace(2);
652 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
653 PN->addIncoming(RHSCond, RHSBlock);
654
655 // ZExt result to int.
656 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
657}
658
659Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
660 CGF.EmitStmt(E->getLHS());
661 return Visit(E->getRHS());
662}
663
664//===----------------------------------------------------------------------===//
665// Other Operators
666//===----------------------------------------------------------------------===//
667
668Value *ScalarExprEmitter::
669VisitConditionalOperator(const ConditionalOperator *E) {
670 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
671 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
672 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
673
674 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
675 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
676
677 CGF.EmitBlock(LHSBlock);
678
679 // Handle the GNU extension for missing LHS.
680 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
681 Builder.CreateBr(ContBlock);
682 LHSBlock = Builder.GetInsertBlock();
683
684 CGF.EmitBlock(RHSBlock);
685
686 Value *RHS = Visit(E->getRHS());
687 Builder.CreateBr(ContBlock);
688 RHSBlock = Builder.GetInsertBlock();
689
690 CGF.EmitBlock(ContBlock);
691
692 // Create a PHI node for the real part.
693 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
694 PN->reserveOperandSpace(2);
695 PN->addIncoming(LHS, LHSBlock);
696 PN->addIncoming(RHS, RHSBlock);
697 return PN;
698}
699
700Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
701 llvm::APSInt CondVal(32);
702 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
703 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
704
705 // Emit the LHS or RHS as appropriate.
706 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
707}
708
709//===----------------------------------------------------------------------===//
710// Entry Point into this File
711//===----------------------------------------------------------------------===//
712
713/// EmitComplexExpr - Emit the computation of the specified expression of
714/// complex type, ignoring the result.
715Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
716 assert(E && !hasAggregateLLVMType(E->getType()) &&
717 "Invalid scalar expression to emit");
718
719 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
720}