blob: 277bcdea2c4eb61a198ffc6923b0012f53a19e89 [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"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
22using namespace clang;
23using namespace CodeGen;
24using llvm::Value;
25
26//===----------------------------------------------------------------------===//
27// Scalar Expression Emitter
28//===----------------------------------------------------------------------===//
29
30struct BinOpInfo {
31 Value *LHS;
32 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000033 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000034 const BinaryOperator *E;
35};
36
37namespace {
38class VISIBILITY_HIDDEN ScalarExprEmitter
39 : public StmtVisitor<ScalarExprEmitter, Value*> {
40 CodeGenFunction &CGF;
Devang Patel638b64c2007-10-09 19:49:58 +000041 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner9fba49a2007-08-24 05:35:26 +000042public:
43
44 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
45 }
46
47
48 //===--------------------------------------------------------------------===//
49 // Utilities
50 //===--------------------------------------------------------------------===//
51
52 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
53 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
54
55 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000056 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000057 }
58
59 /// EmitLoadOfLValue - Given an expression with complex type that represents a
60 /// value l-value, this method emits the address of the l-value, then loads
61 /// and returns the result.
62 Value *EmitLoadOfLValue(const Expr *E) {
63 // FIXME: Volatile
64 return EmitLoadOfLValue(EmitLValue(E), E->getType());
65 }
66
Chris Lattnerd8d44222007-08-26 16:42:57 +000067 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000068 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000069 Value *EmitConversionToBool(Value *Src, QualType DstTy);
70
Chris Lattner4e05d1e2007-08-26 06:48:56 +000071 /// EmitScalarConversion - Emit a conversion from the specified type to the
72 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000073 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
74
75 /// EmitComplexToScalarConversion - Emit a conversion from the specified
76 /// complex type to the specified destination type, where the destination
77 /// type is an LLVM scalar type.
78 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
79 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080
Chris Lattner9fba49a2007-08-24 05:35:26 +000081 //===--------------------------------------------------------------------===//
82 // Visitor Methods
83 //===--------------------------------------------------------------------===//
84
85 Value *VisitStmt(Stmt *S) {
Chris Lattner1aef6212007-09-13 01:17:29 +000086 S->dump(CGF.getContext().SourceMgr);
Chris Lattner9fba49a2007-08-24 05:35:26 +000087 assert(0 && "Stmt can't have complex result type!");
88 return 0;
89 }
90 Value *VisitExpr(Expr *S);
91 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
92
93 // Leaves.
94 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
95 return llvm::ConstantInt::get(E->getValue());
96 }
97 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +000098 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +000099 }
100 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
101 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
102 }
103 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
104 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000105 CGF.getContext().typesAreCompatible(
106 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000107 }
108 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
109 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
110 }
111
112 // l-values.
113 Value *VisitDeclRefExpr(DeclRefExpr *E) {
114 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
115 return llvm::ConstantInt::get(EC->getInitVal());
116 return EmitLoadOfLValue(E);
117 }
118 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
119 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
120 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
121 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
122 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000123
124 Value *VisitInitListExpr(InitListExpr *E) {
Devang Patel01ab1302007-10-24 17:18:43 +0000125 unsigned N = E->getNumInits();
Devang Patel32c39832007-10-24 18:05:48 +0000126 QualType T = E->getInit(0)->getType();
127 Value *V = llvm::UndefValue::get(llvm::VectorType::get(ConvertType(T), N));
Devang Patel01ab1302007-10-24 17:18:43 +0000128 for (unsigned i = 0; i < N; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000129 Value *NewV = Visit(E->getInit(i));
130 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
131 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000132 }
Devang Patel32c39832007-10-24 18:05:48 +0000133 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000134 }
135
136 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
137 return Visit(E->getInitializer());
138 }
139
Chris Lattner9fba49a2007-08-24 05:35:26 +0000140 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
141 Value *VisitCastExpr(const CastExpr *E) {
142 return EmitCastExpr(E->getSubExpr(), E->getType());
143 }
144 Value *EmitCastExpr(const Expr *E, QualType T);
145
146 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000147 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000148 }
149
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000150 Value *VisitStmtExpr(const StmtExpr *E);
151
Chris Lattner9fba49a2007-08-24 05:35:26 +0000152 // Unary Operators.
153 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
154 Value *VisitUnaryPostDec(const UnaryOperator *E) {
155 return VisitPrePostIncDec(E, false, false);
156 }
157 Value *VisitUnaryPostInc(const UnaryOperator *E) {
158 return VisitPrePostIncDec(E, true, false);
159 }
160 Value *VisitUnaryPreDec(const UnaryOperator *E) {
161 return VisitPrePostIncDec(E, false, true);
162 }
163 Value *VisitUnaryPreInc(const UnaryOperator *E) {
164 return VisitPrePostIncDec(E, true, true);
165 }
166 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
167 return EmitLValue(E->getSubExpr()).getAddress();
168 }
169 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
170 Value *VisitUnaryPlus(const UnaryOperator *E) {
171 return Visit(E->getSubExpr());
172 }
173 Value *VisitUnaryMinus (const UnaryOperator *E);
174 Value *VisitUnaryNot (const UnaryOperator *E);
175 Value *VisitUnaryLNot (const UnaryOperator *E);
176 Value *VisitUnarySizeOf (const UnaryOperator *E) {
177 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
178 }
179 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
180 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
181 }
182 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
183 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000184 Value *VisitUnaryReal (const UnaryOperator *E);
185 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000186 Value *VisitUnaryExtension(const UnaryOperator *E) {
187 return Visit(E->getSubExpr());
188 }
189
190 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000191 Value *EmitMul(const BinOpInfo &Ops) {
192 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
193 }
194 Value *EmitDiv(const BinOpInfo &Ops);
195 Value *EmitRem(const BinOpInfo &Ops);
196 Value *EmitAdd(const BinOpInfo &Ops);
197 Value *EmitSub(const BinOpInfo &Ops);
198 Value *EmitShl(const BinOpInfo &Ops);
199 Value *EmitShr(const BinOpInfo &Ops);
200 Value *EmitAnd(const BinOpInfo &Ops) {
201 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
202 }
203 Value *EmitXor(const BinOpInfo &Ops) {
204 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
205 }
206 Value *EmitOr (const BinOpInfo &Ops) {
207 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
208 }
209
Chris Lattner660e31d2007-08-24 21:00:35 +0000210 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000211 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000212 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
213
214 // Binary operators and binary compound assignment operators.
215#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000216 Value *VisitBin ## OP(const BinaryOperator *E) { \
217 return Emit ## OP(EmitBinOps(E)); \
218 } \
219 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
220 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000221 }
222 HANDLEBINOP(Mul);
223 HANDLEBINOP(Div);
224 HANDLEBINOP(Rem);
225 HANDLEBINOP(Add);
226 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
227 HANDLEBINOP(Shl);
228 HANDLEBINOP(Shr);
229 HANDLEBINOP(And);
230 HANDLEBINOP(Xor);
231 HANDLEBINOP(Or);
232#undef HANDLEBINOP
233 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000234 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000235 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
236 }
237
Chris Lattner9fba49a2007-08-24 05:35:26 +0000238 // Comparisons.
239 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
240 unsigned SICmpOpc, unsigned FCmpOpc);
241#define VISITCOMP(CODE, UI, SI, FP) \
242 Value *VisitBin##CODE(const BinaryOperator *E) { \
243 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
244 llvm::FCmpInst::FP); }
245 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
246 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
247 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
248 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
249 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
250 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
251#undef VISITCOMP
252
253 Value *VisitBinAssign (const BinaryOperator *E);
254
255 Value *VisitBinLAnd (const BinaryOperator *E);
256 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000257 Value *VisitBinComma (const BinaryOperator *E);
258
259 // Other Operators.
260 Value *VisitConditionalOperator(const ConditionalOperator *CO);
261 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000262 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000263 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
264 return CGF.EmitObjCStringLiteral(E);
265 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000266 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000267};
268} // end anonymous namespace.
269
270//===----------------------------------------------------------------------===//
271// Utilities
272//===----------------------------------------------------------------------===//
273
Chris Lattnerd8d44222007-08-26 16:42:57 +0000274/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000275/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000276Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
277 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
278
279 if (SrcType->isRealFloatingType()) {
280 // Compare against 0.0 for fp scalars.
281 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000282 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
283 }
284
285 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
286 "Unknown scalar type to convert");
287
288 // Because of the type rules of C, we often end up computing a logical value,
289 // then zero extending it to int, then wanting it as a logical value again.
290 // Optimize this common case.
291 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
292 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
293 Value *Result = ZI->getOperand(0);
294 ZI->eraseFromParent();
295 return Result;
296 }
297 }
298
299 // Compare against an integer or pointer null.
300 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
301 return Builder.CreateICmpNE(Src, Zero, "tobool");
302}
303
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000304/// EmitScalarConversion - Emit a conversion from the specified type to the
305/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000306Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
307 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000308 SrcType = SrcType.getCanonicalType();
309 DstType = DstType.getCanonicalType();
310 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000311
312 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000313
314 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000315 if (DstType->isBooleanType())
316 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000317
318 const llvm::Type *DstTy = ConvertType(DstType);
319
320 // Ignore conversions like int -> uint.
321 if (Src->getType() == DstTy)
322 return Src;
323
324 // Handle pointer conversions next: pointers can only be converted to/from
325 // other pointers and integers.
326 if (isa<PointerType>(DstType)) {
327 // The source value may be an integer, or a pointer.
328 if (isa<llvm::PointerType>(Src->getType()))
329 return Builder.CreateBitCast(Src, DstTy, "conv");
330 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
331 return Builder.CreateIntToPtr(Src, DstTy, "conv");
332 }
333
334 if (isa<PointerType>(SrcType)) {
335 // Must be an ptr to int cast.
336 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
337 return Builder.CreateIntToPtr(Src, DstTy, "conv");
338 }
339
340 // Finally, we have the arithmetic types: real int/float.
341 if (isa<llvm::IntegerType>(Src->getType())) {
342 bool InputSigned = SrcType->isSignedIntegerType();
343 if (isa<llvm::IntegerType>(DstTy))
344 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
345 else if (InputSigned)
346 return Builder.CreateSIToFP(Src, DstTy, "conv");
347 else
348 return Builder.CreateUIToFP(Src, DstTy, "conv");
349 }
350
351 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
352 if (isa<llvm::IntegerType>(DstTy)) {
353 if (DstType->isSignedIntegerType())
354 return Builder.CreateFPToSI(Src, DstTy, "conv");
355 else
356 return Builder.CreateFPToUI(Src, DstTy, "conv");
357 }
358
359 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
360 if (DstTy->getTypeID() < Src->getType()->getTypeID())
361 return Builder.CreateFPTrunc(Src, DstTy, "conv");
362 else
363 return Builder.CreateFPExt(Src, DstTy, "conv");
364}
365
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000366/// EmitComplexToScalarConversion - Emit a conversion from the specified
367/// complex type to the specified destination type, where the destination
368/// type is an LLVM scalar type.
369Value *ScalarExprEmitter::
370EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
371 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000372 // Get the source element type.
373 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
374
375 // Handle conversions to bool first, they are special: comparisons against 0.
376 if (DstTy->isBooleanType()) {
377 // Complex != 0 -> (Real != 0) | (Imag != 0)
378 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
379 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
380 return Builder.CreateOr(Src.first, Src.second, "tobool");
381 }
382
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000383 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
384 // the imaginary part of the complex value is discarded and the value of the
385 // real part is converted according to the conversion rules for the
386 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000387 return EmitScalarConversion(Src.first, SrcTy, DstTy);
388}
389
390
Chris Lattner9fba49a2007-08-24 05:35:26 +0000391//===----------------------------------------------------------------------===//
392// Visitor Methods
393//===----------------------------------------------------------------------===//
394
395Value *ScalarExprEmitter::VisitExpr(Expr *E) {
396 fprintf(stderr, "Unimplemented scalar expr!\n");
Chris Lattner1aef6212007-09-13 01:17:29 +0000397 E->dump(CGF.getContext().SourceMgr);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000398 if (E->getType()->isVoidType())
399 return 0;
400 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
401}
402
403Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
404 // Emit subscript expressions in rvalue context's. For most cases, this just
405 // loads the lvalue formed by the subscript expr. However, we have to be
406 // careful, because the base of a vector subscript is occasionally an rvalue,
407 // so we can't get it as an lvalue.
408 if (!E->getBase()->getType()->isVectorType())
409 return EmitLoadOfLValue(E);
410
411 // Handle the vector case. The base must be a vector, the index must be an
412 // integer value.
413 Value *Base = Visit(E->getBase());
414 Value *Idx = Visit(E->getIdx());
415
416 // FIXME: Convert Idx to i32 type.
417 return Builder.CreateExtractElement(Base, Idx, "vecext");
418}
419
420/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
421/// also handle things like function to pointer-to-function decay, and array to
422/// pointer decay.
423Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
424 const Expr *Op = E->getSubExpr();
425
426 // If this is due to array->pointer conversion, emit the array expression as
427 // an l-value.
428 if (Op->getType()->isArrayType()) {
429 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
430 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000431 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000432
433 assert(isa<llvm::PointerType>(V->getType()) &&
434 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
435 ->getElementType()) &&
436 "Doesn't support VLAs yet!");
437 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000438
439 llvm::Value *Ops[] = {Idx0, Idx0};
440 return Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000441 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000442 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
443 getReferenceeType() ==
444 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000445
446 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000447 }
448
449 return EmitCastExpr(Op, E->getType());
450}
451
452
453// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
454// have to handle a more broad range of conversions than explicit casts, as they
455// handle things like function to ptr-to-function decay etc.
456Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000457 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000458 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000459 Value *Src = Visit(const_cast<Expr*>(E));
460
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000461 // Use EmitScalarConversion to perform the conversion.
462 return EmitScalarConversion(Src, E->getType(), DestTy);
463 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000464
Chris Lattner82e10392007-08-26 07:26:12 +0000465 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000466 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
467 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000468}
469
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000470Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000471 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000472}
473
474
Chris Lattner9fba49a2007-08-24 05:35:26 +0000475//===----------------------------------------------------------------------===//
476// Unary Operators
477//===----------------------------------------------------------------------===//
478
479Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000480 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000481 LValue LV = EmitLValue(E->getSubExpr());
482 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000483 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000484 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000485
486 int AmountVal = isInc ? 1 : -1;
487
488 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000489 if (isa<llvm::PointerType>(InVal->getType())) {
490 // FIXME: This isn't right for VLAs.
491 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
492 NextVal = Builder.CreateGEP(InVal, NextVal);
493 } else {
494 // Add the inc/dec to the real part.
495 if (isa<llvm::IntegerType>(InVal->getType()))
496 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000497 else if (InVal->getType() == llvm::Type::FloatTy)
498 // FIXME: Handle long double.
499 NextVal = llvm::ConstantFP::get(InVal->getType(),
500 llvm::APFloat(static_cast<float>(AmountVal)));
501 else {
502 // FIXME: Handle long double.
503 assert(InVal->getType() == llvm::Type::DoubleTy);
504 NextVal = llvm::ConstantFP::get(InVal->getType(),
505 llvm::APFloat(static_cast<double>(AmountVal)));
506 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000507 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
508 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000509
510 // Store the updated result through the lvalue.
511 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
512 E->getSubExpr()->getType());
513
514 // If this is a postinc, return the value read from memory, otherwise use the
515 // updated value.
516 return isPre ? NextVal : InVal;
517}
518
519
520Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
521 Value *Op = Visit(E->getSubExpr());
522 return Builder.CreateNeg(Op, "neg");
523}
524
525Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
526 Value *Op = Visit(E->getSubExpr());
527 return Builder.CreateNot(Op, "neg");
528}
529
530Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
531 // Compare operand to zero.
532 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
533
534 // Invert value.
535 // TODO: Could dynamically modify easy computations here. For example, if
536 // the operand is an icmp ne, turn into icmp eq.
537 BoolVal = Builder.CreateNot(BoolVal, "lnot");
538
539 // ZExt result to int.
540 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
541}
542
543/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
544/// an integer (RetType).
545Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000546 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000547 /// FIXME: This doesn't handle VLAs yet!
548 std::pair<uint64_t, unsigned> Info =
549 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
550
551 uint64_t Val = isSizeOf ? Info.first : Info.second;
552 Val /= 8; // Return size in bytes, not bits.
553
554 assert(RetType->isIntegerType() && "Result type must be an integer!");
555
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000556 uint32_t ResultWidth = static_cast<uint32_t>(
557 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000558 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
559}
560
Chris Lattner01211af2007-08-24 21:20:17 +0000561Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
562 Expr *Op = E->getSubExpr();
563 if (Op->getType()->isComplexType())
564 return CGF.EmitComplexExpr(Op).first;
565 return Visit(Op);
566}
567Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
568 Expr *Op = E->getSubExpr();
569 if (Op->getType()->isComplexType())
570 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000571
572 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
573 // effects are evaluated.
574 CGF.EmitScalarExpr(Op);
575 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000576}
577
578
Chris Lattner9fba49a2007-08-24 05:35:26 +0000579//===----------------------------------------------------------------------===//
580// Binary Operators
581//===----------------------------------------------------------------------===//
582
583BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
584 BinOpInfo Result;
585 Result.LHS = Visit(E->getLHS());
586 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000587 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000588 Result.E = E;
589 return Result;
590}
591
Chris Lattner0d965302007-08-26 21:41:21 +0000592Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000593 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
594 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
595
596 BinOpInfo OpInfo;
597
598 // Load the LHS and RHS operands.
599 LValue LHSLV = EmitLValue(E->getLHS());
600 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000601
602 // Determine the computation type. If the RHS is complex, then this is one of
603 // the add/sub/mul/div operators. All of these operators can be computed in
604 // with just their real component even though the computation domain really is
605 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000606 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000607
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000608 // If the computation type is complex, then the RHS is complex. Emit the RHS.
609 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
610 ComputeType = CT->getElementType();
611
612 // Emit the RHS, only keeping the real component.
613 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
614 RHSTy = RHSTy->getAsComplexType()->getElementType();
615 } else {
616 // Otherwise the RHS is a simple scalar value.
617 OpInfo.RHS = Visit(E->getRHS());
618 }
619
620 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000621 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000622
Devang Patel04011802007-10-25 22:19:13 +0000623 // Do not merge types for -= or += where the LHS is a pointer.
624 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000625 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000626 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000627 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000628 }
629 OpInfo.Ty = ComputeType;
630 OpInfo.E = E;
631
632 // Expand the binary operator.
633 Value *Result = (this->*Func)(OpInfo);
634
635 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000636 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000637
638 // Store the result value into the LHS lvalue.
639 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
640
641 return Result;
642}
643
644
Chris Lattner9fba49a2007-08-24 05:35:26 +0000645Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
646 if (Ops.LHS->getType()->isFloatingPoint())
647 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000648 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000649 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
650 else
651 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
652}
653
654Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
655 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000656 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000657 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
658 else
659 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
660}
661
662
663Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000664 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000665 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000666
667 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000668 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
669 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
670 // int + pointer
671 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
672}
673
674Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
675 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
676 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
677
Chris Lattner660e31d2007-08-24 21:00:35 +0000678 // pointer - int
679 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
680 "ptr-ptr shouldn't get here");
681 // FIXME: The pointer could point to a VLA.
682 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
683 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
684}
685
686Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
687 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
688 // the compound assignment case it is invalid, so just handle it here.
689 if (!E->getRHS()->getType()->isPointerType())
690 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000691
692 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000693 Value *LHS = Visit(E->getLHS());
694 Value *RHS = Visit(E->getRHS());
695
696 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
697 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
698 "Can't subtract different pointer types");
699
Chris Lattner9fba49a2007-08-24 05:35:26 +0000700 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000701 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
702 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000703
704 const llvm::Type *ResultType = ConvertType(E->getType());
705 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
706 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
707 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000708
709 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
710 // remainder. As such, we handle common power-of-two cases here to generate
711 // better code.
712 if (llvm::isPowerOf2_64(ElementSize)) {
713 Value *ShAmt =
714 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
715 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
716 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000717
Chris Lattner9fba49a2007-08-24 05:35:26 +0000718 // Otherwise, do a full sdiv.
719 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
720 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
721}
722
Chris Lattner660e31d2007-08-24 21:00:35 +0000723
Chris Lattner9fba49a2007-08-24 05:35:26 +0000724Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
725 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
726 // RHS to the same size as the LHS.
727 Value *RHS = Ops.RHS;
728 if (Ops.LHS->getType() != RHS->getType())
729 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
730
731 return Builder.CreateShl(Ops.LHS, RHS, "shl");
732}
733
734Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
735 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
736 // RHS to the same size as the LHS.
737 Value *RHS = Ops.RHS;
738 if (Ops.LHS->getType() != RHS->getType())
739 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
740
Chris Lattner660e31d2007-08-24 21:00:35 +0000741 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000742 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
743 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
744}
745
746Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
747 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000748 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000749 QualType LHSTy = E->getLHS()->getType();
750 if (!LHSTy->isComplexType()) {
751 Value *LHS = Visit(E->getLHS());
752 Value *RHS = Visit(E->getRHS());
753
754 if (LHS->getType()->isFloatingPoint()) {
755 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
756 LHS, RHS, "cmp");
757 } else if (LHSTy->isUnsignedIntegerType()) {
758 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
759 LHS, RHS, "cmp");
760 } else {
761 // Signed integers and pointers.
762 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
763 LHS, RHS, "cmp");
764 }
765 } else {
766 // Complex Comparison: can only be an equality comparison.
767 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
768 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
769
770 QualType CETy =
771 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
772
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000773 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000774 if (CETy->isRealFloatingType()) {
775 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
776 LHS.first, RHS.first, "cmp.r");
777 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
778 LHS.second, RHS.second, "cmp.i");
779 } else {
780 // Complex comparisons can only be equality comparisons. As such, signed
781 // and unsigned opcodes are the same.
782 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
783 LHS.first, RHS.first, "cmp.r");
784 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
785 LHS.second, RHS.second, "cmp.i");
786 }
787
788 if (E->getOpcode() == BinaryOperator::EQ) {
789 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
790 } else {
791 assert(E->getOpcode() == BinaryOperator::NE &&
792 "Complex comparison other than == or != ?");
793 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
794 }
795 }
796
797 // ZExt result to int.
798 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
799}
800
801Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
802 LValue LHS = EmitLValue(E->getLHS());
803 Value *RHS = Visit(E->getRHS());
804
805 // Store the value into the LHS.
806 // FIXME: Volatility!
807 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
808
809 // Return the RHS.
810 return RHS;
811}
812
813Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
814 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
815
816 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
817 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
818
819 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
820 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
821
822 CGF.EmitBlock(RHSBlock);
823 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
824
825 // Reaquire the RHS block, as there may be subblocks inserted.
826 RHSBlock = Builder.GetInsertBlock();
827 CGF.EmitBlock(ContBlock);
828
829 // Create a PHI node. If we just evaluted the LHS condition, the result is
830 // false. If we evaluated both, the result is the RHS condition.
831 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
832 PN->reserveOperandSpace(2);
833 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
834 PN->addIncoming(RHSCond, RHSBlock);
835
836 // ZExt result to int.
837 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
838}
839
840Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
841 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
842
843 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
844 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
845
846 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
847 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
848
849 CGF.EmitBlock(RHSBlock);
850 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
851
852 // Reaquire the RHS block, as there may be subblocks inserted.
853 RHSBlock = Builder.GetInsertBlock();
854 CGF.EmitBlock(ContBlock);
855
856 // Create a PHI node. If we just evaluted the LHS condition, the result is
857 // true. If we evaluated both, the result is the RHS condition.
858 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
859 PN->reserveOperandSpace(2);
860 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
861 PN->addIncoming(RHSCond, RHSBlock);
862
863 // ZExt result to int.
864 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
865}
866
867Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
868 CGF.EmitStmt(E->getLHS());
869 return Visit(E->getRHS());
870}
871
872//===----------------------------------------------------------------------===//
873// Other Operators
874//===----------------------------------------------------------------------===//
875
876Value *ScalarExprEmitter::
877VisitConditionalOperator(const ConditionalOperator *E) {
878 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
879 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
880 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
881
882 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
883 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
884
885 CGF.EmitBlock(LHSBlock);
886
887 // Handle the GNU extension for missing LHS.
888 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
889 Builder.CreateBr(ContBlock);
890 LHSBlock = Builder.GetInsertBlock();
891
892 CGF.EmitBlock(RHSBlock);
893
894 Value *RHS = Visit(E->getRHS());
895 Builder.CreateBr(ContBlock);
896 RHSBlock = Builder.GetInsertBlock();
897
898 CGF.EmitBlock(ContBlock);
899
900 // Create a PHI node for the real part.
901 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
902 PN->reserveOperandSpace(2);
903 PN->addIncoming(LHS, LHSBlock);
904 PN->addIncoming(RHS, RHSBlock);
905 return PN;
906}
907
908Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000909 // Emit the LHS or RHS as appropriate.
Chris Lattnerf624cd22007-10-25 00:29:32 +0000910 return Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000911}
912
Anders Carlsson36760332007-10-15 20:28:48 +0000913Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE)
914{
915 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
916
917 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
918 return V;
919}
920
Anders Carlsson36f07d82007-10-29 05:01:08 +0000921Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
922{
923 std::string str;
924
925 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
926
927 llvm::Constant *C = llvm::ConstantArray::get(str);
928 C = new llvm::GlobalVariable(C->getType(), true,
929 llvm::GlobalValue::InternalLinkage,
930 C, ".str", &CGF.CGM.getModule());
931 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
932 llvm::Constant *Zeros[] = { Zero, Zero };
933 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
934
935 return C;
936}
937
Chris Lattner9fba49a2007-08-24 05:35:26 +0000938//===----------------------------------------------------------------------===//
939// Entry Point into this File
940//===----------------------------------------------------------------------===//
941
942/// EmitComplexExpr - Emit the computation of the specified expression of
943/// complex type, ignoring the result.
944Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
945 assert(E && !hasAggregateLLVMType(E->getType()) &&
946 "Invalid scalar expression to emit");
947
948 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
949}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000950
951/// EmitScalarConversion - Emit a conversion from the specified type to the
952/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000953Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
954 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000955 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
956 "Invalid scalar expression to emit");
957 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
958}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000959
960/// EmitComplexToScalarConversion - Emit a conversion from the specified
961/// complex type to the specified destination type, where the destination
962/// type is an LLVM scalar type.
963Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
964 QualType SrcTy,
965 QualType DstTy) {
966 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
967 "Invalid complex -> scalar conversion");
968 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
969 DstTy);
970}