blob: f20c43f52285872dbca65a5be2603a3b147a2fad [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"
Ted Kremenek03cf4df2007-12-10 23:44:32 +000022#include <stdarg.h>
23
Chris Lattner9fba49a2007-08-24 05:35:26 +000024using namespace clang;
25using namespace CodeGen;
26using llvm::Value;
27
28//===----------------------------------------------------------------------===//
29// Scalar Expression Emitter
30//===----------------------------------------------------------------------===//
31
32struct BinOpInfo {
33 Value *LHS;
34 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000035 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000036 const BinaryOperator *E;
37};
38
39namespace {
40class VISIBILITY_HIDDEN ScalarExprEmitter
41 : public StmtVisitor<ScalarExprEmitter, Value*> {
42 CodeGenFunction &CGF;
Devang Patel638b64c2007-10-09 19:49:58 +000043 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner9fba49a2007-08-24 05:35:26 +000044public:
45
46 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
47 }
48
49
50 //===--------------------------------------------------------------------===//
51 // Utilities
52 //===--------------------------------------------------------------------===//
53
54 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
55 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
56
57 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000058 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000059 }
60
61 /// EmitLoadOfLValue - Given an expression with complex type that represents a
62 /// value l-value, this method emits the address of the l-value, then loads
63 /// and returns the result.
64 Value *EmitLoadOfLValue(const Expr *E) {
65 // FIXME: Volatile
66 return EmitLoadOfLValue(EmitLValue(E), E->getType());
67 }
68
Chris Lattnerd8d44222007-08-26 16:42:57 +000069 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000070 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000071 Value *EmitConversionToBool(Value *Src, QualType DstTy);
72
Chris Lattner4e05d1e2007-08-26 06:48:56 +000073 /// EmitScalarConversion - Emit a conversion from the specified type to the
74 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000075 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
76
77 /// EmitComplexToScalarConversion - Emit a conversion from the specified
78 /// complex type to the specified destination type, where the destination
79 /// type is an LLVM scalar type.
80 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
81 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000082
Chris Lattner9fba49a2007-08-24 05:35:26 +000083 //===--------------------------------------------------------------------===//
84 // Visitor Methods
85 //===--------------------------------------------------------------------===//
86
87 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000088 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000089 assert(0 && "Stmt can't have complex result type!");
90 return 0;
91 }
92 Value *VisitExpr(Expr *S);
93 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
94
95 // Leaves.
96 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
97 return llvm::ConstantInt::get(E->getValue());
98 }
99 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +0000100 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000101 }
102 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
103 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
104 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000105 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
106 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
107 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
109 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000110 CGF.getContext().typesAreCompatible(
111 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000112 }
113 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
114 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
115 }
116
117 // l-values.
118 Value *VisitDeclRefExpr(DeclRefExpr *E) {
119 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
120 return llvm::ConstantInt::get(EC->getInitVal());
121 return EmitLoadOfLValue(E);
122 }
123 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
124 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
125 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
126 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
127 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000128
129 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000130 unsigned NumInitElements = E->getNumInits();
131
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000132 const llvm::VectorType *VType =
133 cast<llvm::VectorType>(ConvertType(E->getType()));
134
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000135 unsigned NumVectorElements = VType->getNumElements();
136 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000137
138 // Emit individual vector element stores.
139 llvm::Value *V = llvm::UndefValue::get(VType);
140
Anders Carlsson323d5682007-12-18 02:45:33 +0000141 // Emit initializers
142 unsigned i;
143 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000144 Value *NewV = Visit(E->getInit(i));
145 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
146 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000147 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000148
149 // Emit remaining default initializers
150 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
151 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
152 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
153 V = Builder.CreateInsertElement(V, NewV, Idx);
154 }
155
Devang Patel32c39832007-10-24 18:05:48 +0000156 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000157 }
158
159 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
160 return Visit(E->getInitializer());
161 }
162
Chris Lattner9fba49a2007-08-24 05:35:26 +0000163 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
164 Value *VisitCastExpr(const CastExpr *E) {
165 return EmitCastExpr(E->getSubExpr(), E->getType());
166 }
167 Value *EmitCastExpr(const Expr *E, QualType T);
168
169 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000170 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000171 }
172
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000173 Value *VisitStmtExpr(const StmtExpr *E);
174
Chris Lattner9fba49a2007-08-24 05:35:26 +0000175 // Unary Operators.
176 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
177 Value *VisitUnaryPostDec(const UnaryOperator *E) {
178 return VisitPrePostIncDec(E, false, false);
179 }
180 Value *VisitUnaryPostInc(const UnaryOperator *E) {
181 return VisitPrePostIncDec(E, true, false);
182 }
183 Value *VisitUnaryPreDec(const UnaryOperator *E) {
184 return VisitPrePostIncDec(E, false, true);
185 }
186 Value *VisitUnaryPreInc(const UnaryOperator *E) {
187 return VisitPrePostIncDec(E, true, true);
188 }
189 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
190 return EmitLValue(E->getSubExpr()).getAddress();
191 }
192 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
193 Value *VisitUnaryPlus(const UnaryOperator *E) {
194 return Visit(E->getSubExpr());
195 }
196 Value *VisitUnaryMinus (const UnaryOperator *E);
197 Value *VisitUnaryNot (const UnaryOperator *E);
198 Value *VisitUnaryLNot (const UnaryOperator *E);
199 Value *VisitUnarySizeOf (const UnaryOperator *E) {
200 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
201 }
202 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
203 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
204 }
205 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
206 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000207 Value *VisitUnaryReal (const UnaryOperator *E);
208 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000209 Value *VisitUnaryExtension(const UnaryOperator *E) {
210 return Visit(E->getSubExpr());
211 }
212
213 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000214 Value *EmitMul(const BinOpInfo &Ops) {
215 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
216 }
217 Value *EmitDiv(const BinOpInfo &Ops);
218 Value *EmitRem(const BinOpInfo &Ops);
219 Value *EmitAdd(const BinOpInfo &Ops);
220 Value *EmitSub(const BinOpInfo &Ops);
221 Value *EmitShl(const BinOpInfo &Ops);
222 Value *EmitShr(const BinOpInfo &Ops);
223 Value *EmitAnd(const BinOpInfo &Ops) {
224 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
225 }
226 Value *EmitXor(const BinOpInfo &Ops) {
227 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
228 }
229 Value *EmitOr (const BinOpInfo &Ops) {
230 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
231 }
232
Chris Lattner660e31d2007-08-24 21:00:35 +0000233 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000234 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000235 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
236
237 // Binary operators and binary compound assignment operators.
238#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000239 Value *VisitBin ## OP(const BinaryOperator *E) { \
240 return Emit ## OP(EmitBinOps(E)); \
241 } \
242 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
243 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000244 }
245 HANDLEBINOP(Mul);
246 HANDLEBINOP(Div);
247 HANDLEBINOP(Rem);
248 HANDLEBINOP(Add);
249 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
250 HANDLEBINOP(Shl);
251 HANDLEBINOP(Shr);
252 HANDLEBINOP(And);
253 HANDLEBINOP(Xor);
254 HANDLEBINOP(Or);
255#undef HANDLEBINOP
256 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000257 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000258 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
259 }
260
Chris Lattner9fba49a2007-08-24 05:35:26 +0000261 // Comparisons.
262 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
263 unsigned SICmpOpc, unsigned FCmpOpc);
264#define VISITCOMP(CODE, UI, SI, FP) \
265 Value *VisitBin##CODE(const BinaryOperator *E) { \
266 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
267 llvm::FCmpInst::FP); }
268 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
269 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
270 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
271 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
272 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
273 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
274#undef VISITCOMP
275
276 Value *VisitBinAssign (const BinaryOperator *E);
277
278 Value *VisitBinLAnd (const BinaryOperator *E);
279 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000280 Value *VisitBinComma (const BinaryOperator *E);
281
282 // Other Operators.
283 Value *VisitConditionalOperator(const ConditionalOperator *CO);
284 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000285 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000286 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
287 return CGF.EmitObjCStringLiteral(E);
288 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000289 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000290};
291} // end anonymous namespace.
292
293//===----------------------------------------------------------------------===//
294// Utilities
295//===----------------------------------------------------------------------===//
296
Chris Lattnerd8d44222007-08-26 16:42:57 +0000297/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000298/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000299Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
300 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
301
302 if (SrcType->isRealFloatingType()) {
303 // Compare against 0.0 for fp scalars.
304 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000305 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
306 }
307
308 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
309 "Unknown scalar type to convert");
310
311 // Because of the type rules of C, we often end up computing a logical value,
312 // then zero extending it to int, then wanting it as a logical value again.
313 // Optimize this common case.
314 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
315 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
316 Value *Result = ZI->getOperand(0);
317 ZI->eraseFromParent();
318 return Result;
319 }
320 }
321
322 // Compare against an integer or pointer null.
323 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
324 return Builder.CreateICmpNE(Src, Zero, "tobool");
325}
326
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000327/// EmitScalarConversion - Emit a conversion from the specified type to the
328/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000329Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
330 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000331 SrcType = SrcType.getCanonicalType();
332 DstType = DstType.getCanonicalType();
333 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000334
335 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000336
337 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000338 if (DstType->isBooleanType())
339 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000340
341 const llvm::Type *DstTy = ConvertType(DstType);
342
343 // Ignore conversions like int -> uint.
344 if (Src->getType() == DstTy)
345 return Src;
346
347 // Handle pointer conversions next: pointers can only be converted to/from
348 // other pointers and integers.
349 if (isa<PointerType>(DstType)) {
350 // The source value may be an integer, or a pointer.
351 if (isa<llvm::PointerType>(Src->getType()))
352 return Builder.CreateBitCast(Src, DstTy, "conv");
353 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
354 return Builder.CreateIntToPtr(Src, DstTy, "conv");
355 }
356
357 if (isa<PointerType>(SrcType)) {
358 // Must be an ptr to int cast.
359 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000360 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000361 }
362
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000363 if (isa<llvm::VectorType>(Src->getType()) ||
364 isa<llvm::VectorType>(DstTy)) {
365 return Builder.CreateBitCast(Src, DstTy, "conv");
366 }
367
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000368 // Finally, we have the arithmetic types: real int/float.
369 if (isa<llvm::IntegerType>(Src->getType())) {
370 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000371 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
372 if (isa<llvm::IntegerType>(DstTy))
373 return llvm::ConstantExpr::getIntegerCast(C, DstTy, InputSigned);
374 else if (InputSigned)
375 return llvm::ConstantExpr::getSIToFP(C, DstTy);
376 else
377 return llvm::ConstantExpr::getUIToFP(C, DstTy);
378 } else {
379 if (isa<llvm::IntegerType>(DstTy))
380 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
381 else if (InputSigned)
382 return Builder.CreateSIToFP(Src, DstTy, "conv");
383 else
384 return Builder.CreateUIToFP(Src, DstTy, "conv");
385 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000386 }
387
388 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
389 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000390 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
391 if (DstType->isSignedIntegerType())
392 return llvm::ConstantExpr::getFPToSI(C, DstTy);
393 else
394 return llvm::ConstantExpr::getFPToUI(C, DstTy);
395 } else {
396 if (DstType->isSignedIntegerType())
397 return Builder.CreateFPToSI(Src, DstTy, "conv");
398 else
399 return Builder.CreateFPToUI(Src, DstTy, "conv");
400 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000401 }
402
403 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000404 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
405 if (DstTy->getTypeID() < Src->getType()->getTypeID())
406 return llvm::ConstantExpr::getFPTrunc(C, DstTy);
407 else
408 return llvm::ConstantExpr::getFPExtend(C, DstTy);
409 } else {
410 if (DstTy->getTypeID() < Src->getType()->getTypeID())
411 return Builder.CreateFPTrunc(Src, DstTy, "conv");
412 else
413 return Builder.CreateFPExt(Src, DstTy, "conv");
414 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000415}
416
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000417/// EmitComplexToScalarConversion - Emit a conversion from the specified
418/// complex type to the specified destination type, where the destination
419/// type is an LLVM scalar type.
420Value *ScalarExprEmitter::
421EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
422 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000423 // Get the source element type.
424 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
425
426 // Handle conversions to bool first, they are special: comparisons against 0.
427 if (DstTy->isBooleanType()) {
428 // Complex != 0 -> (Real != 0) | (Imag != 0)
429 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
430 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
431 return Builder.CreateOr(Src.first, Src.second, "tobool");
432 }
433
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000434 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
435 // the imaginary part of the complex value is discarded and the value of the
436 // real part is converted according to the conversion rules for the
437 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000438 return EmitScalarConversion(Src.first, SrcTy, DstTy);
439}
440
441
Chris Lattner9fba49a2007-08-24 05:35:26 +0000442//===----------------------------------------------------------------------===//
443// Visitor Methods
444//===----------------------------------------------------------------------===//
445
446Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000447 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000448 if (E->getType()->isVoidType())
449 return 0;
450 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
451}
452
453Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
454 // Emit subscript expressions in rvalue context's. For most cases, this just
455 // loads the lvalue formed by the subscript expr. However, we have to be
456 // careful, because the base of a vector subscript is occasionally an rvalue,
457 // so we can't get it as an lvalue.
458 if (!E->getBase()->getType()->isVectorType())
459 return EmitLoadOfLValue(E);
460
461 // Handle the vector case. The base must be a vector, the index must be an
462 // integer value.
463 Value *Base = Visit(E->getBase());
464 Value *Idx = Visit(E->getIdx());
465
466 // FIXME: Convert Idx to i32 type.
467 return Builder.CreateExtractElement(Base, Idx, "vecext");
468}
469
470/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
471/// also handle things like function to pointer-to-function decay, and array to
472/// pointer decay.
473Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
474 const Expr *Op = E->getSubExpr();
475
476 // If this is due to array->pointer conversion, emit the array expression as
477 // an l-value.
478 if (Op->getType()->isArrayType()) {
479 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
480 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000481 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000482
483 assert(isa<llvm::PointerType>(V->getType()) &&
484 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
485 ->getElementType()) &&
486 "Doesn't support VLAs yet!");
487 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000488
489 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000490 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
491
492 // The resultant pointer type can be implicitly casted to other pointer
493 // types as well, for example void*.
494 const llvm::Type *DestPTy = ConvertType(E->getType());
495 assert(isa<llvm::PointerType>(DestPTy) &&
496 "Only expect implicit cast to pointer");
497 if (V->getType() != DestPTy)
498 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
499 return V;
500
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000501 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000502 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
503 getReferenceeType() ==
504 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000505
506 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000507 }
508
509 return EmitCastExpr(Op, E->getType());
510}
511
512
513// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
514// have to handle a more broad range of conversions than explicit casts, as they
515// handle things like function to ptr-to-function decay etc.
516Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000517 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000518 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000519 Value *Src = Visit(const_cast<Expr*>(E));
520
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000521 // Use EmitScalarConversion to perform the conversion.
522 return EmitScalarConversion(Src, E->getType(), DestTy);
523 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000524
Chris Lattner82e10392007-08-26 07:26:12 +0000525 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000526 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
527 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000528}
529
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000530Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000531 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000532}
533
534
Chris Lattner9fba49a2007-08-24 05:35:26 +0000535//===----------------------------------------------------------------------===//
536// Unary Operators
537//===----------------------------------------------------------------------===//
538
539Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000540 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000541 LValue LV = EmitLValue(E->getSubExpr());
542 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000543 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000544 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000545
546 int AmountVal = isInc ? 1 : -1;
547
548 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000549 if (isa<llvm::PointerType>(InVal->getType())) {
550 // FIXME: This isn't right for VLAs.
551 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
552 NextVal = Builder.CreateGEP(InVal, NextVal);
553 } else {
554 // Add the inc/dec to the real part.
555 if (isa<llvm::IntegerType>(InVal->getType()))
556 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000557 else if (InVal->getType() == llvm::Type::FloatTy)
558 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000559 NextVal =
560 llvm::ConstantFP::get(InVal->getType(),
561 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000562 else {
563 // FIXME: Handle long double.
564 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000565 NextVal =
566 llvm::ConstantFP::get(InVal->getType(),
567 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000568 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000569 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
570 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000571
572 // Store the updated result through the lvalue.
573 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
574 E->getSubExpr()->getType());
575
576 // If this is a postinc, return the value read from memory, otherwise use the
577 // updated value.
578 return isPre ? NextVal : InVal;
579}
580
581
582Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
583 Value *Op = Visit(E->getSubExpr());
584 return Builder.CreateNeg(Op, "neg");
585}
586
587Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
588 Value *Op = Visit(E->getSubExpr());
589 return Builder.CreateNot(Op, "neg");
590}
591
592Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
593 // Compare operand to zero.
594 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
595
596 // Invert value.
597 // TODO: Could dynamically modify easy computations here. For example, if
598 // the operand is an icmp ne, turn into icmp eq.
599 BoolVal = Builder.CreateNot(BoolVal, "lnot");
600
601 // ZExt result to int.
602 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
603}
604
605/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
606/// an integer (RetType).
607Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000608 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000609 /// FIXME: This doesn't handle VLAs yet!
610 std::pair<uint64_t, unsigned> Info =
611 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
612
613 uint64_t Val = isSizeOf ? Info.first : Info.second;
614 Val /= 8; // Return size in bytes, not bits.
615
616 assert(RetType->isIntegerType() && "Result type must be an integer!");
617
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000618 uint32_t ResultWidth = static_cast<uint32_t>(
619 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000620 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
621}
622
Chris Lattner01211af2007-08-24 21:20:17 +0000623Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
624 Expr *Op = E->getSubExpr();
625 if (Op->getType()->isComplexType())
626 return CGF.EmitComplexExpr(Op).first;
627 return Visit(Op);
628}
629Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
630 Expr *Op = E->getSubExpr();
631 if (Op->getType()->isComplexType())
632 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000633
634 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
635 // effects are evaluated.
636 CGF.EmitScalarExpr(Op);
637 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000638}
639
640
Chris Lattner9fba49a2007-08-24 05:35:26 +0000641//===----------------------------------------------------------------------===//
642// Binary Operators
643//===----------------------------------------------------------------------===//
644
645BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
646 BinOpInfo Result;
647 Result.LHS = Visit(E->getLHS());
648 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000649 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000650 Result.E = E;
651 return Result;
652}
653
Chris Lattner0d965302007-08-26 21:41:21 +0000654Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000655 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
656 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
657
658 BinOpInfo OpInfo;
659
660 // Load the LHS and RHS operands.
661 LValue LHSLV = EmitLValue(E->getLHS());
662 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000663
664 // Determine the computation type. If the RHS is complex, then this is one of
665 // the add/sub/mul/div operators. All of these operators can be computed in
666 // with just their real component even though the computation domain really is
667 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000668 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000669
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000670 // If the computation type is complex, then the RHS is complex. Emit the RHS.
671 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
672 ComputeType = CT->getElementType();
673
674 // Emit the RHS, only keeping the real component.
675 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
676 RHSTy = RHSTy->getAsComplexType()->getElementType();
677 } else {
678 // Otherwise the RHS is a simple scalar value.
679 OpInfo.RHS = Visit(E->getRHS());
680 }
681
682 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000683 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000684
Devang Patel04011802007-10-25 22:19:13 +0000685 // Do not merge types for -= or += where the LHS is a pointer.
686 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000687 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000688 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000689 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000690 }
691 OpInfo.Ty = ComputeType;
692 OpInfo.E = E;
693
694 // Expand the binary operator.
695 Value *Result = (this->*Func)(OpInfo);
696
697 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000698 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000699
700 // Store the result value into the LHS lvalue.
701 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
702
703 return Result;
704}
705
706
Chris Lattner9fba49a2007-08-24 05:35:26 +0000707Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
708 if (Ops.LHS->getType()->isFloatingPoint())
709 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000710 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000711 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
712 else
713 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
714}
715
716Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
717 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000718 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000719 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
720 else
721 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
722}
723
724
725Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000726 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000727 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000728
729 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000730 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
731 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
732 // int + pointer
733 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
734}
735
736Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
737 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
738 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
739
Chris Lattner660e31d2007-08-24 21:00:35 +0000740 // pointer - int
741 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
742 "ptr-ptr shouldn't get here");
743 // FIXME: The pointer could point to a VLA.
744 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
745 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
746}
747
748Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
749 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
750 // the compound assignment case it is invalid, so just handle it here.
751 if (!E->getRHS()->getType()->isPointerType())
752 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000753
754 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000755 Value *LHS = Visit(E->getLHS());
756 Value *RHS = Visit(E->getRHS());
757
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000758 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
759 const QualType RHSType = E->getRHS()->getType().getCanonicalType();
760 assert(LHSType == RHSType && "Can't subtract different pointer types");
Chris Lattner660e31d2007-08-24 21:00:35 +0000761
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000762 QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000763 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
764 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000765
766 const llvm::Type *ResultType = ConvertType(E->getType());
767 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
768 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
769 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000770
771 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
772 // remainder. As such, we handle common power-of-two cases here to generate
773 // better code.
774 if (llvm::isPowerOf2_64(ElementSize)) {
775 Value *ShAmt =
776 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
777 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
778 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000779
Chris Lattner9fba49a2007-08-24 05:35:26 +0000780 // Otherwise, do a full sdiv.
781 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
782 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
783}
784
Chris Lattner660e31d2007-08-24 21:00:35 +0000785
Chris Lattner9fba49a2007-08-24 05:35:26 +0000786Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
787 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
788 // RHS to the same size as the LHS.
789 Value *RHS = Ops.RHS;
790 if (Ops.LHS->getType() != RHS->getType())
791 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
792
793 return Builder.CreateShl(Ops.LHS, RHS, "shl");
794}
795
796Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
797 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
798 // RHS to the same size as the LHS.
799 Value *RHS = Ops.RHS;
800 if (Ops.LHS->getType() != RHS->getType())
801 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
802
Chris Lattner660e31d2007-08-24 21:00:35 +0000803 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000804 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
805 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
806}
807
808Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
809 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000810 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000811 QualType LHSTy = E->getLHS()->getType();
812 if (!LHSTy->isComplexType()) {
813 Value *LHS = Visit(E->getLHS());
814 Value *RHS = Visit(E->getRHS());
815
816 if (LHS->getType()->isFloatingPoint()) {
817 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
818 LHS, RHS, "cmp");
819 } else if (LHSTy->isUnsignedIntegerType()) {
820 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
821 LHS, RHS, "cmp");
822 } else {
823 // Signed integers and pointers.
824 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
825 LHS, RHS, "cmp");
826 }
827 } else {
828 // Complex Comparison: can only be an equality comparison.
829 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
830 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
831
832 QualType CETy =
833 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
834
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000835 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000836 if (CETy->isRealFloatingType()) {
837 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
838 LHS.first, RHS.first, "cmp.r");
839 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
840 LHS.second, RHS.second, "cmp.i");
841 } else {
842 // Complex comparisons can only be equality comparisons. As such, signed
843 // and unsigned opcodes are the same.
844 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
845 LHS.first, RHS.first, "cmp.r");
846 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
847 LHS.second, RHS.second, "cmp.i");
848 }
849
850 if (E->getOpcode() == BinaryOperator::EQ) {
851 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
852 } else {
853 assert(E->getOpcode() == BinaryOperator::NE &&
854 "Complex comparison other than == or != ?");
855 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
856 }
857 }
858
859 // ZExt result to int.
860 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
861}
862
863Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
864 LValue LHS = EmitLValue(E->getLHS());
865 Value *RHS = Visit(E->getRHS());
866
867 // Store the value into the LHS.
868 // FIXME: Volatility!
869 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
870
871 // Return the RHS.
872 return RHS;
873}
874
875Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
876 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
877
878 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
879 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
880
881 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
882 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
883
884 CGF.EmitBlock(RHSBlock);
885 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
886
887 // Reaquire the RHS block, as there may be subblocks inserted.
888 RHSBlock = Builder.GetInsertBlock();
889 CGF.EmitBlock(ContBlock);
890
891 // Create a PHI node. If we just evaluted the LHS condition, the result is
892 // false. If we evaluated both, the result is the RHS condition.
893 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
894 PN->reserveOperandSpace(2);
895 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
896 PN->addIncoming(RHSCond, RHSBlock);
897
898 // ZExt result to int.
899 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
900}
901
902Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
903 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
904
905 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
906 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
907
908 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
909 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
910
911 CGF.EmitBlock(RHSBlock);
912 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
913
914 // Reaquire the RHS block, as there may be subblocks inserted.
915 RHSBlock = Builder.GetInsertBlock();
916 CGF.EmitBlock(ContBlock);
917
918 // Create a PHI node. If we just evaluted the LHS condition, the result is
919 // true. If we evaluated both, the result is the RHS condition.
920 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
921 PN->reserveOperandSpace(2);
922 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
923 PN->addIncoming(RHSCond, RHSBlock);
924
925 // ZExt result to int.
926 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
927}
928
929Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
930 CGF.EmitStmt(E->getLHS());
931 return Visit(E->getRHS());
932}
933
934//===----------------------------------------------------------------------===//
935// Other Operators
936//===----------------------------------------------------------------------===//
937
938Value *ScalarExprEmitter::
939VisitConditionalOperator(const ConditionalOperator *E) {
940 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
941 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
942 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
943
Chris Lattner98a425c2007-11-26 01:40:58 +0000944 // Evaluate the conditional, then convert it to bool. We do this explicitly
945 // because we need the unconverted value if this is a GNU ?: expression with
946 // missing middle value.
947 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
948 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
949 CGF.getContext().BoolTy);
950 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000951
952 CGF.EmitBlock(LHSBlock);
953
954 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000955 Value *LHS;
956 if (E->getLHS())
957 LHS = Visit(E->getLHS());
958 else // Perform promotions, to handle cases like "short ?: int"
959 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
960
Chris Lattner9fba49a2007-08-24 05:35:26 +0000961 Builder.CreateBr(ContBlock);
962 LHSBlock = Builder.GetInsertBlock();
963
964 CGF.EmitBlock(RHSBlock);
965
966 Value *RHS = Visit(E->getRHS());
967 Builder.CreateBr(ContBlock);
968 RHSBlock = Builder.GetInsertBlock();
969
970 CGF.EmitBlock(ContBlock);
971
Chris Lattner307da022007-11-30 17:56:23 +0000972 if (!LHS) {
973 assert(E->getType()->isVoidType() && "Non-void value should have a value");
974 return 0;
975 }
976
Chris Lattner9fba49a2007-08-24 05:35:26 +0000977 // Create a PHI node for the real part.
978 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
979 PN->reserveOperandSpace(2);
980 PN->addIncoming(LHS, LHSBlock);
981 PN->addIncoming(RHS, RHSBlock);
982 return PN;
983}
984
985Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000986 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000987 return
988 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000989}
990
Chris Lattner307da022007-11-30 17:56:23 +0000991Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +0000992 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
993
994 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
995 return V;
996}
997
Chris Lattner307da022007-11-30 17:56:23 +0000998Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000999 std::string str;
1000
1001 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
1002
1003 llvm::Constant *C = llvm::ConstantArray::get(str);
1004 C = new llvm::GlobalVariable(C->getType(), true,
1005 llvm::GlobalValue::InternalLinkage,
1006 C, ".str", &CGF.CGM.getModule());
1007 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1008 llvm::Constant *Zeros[] = { Zero, Zero };
1009 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1010
1011 return C;
1012}
1013
Chris Lattner9fba49a2007-08-24 05:35:26 +00001014//===----------------------------------------------------------------------===//
1015// Entry Point into this File
1016//===----------------------------------------------------------------------===//
1017
1018/// EmitComplexExpr - Emit the computation of the specified expression of
1019/// complex type, ignoring the result.
1020Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1021 assert(E && !hasAggregateLLVMType(E->getType()) &&
1022 "Invalid scalar expression to emit");
1023
1024 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1025}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001026
1027/// EmitScalarConversion - Emit a conversion from the specified type to the
1028/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001029Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1030 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001031 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1032 "Invalid scalar expression to emit");
1033 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1034}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001035
1036/// EmitComplexToScalarConversion - Emit a conversion from the specified
1037/// complex type to the specified destination type, where the destination
1038/// type is an LLVM scalar type.
1039Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1040 QualType SrcTy,
1041 QualType DstTy) {
1042 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1043 "Invalid complex -> scalar conversion");
1044 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1045 DstTy);
1046}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001047
1048Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1049 assert(V1->getType() == V2->getType() &&
1050 "Vector operands must be of the same type");
1051
1052 unsigned NumElements =
1053 cast<llvm::VectorType>(V1->getType())->getNumElements();
1054
1055 va_list va;
1056 va_start(va, V2);
1057
1058 llvm::SmallVector<llvm::Constant*, 16> Args;
1059
1060 for (unsigned i = 0; i < NumElements; i++) {
1061 int n = va_arg(va, int);
1062
1063 assert(n >= 0 && n < (int)NumElements * 2 &&
1064 "Vector shuffle index out of bounds!");
1065
1066 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1067 }
1068
1069 const char *Name = va_arg(va, const char *);
1070 va_end(va);
1071
1072 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1073
1074 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1075}
1076
Anders Carlsson68b8be92007-12-15 21:23:30 +00001077llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1078 unsigned NumVals)
1079{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001080 llvm::Value *Vec
1081 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1082
1083 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
1084 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1085 Vec = Builder.CreateInsertElement(Vec, Vals[i], Idx, "tmp");
1086 }
1087
1088 return Vec;
1089}