blob: 6c5326105feab4982eab21a092220ba5cfd30383 [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
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 Carlsson85f9bce2007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
Chris Lattner391d77a2008-03-30 23:03:07 +000022#include "llvm/ValueSymbolTable.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000023#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000024
Chris Lattner7f02f722007-08-24 05:35:26 +000025using namespace clang;
26using namespace CodeGen;
27using llvm::Value;
28
29//===----------------------------------------------------------------------===//
30// Scalar Expression Emitter
31//===----------------------------------------------------------------------===//
32
33struct BinOpInfo {
34 Value *LHS;
35 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000036 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000037 const BinaryOperator *E;
38};
39
40namespace {
41class VISIBILITY_HIDDEN ScalarExprEmitter
42 : public StmtVisitor<ScalarExprEmitter, Value*> {
43 CodeGenFunction &CGF;
Devang Patel50c90342007-10-09 19:49:58 +000044 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner2b94fe32008-03-01 08:45:05 +000045 CGObjCRuntime *Runtime;
46
47
Chris Lattner7f02f722007-08-24 05:35:26 +000048public:
49
Chris Lattner2b94fe32008-03-01 08:45:05 +000050 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
51 Builder(CGF.Builder),
52 Runtime(CGF.CGM.getObjCRuntime()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000053 }
54
55
56 //===--------------------------------------------------------------------===//
57 // Utilities
58 //===--------------------------------------------------------------------===//
59
60 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
61 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
62
63 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000064 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000065 }
66
67 /// EmitLoadOfLValue - Given an expression with complex type that represents a
68 /// value l-value, this method emits the address of the l-value, then loads
69 /// and returns the result.
70 Value *EmitLoadOfLValue(const Expr *E) {
71 // FIXME: Volatile
72 return EmitLoadOfLValue(EmitLValue(E), E->getType());
73 }
74
Chris Lattner9abc84e2007-08-26 16:42:57 +000075 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000076 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000077 Value *EmitConversionToBool(Value *Src, QualType DstTy);
78
Chris Lattner3707b252007-08-26 06:48:56 +000079 /// EmitScalarConversion - Emit a conversion from the specified type to the
80 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000081 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
82
83 /// EmitComplexToScalarConversion - Emit a conversion from the specified
84 /// complex type to the specified destination type, where the destination
85 /// type is an LLVM scalar type.
86 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
87 QualType SrcTy, QualType DstTy);
Chris Lattner3707b252007-08-26 06:48:56 +000088
Chris Lattner7f02f722007-08-24 05:35:26 +000089 //===--------------------------------------------------------------------===//
90 // Visitor Methods
91 //===--------------------------------------------------------------------===//
92
93 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000094 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +000095 assert(0 && "Stmt can't have complex result type!");
96 return 0;
97 }
98 Value *VisitExpr(Expr *S);
99 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
100
101 // Leaves.
102 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
103 return llvm::ConstantInt::get(E->getValue());
104 }
105 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattnerc9bec4b2007-09-22 18:47:25 +0000106 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000107 }
108 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
109 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
110 }
Nate Begemane7579b52007-11-15 05:40:03 +0000111 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
112 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
113 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000114 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
115 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000116 CGF.getContext().typesAreCompatible(
117 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000118 }
119 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
120 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
121 }
122
123 // l-values.
124 Value *VisitDeclRefExpr(DeclRefExpr *E) {
125 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
126 return llvm::ConstantInt::get(EC->getInitVal());
127 return EmitLoadOfLValue(E);
128 }
Chris Lattner2b94fe32008-03-01 08:45:05 +0000129 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Chris Lattner391d77a2008-03-30 23:03:07 +0000130 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000131 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
132 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
133 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
134 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
135 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000136
137 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000138 unsigned NumInitElements = E->getNumInits();
139
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000140 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000141 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
142
143 // We have a scalar in braces. Just use the first element.
144 if (!VType)
145 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000146
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000147 unsigned NumVectorElements = VType->getNumElements();
148 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000149
150 // Emit individual vector element stores.
151 llvm::Value *V = llvm::UndefValue::get(VType);
152
Anders Carlsson222d2c82007-12-18 02:45:33 +0000153 // Emit initializers
154 unsigned i;
155 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000156 Value *NewV = Visit(E->getInit(i));
157 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
158 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000159 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000160
161 // Emit remaining default initializers
162 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
163 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
164 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
165 V = Builder.CreateInsertElement(V, NewV, Idx);
166 }
167
Devang Patela83cc332007-10-24 18:05:48 +0000168 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000169 }
170
171 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
172 return Visit(E->getInitializer());
173 }
174
Chris Lattner7f02f722007-08-24 05:35:26 +0000175 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
176 Value *VisitCastExpr(const CastExpr *E) {
177 return EmitCastExpr(E->getSubExpr(), E->getType());
178 }
179 Value *EmitCastExpr(const Expr *E, QualType T);
180
181 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattner9b655512007-08-31 22:49:20 +0000182 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000183 }
184
Chris Lattner33793202007-08-31 22:09:40 +0000185 Value *VisitStmtExpr(const StmtExpr *E);
186
Chris Lattner7f02f722007-08-24 05:35:26 +0000187 // Unary Operators.
188 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
189 Value *VisitUnaryPostDec(const UnaryOperator *E) {
190 return VisitPrePostIncDec(E, false, false);
191 }
192 Value *VisitUnaryPostInc(const UnaryOperator *E) {
193 return VisitPrePostIncDec(E, true, false);
194 }
195 Value *VisitUnaryPreDec(const UnaryOperator *E) {
196 return VisitPrePostIncDec(E, false, true);
197 }
198 Value *VisitUnaryPreInc(const UnaryOperator *E) {
199 return VisitPrePostIncDec(E, true, true);
200 }
201 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
202 return EmitLValue(E->getSubExpr()).getAddress();
203 }
204 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
205 Value *VisitUnaryPlus(const UnaryOperator *E) {
206 return Visit(E->getSubExpr());
207 }
208 Value *VisitUnaryMinus (const UnaryOperator *E);
209 Value *VisitUnaryNot (const UnaryOperator *E);
210 Value *VisitUnaryLNot (const UnaryOperator *E);
211 Value *VisitUnarySizeOf (const UnaryOperator *E) {
212 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
213 }
214 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
215 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
216 }
217 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
218 bool isSizeOf);
Chris Lattner46f93d02007-08-24 21:20:17 +0000219 Value *VisitUnaryReal (const UnaryOperator *E);
220 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000221 Value *VisitUnaryExtension(const UnaryOperator *E) {
222 return Visit(E->getSubExpr());
223 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000224 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
225
Chris Lattner7f02f722007-08-24 05:35:26 +0000226 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000227 Value *EmitMul(const BinOpInfo &Ops) {
228 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
229 }
230 Value *EmitDiv(const BinOpInfo &Ops);
231 Value *EmitRem(const BinOpInfo &Ops);
232 Value *EmitAdd(const BinOpInfo &Ops);
233 Value *EmitSub(const BinOpInfo &Ops);
234 Value *EmitShl(const BinOpInfo &Ops);
235 Value *EmitShr(const BinOpInfo &Ops);
236 Value *EmitAnd(const BinOpInfo &Ops) {
237 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
238 }
239 Value *EmitXor(const BinOpInfo &Ops) {
240 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
241 }
242 Value *EmitOr (const BinOpInfo &Ops) {
243 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
244 }
245
Chris Lattner1f1ded92007-08-24 21:00:35 +0000246 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000247 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000248 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
249
250 // Binary operators and binary compound assignment operators.
251#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000252 Value *VisitBin ## OP(const BinaryOperator *E) { \
253 return Emit ## OP(EmitBinOps(E)); \
254 } \
255 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
256 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000257 }
258 HANDLEBINOP(Mul);
259 HANDLEBINOP(Div);
260 HANDLEBINOP(Rem);
261 HANDLEBINOP(Add);
262 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
263 HANDLEBINOP(Shl);
264 HANDLEBINOP(Shr);
265 HANDLEBINOP(And);
266 HANDLEBINOP(Xor);
267 HANDLEBINOP(Or);
268#undef HANDLEBINOP
269 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000270 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner1f1ded92007-08-24 21:00:35 +0000271 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
272 }
273
Chris Lattner7f02f722007-08-24 05:35:26 +0000274 // Comparisons.
275 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
276 unsigned SICmpOpc, unsigned FCmpOpc);
277#define VISITCOMP(CODE, UI, SI, FP) \
278 Value *VisitBin##CODE(const BinaryOperator *E) { \
279 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
280 llvm::FCmpInst::FP); }
281 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
282 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
283 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
284 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
285 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
286 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
287#undef VISITCOMP
288
289 Value *VisitBinAssign (const BinaryOperator *E);
290
291 Value *VisitBinLAnd (const BinaryOperator *E);
292 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000293 Value *VisitBinComma (const BinaryOperator *E);
294
295 // Other Operators.
296 Value *VisitConditionalOperator(const ConditionalOperator *CO);
297 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begemane2ce1d92008-01-17 17:46:27 +0000298 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000299 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000300 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
301 return CGF.EmitObjCStringLiteral(E);
302 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000303 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000304};
305} // end anonymous namespace.
306
307//===----------------------------------------------------------------------===//
308// Utilities
309//===----------------------------------------------------------------------===//
310
Chris Lattner9abc84e2007-08-26 16:42:57 +0000311/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000312/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000313Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
314 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
315
316 if (SrcType->isRealFloatingType()) {
317 // Compare against 0.0 for fp scalars.
318 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000319 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
320 }
321
322 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
323 "Unknown scalar type to convert");
324
325 // Because of the type rules of C, we often end up computing a logical value,
326 // then zero extending it to int, then wanting it as a logical value again.
327 // Optimize this common case.
328 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
329 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
330 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000331 // If there aren't any more uses, zap the instruction to save space.
332 // Note that there can be more uses, for example if this
333 // is the result of an assignment.
334 if (ZI->use_empty())
335 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000336 return Result;
337 }
338 }
339
340 // Compare against an integer or pointer null.
341 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
342 return Builder.CreateICmpNE(Src, Zero, "tobool");
343}
344
Chris Lattner3707b252007-08-26 06:48:56 +0000345/// EmitScalarConversion - Emit a conversion from the specified type to the
346/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000347Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
348 QualType DstType) {
Chris Lattner3707b252007-08-26 06:48:56 +0000349 SrcType = SrcType.getCanonicalType();
350 DstType = DstType.getCanonicalType();
351 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000352
353 if (DstType->isVoidType()) return 0;
Chris Lattner3707b252007-08-26 06:48:56 +0000354
355 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000356 if (DstType->isBooleanType())
357 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000358
359 const llvm::Type *DstTy = ConvertType(DstType);
360
361 // Ignore conversions like int -> uint.
362 if (Src->getType() == DstTy)
363 return Src;
364
365 // Handle pointer conversions next: pointers can only be converted to/from
366 // other pointers and integers.
367 if (isa<PointerType>(DstType)) {
368 // The source value may be an integer, or a pointer.
369 if (isa<llvm::PointerType>(Src->getType()))
370 return Builder.CreateBitCast(Src, DstTy, "conv");
371 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
372 return Builder.CreateIntToPtr(Src, DstTy, "conv");
373 }
374
375 if (isa<PointerType>(SrcType)) {
376 // Must be an ptr to int cast.
377 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000378 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000379 }
380
Anders Carlsson79b67f32008-02-01 23:17:55 +0000381 // A scalar source can be splatted to an OCU vector of the same element type
Chris Lattner3b1ae002008-02-02 04:51:41 +0000382 if (DstType->isOCUVectorType() && !isa<VectorType>(SrcType) &&
383 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begeman4119d1a2007-12-30 02:59:45 +0000384 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
385 true);
Nate Begeman4119d1a2007-12-30 02:59:45 +0000386
Chris Lattner3b1ae002008-02-02 04:51:41 +0000387 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000388 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000389 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000390 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000391
Chris Lattner3707b252007-08-26 06:48:56 +0000392 // Finally, we have the arithmetic types: real int/float.
393 if (isa<llvm::IntegerType>(Src->getType())) {
394 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000395 if (isa<llvm::IntegerType>(DstTy))
396 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
397 else if (InputSigned)
398 return Builder.CreateSIToFP(Src, DstTy, "conv");
399 else
400 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000401 }
402
403 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
404 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000405 if (DstType->isSignedIntegerType())
406 return Builder.CreateFPToSI(Src, DstTy, "conv");
407 else
408 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000409 }
410
411 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000412 if (DstTy->getTypeID() < Src->getType()->getTypeID())
413 return Builder.CreateFPTrunc(Src, DstTy, "conv");
414 else
415 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000416}
417
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000418/// EmitComplexToScalarConversion - Emit a conversion from the specified
419/// complex type to the specified destination type, where the destination
420/// type is an LLVM scalar type.
421Value *ScalarExprEmitter::
422EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
423 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000424 // Get the source element type.
425 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
426
427 // Handle conversions to bool first, they are special: comparisons against 0.
428 if (DstTy->isBooleanType()) {
429 // Complex != 0 -> (Real != 0) | (Imag != 0)
430 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
431 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
432 return Builder.CreateOr(Src.first, Src.second, "tobool");
433 }
434
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000435 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
436 // the imaginary part of the complex value is discarded and the value of the
437 // real part is converted according to the conversion rules for the
438 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000439 return EmitScalarConversion(Src.first, SrcTy, DstTy);
440}
441
442
Chris Lattner7f02f722007-08-24 05:35:26 +0000443//===----------------------------------------------------------------------===//
444// Visitor Methods
445//===----------------------------------------------------------------------===//
446
447Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnerdc4d2802007-12-02 01:49:16 +0000448 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000449 if (E->getType()->isVoidType())
450 return 0;
451 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
452}
453
Chris Lattner391d77a2008-03-30 23:03:07 +0000454Value *ScalarExprEmitter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
455 return Builder.CreateLoad(CGF.EmitObjCIvarRefLValue(E).getAddress());
456}
457
Chris Lattner2b94fe32008-03-01 08:45:05 +0000458Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
459 // Only the lookup mechanism and first two arguments of the method
460 // implementation vary between runtimes. We can get the receiver and
461 // arguments in generic code.
462
463 // Find the receiver
464 llvm::Value * Receiver = CGF.EmitScalarExpr(E->getReceiver());
465
466 // Process the arguments
467 unsigned int ArgC = E->getNumArgs();
468 llvm::SmallVector<llvm::Value*, 16> Args;
469 for(unsigned i=0 ; i<ArgC ; i++) {
470 Expr *ArgExpr = E->getArg(i);
471 QualType ArgTy = ArgExpr->getType();
472 if (!CGF.hasAggregateLLVMType(ArgTy)) {
473 // Scalar argument is passed by-value.
474 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
475 } else if (ArgTy->isComplexType()) {
476 // Make a temporary alloca to pass the argument.
477 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
478 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
479 Args.push_back(DestMem);
480 } else {
481 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
482 CGF.EmitAggExpr(ArgExpr, DestMem, false);
483 Args.push_back(DestMem);
484 }
485 }
486
487 // Get the selector string
488 std::string SelStr = E->getSelector().getName();
489 llvm::Constant *Selector = CGF.CGM.GetAddrOfConstantString(SelStr);
Chris Lattner391d77a2008-03-30 23:03:07 +0000490
491 llvm::Value *SelPtr = Builder.CreateStructGEP(Selector, 0);
Chris Lattner2b94fe32008-03-01 08:45:05 +0000492 return Runtime->generateMessageSend(Builder,
493 ConvertType(E->getType()),
Chris Lattner391d77a2008-03-30 23:03:07 +0000494 CGF.CurFn->getValueSymbolTable().lookup("self"),
Chris Lattner2b94fe32008-03-01 08:45:05 +0000495 Receiver,
Chris Lattner391d77a2008-03-30 23:03:07 +0000496 SelPtr,
Chris Lattner2b94fe32008-03-01 08:45:05 +0000497 &Args[0],
498 Args.size());
499}
500
Chris Lattner7f02f722007-08-24 05:35:26 +0000501Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
502 // Emit subscript expressions in rvalue context's. For most cases, this just
503 // loads the lvalue formed by the subscript expr. However, we have to be
504 // careful, because the base of a vector subscript is occasionally an rvalue,
505 // so we can't get it as an lvalue.
506 if (!E->getBase()->getType()->isVectorType())
507 return EmitLoadOfLValue(E);
508
509 // Handle the vector case. The base must be a vector, the index must be an
510 // integer value.
511 Value *Base = Visit(E->getBase());
512 Value *Idx = Visit(E->getIdx());
513
514 // FIXME: Convert Idx to i32 type.
515 return Builder.CreateExtractElement(Base, Idx, "vecext");
516}
517
518/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
519/// also handle things like function to pointer-to-function decay, and array to
520/// pointer decay.
521Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
522 const Expr *Op = E->getSubExpr();
523
524 // If this is due to array->pointer conversion, emit the array expression as
525 // an l-value.
526 if (Op->getType()->isArrayType()) {
527 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
528 // will not true when we add support for VLAs.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000529 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner7f02f722007-08-24 05:35:26 +0000530
531 assert(isa<llvm::PointerType>(V->getType()) &&
532 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
533 ->getElementType()) &&
534 "Doesn't support VLAs yet!");
Chris Lattner36b6a0a2008-03-19 05:19:41 +0000535 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnera9e63722007-12-12 04:13:20 +0000536
537 // The resultant pointer type can be implicitly casted to other pointer
538 // types as well, for example void*.
539 const llvm::Type *DestPTy = ConvertType(E->getType());
540 assert(isa<llvm::PointerType>(DestPTy) &&
541 "Only expect implicit cast to pointer");
542 if (V->getType() != DestPTy)
543 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
544 return V;
545
Anders Carlsson793680e2007-10-12 23:56:29 +0000546 } else if (E->getType()->isReferenceType()) {
Anders Carlsson23af9f22007-10-13 05:52:34 +0000547 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
548 getReferenceeType() ==
549 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlsson793680e2007-10-12 23:56:29 +0000550
551 return EmitLValue(Op).getAddress();
Chris Lattner7f02f722007-08-24 05:35:26 +0000552 }
553
554 return EmitCastExpr(Op, E->getType());
555}
556
557
558// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
559// have to handle a more broad range of conversions than explicit casts, as they
560// handle things like function to ptr-to-function decay etc.
561Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner58a2e942007-08-26 07:26:12 +0000562 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000563
564 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000565 Value *Src = Visit(const_cast<Expr*>(E));
566
Chris Lattner3707b252007-08-26 06:48:56 +0000567 // Use EmitScalarConversion to perform the conversion.
568 return EmitScalarConversion(Src, E->getType(), DestTy);
569 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000570
571 if (E->getType()->isComplexType()) {
572 // Handle cases where the source is a complex type.
573 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
574 DestTy);
575 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000576
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000577 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
578 // evaluate the result and return.
579 CGF.EmitAggExpr(E, 0, false);
580 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000581}
582
Chris Lattner33793202007-08-31 22:09:40 +0000583Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner9b655512007-08-31 22:49:20 +0000584 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000585}
586
587
Chris Lattner7f02f722007-08-24 05:35:26 +0000588//===----------------------------------------------------------------------===//
589// Unary Operators
590//===----------------------------------------------------------------------===//
591
592Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000593 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000594 LValue LV = EmitLValue(E->getSubExpr());
595 // FIXME: Handle volatile!
Chris Lattnere936cc82007-08-26 05:10:16 +0000596 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattner9b655512007-08-31 22:49:20 +0000597 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000598
599 int AmountVal = isInc ? 1 : -1;
600
601 Value *NextVal;
Chris Lattnere936cc82007-08-26 05:10:16 +0000602 if (isa<llvm::PointerType>(InVal->getType())) {
603 // FIXME: This isn't right for VLAs.
604 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner36b6a0a2008-03-19 05:19:41 +0000605 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000606 } else {
607 // Add the inc/dec to the real part.
608 if (isa<llvm::IntegerType>(InVal->getType()))
609 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000610 else if (InVal->getType() == llvm::Type::FloatTy)
611 // FIXME: Handle long double.
Devang Patele9b8c0a2007-10-30 20:59:40 +0000612 NextVal =
613 llvm::ConstantFP::get(InVal->getType(),
614 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerca2617c2007-09-13 06:19:18 +0000615 else {
616 // FIXME: Handle long double.
617 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patele9b8c0a2007-10-30 20:59:40 +0000618 NextVal =
619 llvm::ConstantFP::get(InVal->getType(),
620 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerca2617c2007-09-13 06:19:18 +0000621 }
Chris Lattnere936cc82007-08-26 05:10:16 +0000622 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
623 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000624
625 // Store the updated result through the lvalue.
626 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
627 E->getSubExpr()->getType());
628
629 // If this is a postinc, return the value read from memory, otherwise use the
630 // updated value.
631 return isPre ? NextVal : InVal;
632}
633
634
635Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
636 Value *Op = Visit(E->getSubExpr());
637 return Builder.CreateNeg(Op, "neg");
638}
639
640Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
641 Value *Op = Visit(E->getSubExpr());
642 return Builder.CreateNot(Op, "neg");
643}
644
645Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
646 // Compare operand to zero.
647 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
648
649 // Invert value.
650 // TODO: Could dynamically modify easy computations here. For example, if
651 // the operand is an icmp ne, turn into icmp eq.
652 BoolVal = Builder.CreateNot(BoolVal, "lnot");
653
654 // ZExt result to int.
655 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
656}
657
658/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
659/// an integer (RetType).
660Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner46f93d02007-08-24 21:20:17 +0000661 QualType RetType,bool isSizeOf){
Chris Lattnera269ebf2008-02-21 05:45:29 +0000662 assert(RetType->isIntegerType() && "Result type must be an integer!");
663 uint32_t ResultWidth =
Chris Lattner98be4942008-03-05 18:54:05 +0000664 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattnera269ebf2008-02-21 05:45:29 +0000665
666 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
667 if (TypeToSize->isVoidType())
668 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
669
Chris Lattner7f02f722007-08-24 05:35:26 +0000670 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner98be4942008-03-05 18:54:05 +0000671 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner7f02f722007-08-24 05:35:26 +0000672
673 uint64_t Val = isSizeOf ? Info.first : Info.second;
674 Val /= 8; // Return size in bytes, not bits.
675
Chris Lattner7f02f722007-08-24 05:35:26 +0000676 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
677}
678
Chris Lattner46f93d02007-08-24 21:20:17 +0000679Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
680 Expr *Op = E->getSubExpr();
681 if (Op->getType()->isComplexType())
682 return CGF.EmitComplexExpr(Op).first;
683 return Visit(Op);
684}
685Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
686 Expr *Op = E->getSubExpr();
687 if (Op->getType()->isComplexType())
688 return CGF.EmitComplexExpr(Op).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000689
690 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
691 // effects are evaluated.
692 CGF.EmitScalarExpr(Op);
693 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000694}
695
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000696Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
697{
698 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
699
700 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
701
Chris Lattner98be4942008-03-05 18:54:05 +0000702 uint32_t ResultWidth =
703 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000704 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
705}
Chris Lattner46f93d02007-08-24 21:20:17 +0000706
Chris Lattner7f02f722007-08-24 05:35:26 +0000707//===----------------------------------------------------------------------===//
708// Binary Operators
709//===----------------------------------------------------------------------===//
710
711BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
712 BinOpInfo Result;
713 Result.LHS = Visit(E->getLHS());
714 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000715 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000716 Result.E = E;
717 return Result;
718}
719
Chris Lattner3ccf7742007-08-26 21:41:21 +0000720Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000721 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
722 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
723
724 BinOpInfo OpInfo;
725
726 // Load the LHS and RHS operands.
727 LValue LHSLV = EmitLValue(E->getLHS());
728 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner04dc7642007-08-26 22:37:40 +0000729
730 // Determine the computation type. If the RHS is complex, then this is one of
731 // the add/sub/mul/div operators. All of these operators can be computed in
732 // with just their real component even though the computation domain really is
733 // complex.
Chris Lattner3ccf7742007-08-26 21:41:21 +0000734 QualType ComputeType = E->getComputationType();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000735
Chris Lattner04dc7642007-08-26 22:37:40 +0000736 // If the computation type is complex, then the RHS is complex. Emit the RHS.
737 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
738 ComputeType = CT->getElementType();
739
740 // Emit the RHS, only keeping the real component.
741 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
742 RHSTy = RHSTy->getAsComplexType()->getElementType();
743 } else {
744 // Otherwise the RHS is a simple scalar value.
745 OpInfo.RHS = Visit(E->getRHS());
746 }
747
748 // Convert the LHS/RHS values to the computation type.
Chris Lattnere9377122007-08-26 07:08:39 +0000749 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000750
Devang Patelf86206f2007-10-25 22:19:13 +0000751 // Do not merge types for -= or += where the LHS is a pointer.
752 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patel03f7c032007-10-30 18:31:12 +0000753 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner3b44b572007-08-25 21:56:20 +0000754 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnere9377122007-08-26 07:08:39 +0000755 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000756 }
757 OpInfo.Ty = ComputeType;
758 OpInfo.E = E;
759
760 // Expand the binary operator.
761 Value *Result = (this->*Func)(OpInfo);
762
763 // Truncate the result back to the LHS type.
Chris Lattnere9377122007-08-26 07:08:39 +0000764 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000765
766 // Store the result value into the LHS lvalue.
767 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
768
769 return Result;
770}
771
772
Chris Lattner7f02f722007-08-24 05:35:26 +0000773Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000774 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000775 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000776 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000777 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
778 else
779 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
780}
781
782Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
783 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000784 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000785 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
786 else
787 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
788}
789
790
791Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner1f1ded92007-08-24 21:00:35 +0000792 if (!Ops.Ty->isPointerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000793 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000794
795 // FIXME: What about a pointer to a VLA?
Chris Lattner8f925282008-01-03 06:36:51 +0000796 Value *Ptr, *Idx;
797 Expr *IdxExp;
798 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
799 Ptr = Ops.LHS;
800 Idx = Ops.RHS;
801 IdxExp = Ops.E->getRHS();
802 } else { // int + pointer
803 Ptr = Ops.RHS;
804 Idx = Ops.LHS;
805 IdxExp = Ops.E->getLHS();
806 }
807
808 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
809 if (Width < CGF.LLVMPointerWidth) {
810 // Zero or sign extend the pointer value based on whether the index is
811 // signed or not.
812 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
813 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
814 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
815 else
816 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
817 }
818
819 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +0000820}
821
822Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
823 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
824 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
825
Chris Lattner1f1ded92007-08-24 21:00:35 +0000826 // pointer - int
827 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
828 "ptr-ptr shouldn't get here");
829 // FIXME: The pointer could point to a VLA.
Chris Lattner6860f3c2008-01-31 04:12:50 +0000830 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
831
832 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
833 if (Width < CGF.LLVMPointerWidth) {
834 // Zero or sign extend the pointer value based on whether the index is
835 // signed or not.
836 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
837 if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
838 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
839 else
840 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
841 }
842
843 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000844}
845
846Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
847 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
848 // the compound assignment case it is invalid, so just handle it here.
849 if (!E->getRHS()->getType()->isPointerType())
850 return EmitSub(EmitBinOps(E));
Chris Lattner7f02f722007-08-24 05:35:26 +0000851
852 // pointer - pointer
Chris Lattner1f1ded92007-08-24 21:00:35 +0000853 Value *LHS = Visit(E->getLHS());
854 Value *RHS = Visit(E->getRHS());
855
Seo Sanghyeonec86b972007-12-03 06:23:43 +0000856 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeon9bb947a2007-12-26 05:21:37 +0000857 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner98be4942008-03-05 18:54:05 +0000858 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000859
860 const llvm::Type *ResultType = ConvertType(E->getType());
861 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
862 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
863 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner7f02f722007-08-24 05:35:26 +0000864
865 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
866 // remainder. As such, we handle common power-of-two cases here to generate
867 // better code.
868 if (llvm::isPowerOf2_64(ElementSize)) {
869 Value *ShAmt =
870 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
871 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
872 }
Chris Lattner1f1ded92007-08-24 21:00:35 +0000873
Chris Lattner7f02f722007-08-24 05:35:26 +0000874 // Otherwise, do a full sdiv.
875 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
876 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
877}
878
Chris Lattner1f1ded92007-08-24 21:00:35 +0000879
Chris Lattner7f02f722007-08-24 05:35:26 +0000880Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
881 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
882 // RHS to the same size as the LHS.
883 Value *RHS = Ops.RHS;
884 if (Ops.LHS->getType() != RHS->getType())
885 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
886
887 return Builder.CreateShl(Ops.LHS, RHS, "shl");
888}
889
890Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
891 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
892 // RHS to the same size as the LHS.
893 Value *RHS = Ops.RHS;
894 if (Ops.LHS->getType() != RHS->getType())
895 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
896
Chris Lattner1f1ded92007-08-24 21:00:35 +0000897 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000898 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
899 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
900}
901
902Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
903 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000904 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +0000905 QualType LHSTy = E->getLHS()->getType();
906 if (!LHSTy->isComplexType()) {
907 Value *LHS = Visit(E->getLHS());
908 Value *RHS = Visit(E->getRHS());
909
910 if (LHS->getType()->isFloatingPoint()) {
911 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
912 LHS, RHS, "cmp");
913 } else if (LHSTy->isUnsignedIntegerType()) {
914 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
915 LHS, RHS, "cmp");
916 } else {
917 // Signed integers and pointers.
918 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
919 LHS, RHS, "cmp");
920 }
921 } else {
922 // Complex Comparison: can only be an equality comparison.
923 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
924 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
925
926 QualType CETy =
927 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
928
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000929 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +0000930 if (CETy->isRealFloatingType()) {
931 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
932 LHS.first, RHS.first, "cmp.r");
933 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
934 LHS.second, RHS.second, "cmp.i");
935 } else {
936 // Complex comparisons can only be equality comparisons. As such, signed
937 // and unsigned opcodes are the same.
938 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
939 LHS.first, RHS.first, "cmp.r");
940 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
941 LHS.second, RHS.second, "cmp.i");
942 }
943
944 if (E->getOpcode() == BinaryOperator::EQ) {
945 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
946 } else {
947 assert(E->getOpcode() == BinaryOperator::NE &&
948 "Complex comparison other than == or != ?");
949 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
950 }
951 }
952
953 // ZExt result to int.
954 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
955}
956
957Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
958 LValue LHS = EmitLValue(E->getLHS());
959 Value *RHS = Visit(E->getRHS());
960
961 // Store the value into the LHS.
962 // FIXME: Volatility!
963 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
964
965 // Return the RHS.
966 return RHS;
967}
968
969Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
970 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
971
972 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
973 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
974
975 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
976 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
977
978 CGF.EmitBlock(RHSBlock);
979 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
980
981 // Reaquire the RHS block, as there may be subblocks inserted.
982 RHSBlock = Builder.GetInsertBlock();
983 CGF.EmitBlock(ContBlock);
984
985 // Create a PHI node. If we just evaluted the LHS condition, the result is
986 // false. If we evaluated both, the result is the RHS condition.
987 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
988 PN->reserveOperandSpace(2);
989 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
990 PN->addIncoming(RHSCond, RHSBlock);
991
992 // ZExt result to int.
993 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
994}
995
996Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
997 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
998
999 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1000 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1001
1002 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1003 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1004
1005 CGF.EmitBlock(RHSBlock);
1006 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1007
1008 // Reaquire the RHS block, as there may be subblocks inserted.
1009 RHSBlock = Builder.GetInsertBlock();
1010 CGF.EmitBlock(ContBlock);
1011
1012 // Create a PHI node. If we just evaluted the LHS condition, the result is
1013 // true. If we evaluated both, the result is the RHS condition.
1014 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1015 PN->reserveOperandSpace(2);
1016 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1017 PN->addIncoming(RHSCond, RHSBlock);
1018
1019 // ZExt result to int.
1020 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1021}
1022
1023Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1024 CGF.EmitStmt(E->getLHS());
1025 return Visit(E->getRHS());
1026}
1027
1028//===----------------------------------------------------------------------===//
1029// Other Operators
1030//===----------------------------------------------------------------------===//
1031
1032Value *ScalarExprEmitter::
1033VisitConditionalOperator(const ConditionalOperator *E) {
1034 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1035 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1036 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1037
Chris Lattnera21ddb32007-11-26 01:40:58 +00001038 // Evaluate the conditional, then convert it to bool. We do this explicitly
1039 // because we need the unconverted value if this is a GNU ?: expression with
1040 // missing middle value.
1041 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc89bf692008-01-03 07:05:49 +00001042 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1043 CGF.getContext().BoolTy);
Chris Lattnera21ddb32007-11-26 01:40:58 +00001044 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001045
1046 CGF.EmitBlock(LHSBlock);
1047
1048 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001049 Value *LHS;
1050 if (E->getLHS())
1051 LHS = Visit(E->getLHS());
1052 else // Perform promotions, to handle cases like "short ?: int"
1053 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1054
Chris Lattner7f02f722007-08-24 05:35:26 +00001055 Builder.CreateBr(ContBlock);
1056 LHSBlock = Builder.GetInsertBlock();
1057
1058 CGF.EmitBlock(RHSBlock);
1059
1060 Value *RHS = Visit(E->getRHS());
1061 Builder.CreateBr(ContBlock);
1062 RHSBlock = Builder.GetInsertBlock();
1063
1064 CGF.EmitBlock(ContBlock);
1065
Chris Lattner2202bce2007-11-30 17:56:23 +00001066 if (!LHS) {
1067 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1068 return 0;
1069 }
1070
Chris Lattner7f02f722007-08-24 05:35:26 +00001071 // Create a PHI node for the real part.
1072 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1073 PN->reserveOperandSpace(2);
1074 PN->addIncoming(LHS, LHSBlock);
1075 PN->addIncoming(RHS, RHSBlock);
1076 return PN;
1077}
1078
1079Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001080 // Emit the LHS or RHS as appropriate.
Devang Patele9b8c0a2007-10-30 20:59:40 +00001081 return
1082 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001083}
1084
Nate Begemane2ce1d92008-01-17 17:46:27 +00001085Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begeman67295d02008-01-30 20:50:20 +00001086 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1087 E->getNumArgs(CGF.getContext())).getScalarVal();
Nate Begemane2ce1d92008-01-17 17:46:27 +00001088}
1089
Chris Lattner2202bce2007-11-30 17:56:23 +00001090Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001091 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1092
1093 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1094 return V;
1095}
1096
Chris Lattner2202bce2007-11-30 17:56:23 +00001097Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001098 std::string str;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001099 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1100 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1101 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001102
1103 llvm::Constant *C = llvm::ConstantArray::get(str);
1104 C = new llvm::GlobalVariable(C->getType(), true,
1105 llvm::GlobalValue::InternalLinkage,
1106 C, ".str", &CGF.CGM.getModule());
1107 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1108 llvm::Constant *Zeros[] = { Zero, Zero };
1109 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1110
1111 return C;
1112}
1113
Chris Lattner7f02f722007-08-24 05:35:26 +00001114//===----------------------------------------------------------------------===//
1115// Entry Point into this File
1116//===----------------------------------------------------------------------===//
1117
1118/// EmitComplexExpr - Emit the computation of the specified expression of
1119/// complex type, ignoring the result.
1120Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1121 assert(E && !hasAggregateLLVMType(E->getType()) &&
1122 "Invalid scalar expression to emit");
1123
1124 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1125}
Chris Lattner3707b252007-08-26 06:48:56 +00001126
1127/// EmitScalarConversion - Emit a conversion from the specified type to the
1128/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001129Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1130 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001131 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1132 "Invalid scalar expression to emit");
1133 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1134}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001135
1136/// EmitComplexToScalarConversion - Emit a conversion from the specified
1137/// complex type to the specified destination type, where the destination
1138/// type is an LLVM scalar type.
1139Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1140 QualType SrcTy,
1141 QualType DstTy) {
1142 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1143 "Invalid complex -> scalar conversion");
1144 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1145 DstTy);
1146}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001147
1148Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1149 assert(V1->getType() == V2->getType() &&
1150 "Vector operands must be of the same type");
1151
1152 unsigned NumElements =
1153 cast<llvm::VectorType>(V1->getType())->getNumElements();
1154
1155 va_list va;
1156 va_start(va, V2);
1157
1158 llvm::SmallVector<llvm::Constant*, 16> Args;
1159
1160 for (unsigned i = 0; i < NumElements; i++) {
1161 int n = va_arg(va, int);
1162
1163 assert(n >= 0 && n < (int)NumElements * 2 &&
1164 "Vector shuffle index out of bounds!");
1165
1166 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1167 }
1168
1169 const char *Name = va_arg(va, const char *);
1170 va_end(va);
1171
1172 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1173
1174 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1175}
1176
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001177llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001178 unsigned NumVals, bool isSplat)
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001179{
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001180 llvm::Value *Vec
1181 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1182
1183 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001184 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001185 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001186 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001187 }
1188
1189 return Vec;
1190}