blob: 892712a0d4cab7da709cbb76576ee7129a888dac [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//
Chris Lattner959e5be2007-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 Lattner9fba49a2007-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 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"
Chris Lattnerc2126682008-01-03 07:05:49 +000022#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000023
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 Lattnercbfb5512008-03-01 08:45:05 +000044 CGObjCRuntime *Runtime;
45
46
Chris Lattner9fba49a2007-08-24 05:35:26 +000047public:
48
Chris Lattnercbfb5512008-03-01 08:45:05 +000049 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
50 Builder(CGF.Builder),
51 Runtime(CGF.CGM.getObjCRuntime()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000052 }
53
54
55 //===--------------------------------------------------------------------===//
56 // Utilities
57 //===--------------------------------------------------------------------===//
58
59 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
60 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
61
62 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000063 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000064 }
65
66 /// EmitLoadOfLValue - Given an expression with complex type that represents a
67 /// value l-value, this method emits the address of the l-value, then loads
68 /// and returns the result.
69 Value *EmitLoadOfLValue(const Expr *E) {
70 // FIXME: Volatile
71 return EmitLoadOfLValue(EmitLValue(E), E->getType());
72 }
73
Chris Lattnerd8d44222007-08-26 16:42:57 +000074 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000075 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000076 Value *EmitConversionToBool(Value *Src, QualType DstTy);
77
Chris Lattner4e05d1e2007-08-26 06:48:56 +000078 /// EmitScalarConversion - Emit a conversion from the specified type to the
79 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000080 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
81
82 /// EmitComplexToScalarConversion - Emit a conversion from the specified
83 /// complex type to the specified destination type, where the destination
84 /// type is an LLVM scalar type.
85 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
86 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000087
Chris Lattner9fba49a2007-08-24 05:35:26 +000088 //===--------------------------------------------------------------------===//
89 // Visitor Methods
90 //===--------------------------------------------------------------------===//
91
92 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000093 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000094 assert(0 && "Stmt can't have complex result type!");
95 return 0;
96 }
97 Value *VisitExpr(Expr *S);
98 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
99
100 // Leaves.
101 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
102 return llvm::ConstantInt::get(E->getValue());
103 }
104 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +0000105 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000106 }
107 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
108 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
109 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000110 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
111 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
112 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000113 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
114 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000115 CGF.getContext().typesAreCompatible(
116 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000117 }
118 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
119 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
120 }
121
122 // l-values.
123 Value *VisitDeclRefExpr(DeclRefExpr *E) {
124 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
125 return llvm::ConstantInt::get(EC->getInitVal());
126 return EmitLoadOfLValue(E);
127 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000128 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000129 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
130 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
131 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
132 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
133 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000134
135 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000136 unsigned NumInitElements = E->getNumInits();
137
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000138 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000139 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
140
141 // We have a scalar in braces. Just use the first element.
142 if (!VType)
143 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000144
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000145 unsigned NumVectorElements = VType->getNumElements();
146 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000147
148 // Emit individual vector element stores.
149 llvm::Value *V = llvm::UndefValue::get(VType);
150
Anders Carlsson323d5682007-12-18 02:45:33 +0000151 // Emit initializers
152 unsigned i;
153 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000154 Value *NewV = Visit(E->getInit(i));
155 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
156 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000157 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000158
159 // Emit remaining default initializers
160 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
161 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
162 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
163 V = Builder.CreateInsertElement(V, NewV, Idx);
164 }
165
Devang Patel32c39832007-10-24 18:05:48 +0000166 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000167 }
168
169 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
170 return Visit(E->getInitializer());
171 }
172
Chris Lattner9fba49a2007-08-24 05:35:26 +0000173 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
174 Value *VisitCastExpr(const CastExpr *E) {
175 return EmitCastExpr(E->getSubExpr(), E->getType());
176 }
177 Value *EmitCastExpr(const Expr *E, QualType T);
178
179 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000180 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000181 }
182
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000183 Value *VisitStmtExpr(const StmtExpr *E);
184
Chris Lattner9fba49a2007-08-24 05:35:26 +0000185 // Unary Operators.
186 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
187 Value *VisitUnaryPostDec(const UnaryOperator *E) {
188 return VisitPrePostIncDec(E, false, false);
189 }
190 Value *VisitUnaryPostInc(const UnaryOperator *E) {
191 return VisitPrePostIncDec(E, true, false);
192 }
193 Value *VisitUnaryPreDec(const UnaryOperator *E) {
194 return VisitPrePostIncDec(E, false, true);
195 }
196 Value *VisitUnaryPreInc(const UnaryOperator *E) {
197 return VisitPrePostIncDec(E, true, true);
198 }
199 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
200 return EmitLValue(E->getSubExpr()).getAddress();
201 }
202 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
203 Value *VisitUnaryPlus(const UnaryOperator *E) {
204 return Visit(E->getSubExpr());
205 }
206 Value *VisitUnaryMinus (const UnaryOperator *E);
207 Value *VisitUnaryNot (const UnaryOperator *E);
208 Value *VisitUnaryLNot (const UnaryOperator *E);
209 Value *VisitUnarySizeOf (const UnaryOperator *E) {
210 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
211 }
212 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
213 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
214 }
215 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
216 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000217 Value *VisitUnaryReal (const UnaryOperator *E);
218 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000219 Value *VisitUnaryExtension(const UnaryOperator *E) {
220 return Visit(E->getSubExpr());
221 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000222 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
223
Chris Lattner9fba49a2007-08-24 05:35:26 +0000224 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000225 Value *EmitMul(const BinOpInfo &Ops) {
226 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
227 }
228 Value *EmitDiv(const BinOpInfo &Ops);
229 Value *EmitRem(const BinOpInfo &Ops);
230 Value *EmitAdd(const BinOpInfo &Ops);
231 Value *EmitSub(const BinOpInfo &Ops);
232 Value *EmitShl(const BinOpInfo &Ops);
233 Value *EmitShr(const BinOpInfo &Ops);
234 Value *EmitAnd(const BinOpInfo &Ops) {
235 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
236 }
237 Value *EmitXor(const BinOpInfo &Ops) {
238 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
239 }
240 Value *EmitOr (const BinOpInfo &Ops) {
241 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
242 }
243
Chris Lattner660e31d2007-08-24 21:00:35 +0000244 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000245 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000246 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
247
248 // Binary operators and binary compound assignment operators.
249#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000250 Value *VisitBin ## OP(const BinaryOperator *E) { \
251 return Emit ## OP(EmitBinOps(E)); \
252 } \
253 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
254 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000255 }
256 HANDLEBINOP(Mul);
257 HANDLEBINOP(Div);
258 HANDLEBINOP(Rem);
259 HANDLEBINOP(Add);
260 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
261 HANDLEBINOP(Shl);
262 HANDLEBINOP(Shr);
263 HANDLEBINOP(And);
264 HANDLEBINOP(Xor);
265 HANDLEBINOP(Or);
266#undef HANDLEBINOP
267 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000268 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000269 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
270 }
271
Chris Lattner9fba49a2007-08-24 05:35:26 +0000272 // Comparisons.
273 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
274 unsigned SICmpOpc, unsigned FCmpOpc);
275#define VISITCOMP(CODE, UI, SI, FP) \
276 Value *VisitBin##CODE(const BinaryOperator *E) { \
277 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
278 llvm::FCmpInst::FP); }
279 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
280 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
281 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
282 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
283 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
284 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
285#undef VISITCOMP
286
287 Value *VisitBinAssign (const BinaryOperator *E);
288
289 Value *VisitBinLAnd (const BinaryOperator *E);
290 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000291 Value *VisitBinComma (const BinaryOperator *E);
292
293 // Other Operators.
294 Value *VisitConditionalOperator(const ConditionalOperator *CO);
295 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000296 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000297 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000298 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
299 return CGF.EmitObjCStringLiteral(E);
300 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000301 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000302};
303} // end anonymous namespace.
304
305//===----------------------------------------------------------------------===//
306// Utilities
307//===----------------------------------------------------------------------===//
308
Chris Lattnerd8d44222007-08-26 16:42:57 +0000309/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000310/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000311Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
312 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
313
314 if (SrcType->isRealFloatingType()) {
315 // Compare against 0.0 for fp scalars.
316 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000317 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
318 }
319
320 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
321 "Unknown scalar type to convert");
322
323 // Because of the type rules of C, we often end up computing a logical value,
324 // then zero extending it to int, then wanting it as a logical value again.
325 // Optimize this common case.
326 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
327 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
328 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000329 // If there aren't any more uses, zap the instruction to save space.
330 // Note that there can be more uses, for example if this
331 // is the result of an assignment.
332 if (ZI->use_empty())
333 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000334 return Result;
335 }
336 }
337
338 // Compare against an integer or pointer null.
339 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
340 return Builder.CreateICmpNE(Src, Zero, "tobool");
341}
342
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000343/// EmitScalarConversion - Emit a conversion from the specified type to the
344/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000345Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
346 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000347 SrcType = SrcType.getCanonicalType();
348 DstType = DstType.getCanonicalType();
349 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000350
351 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000352
353 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000354 if (DstType->isBooleanType())
355 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000356
357 const llvm::Type *DstTy = ConvertType(DstType);
358
359 // Ignore conversions like int -> uint.
360 if (Src->getType() == DstTy)
361 return Src;
362
363 // Handle pointer conversions next: pointers can only be converted to/from
364 // other pointers and integers.
365 if (isa<PointerType>(DstType)) {
366 // The source value may be an integer, or a pointer.
367 if (isa<llvm::PointerType>(Src->getType()))
368 return Builder.CreateBitCast(Src, DstTy, "conv");
369 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
370 return Builder.CreateIntToPtr(Src, DstTy, "conv");
371 }
372
373 if (isa<PointerType>(SrcType)) {
374 // Must be an ptr to int cast.
375 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000376 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000377 }
378
Anders Carlssonaba8c572008-02-01 23:17:55 +0000379 // A scalar source can be splatted to an OCU vector of the same element type
Chris Lattner4f025a42008-02-02 04:51:41 +0000380 if (DstType->isOCUVectorType() && !isa<VectorType>(SrcType) &&
381 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000382 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
383 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000384
Chris Lattner4f025a42008-02-02 04:51:41 +0000385 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000386 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000387 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000388 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000389
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000390 // Finally, we have the arithmetic types: real int/float.
391 if (isa<llvm::IntegerType>(Src->getType())) {
392 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000393 if (isa<llvm::IntegerType>(DstTy))
394 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
395 else if (InputSigned)
396 return Builder.CreateSIToFP(Src, DstTy, "conv");
397 else
398 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000399 }
400
401 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
402 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000403 if (DstType->isSignedIntegerType())
404 return Builder.CreateFPToSI(Src, DstTy, "conv");
405 else
406 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000407 }
408
409 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000410 if (DstTy->getTypeID() < Src->getType()->getTypeID())
411 return Builder.CreateFPTrunc(Src, DstTy, "conv");
412 else
413 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000414}
415
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000416/// EmitComplexToScalarConversion - Emit a conversion from the specified
417/// complex type to the specified destination type, where the destination
418/// type is an LLVM scalar type.
419Value *ScalarExprEmitter::
420EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
421 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000422 // Get the source element type.
423 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
424
425 // Handle conversions to bool first, they are special: comparisons against 0.
426 if (DstTy->isBooleanType()) {
427 // Complex != 0 -> (Real != 0) | (Imag != 0)
428 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
429 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
430 return Builder.CreateOr(Src.first, Src.second, "tobool");
431 }
432
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000433 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
434 // the imaginary part of the complex value is discarded and the value of the
435 // real part is converted according to the conversion rules for the
436 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000437 return EmitScalarConversion(Src.first, SrcTy, DstTy);
438}
439
440
Chris Lattner9fba49a2007-08-24 05:35:26 +0000441//===----------------------------------------------------------------------===//
442// Visitor Methods
443//===----------------------------------------------------------------------===//
444
445Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000446 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000447 if (E->getType()->isVoidType())
448 return 0;
449 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
450}
451
Chris Lattnercbfb5512008-03-01 08:45:05 +0000452Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
453 // Only the lookup mechanism and first two arguments of the method
454 // implementation vary between runtimes. We can get the receiver and
455 // arguments in generic code.
456
457 // Find the receiver
458 llvm::Value * Receiver = CGF.EmitScalarExpr(E->getReceiver());
459
460 // Process the arguments
461 unsigned int ArgC = E->getNumArgs();
462 llvm::SmallVector<llvm::Value*, 16> Args;
463 for(unsigned i=0 ; i<ArgC ; i++) {
464 Expr *ArgExpr = E->getArg(i);
465 QualType ArgTy = ArgExpr->getType();
466 if (!CGF.hasAggregateLLVMType(ArgTy)) {
467 // Scalar argument is passed by-value.
468 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
469 } else if (ArgTy->isComplexType()) {
470 // Make a temporary alloca to pass the argument.
471 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
472 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
473 Args.push_back(DestMem);
474 } else {
475 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
476 CGF.EmitAggExpr(ArgExpr, DestMem, false);
477 Args.push_back(DestMem);
478 }
479 }
480
481 // Get the selector string
482 std::string SelStr = E->getSelector().getName();
483 llvm::Constant *Selector = CGF.CGM.GetAddrOfConstantString(SelStr);
484 ConvertType(E->getType());
485 return Runtime->generateMessageSend(Builder,
486 ConvertType(E->getType()),
487 Receiver,
488 Selector,
489 &Args[0],
490 Args.size());
491}
492
Chris Lattner9fba49a2007-08-24 05:35:26 +0000493Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
494 // Emit subscript expressions in rvalue context's. For most cases, this just
495 // loads the lvalue formed by the subscript expr. However, we have to be
496 // careful, because the base of a vector subscript is occasionally an rvalue,
497 // so we can't get it as an lvalue.
498 if (!E->getBase()->getType()->isVectorType())
499 return EmitLoadOfLValue(E);
500
501 // Handle the vector case. The base must be a vector, the index must be an
502 // integer value.
503 Value *Base = Visit(E->getBase());
504 Value *Idx = Visit(E->getIdx());
505
506 // FIXME: Convert Idx to i32 type.
507 return Builder.CreateExtractElement(Base, Idx, "vecext");
508}
509
510/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
511/// also handle things like function to pointer-to-function decay, and array to
512/// pointer decay.
513Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
514 const Expr *Op = E->getSubExpr();
515
516 // If this is due to array->pointer conversion, emit the array expression as
517 // an l-value.
518 if (Op->getType()->isArrayType()) {
519 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
520 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000521 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000522
523 assert(isa<llvm::PointerType>(V->getType()) &&
524 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
525 ->getElementType()) &&
526 "Doesn't support VLAs yet!");
527 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000528
529 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000530 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
531
532 // The resultant pointer type can be implicitly casted to other pointer
533 // types as well, for example void*.
534 const llvm::Type *DestPTy = ConvertType(E->getType());
535 assert(isa<llvm::PointerType>(DestPTy) &&
536 "Only expect implicit cast to pointer");
537 if (V->getType() != DestPTy)
538 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
539 return V;
540
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000541 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000542 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
543 getReferenceeType() ==
544 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000545
546 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000547 }
548
549 return EmitCastExpr(Op, E->getType());
550}
551
552
553// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
554// have to handle a more broad range of conversions than explicit casts, as they
555// handle things like function to ptr-to-function decay etc.
556Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000557 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000558
559 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000560 Value *Src = Visit(const_cast<Expr*>(E));
561
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000562 // Use EmitScalarConversion to perform the conversion.
563 return EmitScalarConversion(Src, E->getType(), DestTy);
564 }
Chris Lattner77288792008-02-16 23:55:16 +0000565
566 if (E->getType()->isComplexType()) {
567 // Handle cases where the source is a complex type.
568 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
569 DestTy);
570 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000571
Chris Lattner77288792008-02-16 23:55:16 +0000572 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
573 // evaluate the result and return.
574 CGF.EmitAggExpr(E, 0, false);
575 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000576}
577
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000578Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000579 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000580}
581
582
Chris Lattner9fba49a2007-08-24 05:35:26 +0000583//===----------------------------------------------------------------------===//
584// Unary Operators
585//===----------------------------------------------------------------------===//
586
587Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000588 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000589 LValue LV = EmitLValue(E->getSubExpr());
590 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000591 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000592 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593
594 int AmountVal = isInc ? 1 : -1;
595
596 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000597 if (isa<llvm::PointerType>(InVal->getType())) {
598 // FIXME: This isn't right for VLAs.
599 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
600 NextVal = Builder.CreateGEP(InVal, NextVal);
601 } else {
602 // Add the inc/dec to the real part.
603 if (isa<llvm::IntegerType>(InVal->getType()))
604 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000605 else if (InVal->getType() == llvm::Type::FloatTy)
606 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000607 NextVal =
608 llvm::ConstantFP::get(InVal->getType(),
609 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000610 else {
611 // FIXME: Handle long double.
612 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000613 NextVal =
614 llvm::ConstantFP::get(InVal->getType(),
615 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000616 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000617 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
618 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000619
620 // Store the updated result through the lvalue.
621 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
622 E->getSubExpr()->getType());
623
624 // If this is a postinc, return the value read from memory, otherwise use the
625 // updated value.
626 return isPre ? NextVal : InVal;
627}
628
629
630Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
631 Value *Op = Visit(E->getSubExpr());
632 return Builder.CreateNeg(Op, "neg");
633}
634
635Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
636 Value *Op = Visit(E->getSubExpr());
637 return Builder.CreateNot(Op, "neg");
638}
639
640Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
641 // Compare operand to zero.
642 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
643
644 // Invert value.
645 // TODO: Could dynamically modify easy computations here. For example, if
646 // the operand is an icmp ne, turn into icmp eq.
647 BoolVal = Builder.CreateNot(BoolVal, "lnot");
648
649 // ZExt result to int.
650 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
651}
652
653/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
654/// an integer (RetType).
655Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000656 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000657 assert(RetType->isIntegerType() && "Result type must be an integer!");
658 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000659 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000660
661 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
662 if (TypeToSize->isVoidType())
663 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
664
Chris Lattner9fba49a2007-08-24 05:35:26 +0000665 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000666 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000667
668 uint64_t Val = isSizeOf ? Info.first : Info.second;
669 Val /= 8; // Return size in bytes, not bits.
670
Chris Lattner9fba49a2007-08-24 05:35:26 +0000671 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
672}
673
Chris Lattner01211af2007-08-24 21:20:17 +0000674Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
675 Expr *Op = E->getSubExpr();
676 if (Op->getType()->isComplexType())
677 return CGF.EmitComplexExpr(Op).first;
678 return Visit(Op);
679}
680Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
681 Expr *Op = E->getSubExpr();
682 if (Op->getType()->isComplexType())
683 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000684
685 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
686 // effects are evaluated.
687 CGF.EmitScalarExpr(Op);
688 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000689}
690
Anders Carlsson52774ad2008-01-29 15:56:48 +0000691Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
692{
693 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
694
695 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
696
Chris Lattner8cd0e932008-03-05 18:54:05 +0000697 uint32_t ResultWidth =
698 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000699 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
700}
Chris Lattner01211af2007-08-24 21:20:17 +0000701
Chris Lattner9fba49a2007-08-24 05:35:26 +0000702//===----------------------------------------------------------------------===//
703// Binary Operators
704//===----------------------------------------------------------------------===//
705
706BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
707 BinOpInfo Result;
708 Result.LHS = Visit(E->getLHS());
709 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000710 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000711 Result.E = E;
712 return Result;
713}
714
Chris Lattner0d965302007-08-26 21:41:21 +0000715Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000716 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
717 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
718
719 BinOpInfo OpInfo;
720
721 // Load the LHS and RHS operands.
722 LValue LHSLV = EmitLValue(E->getLHS());
723 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000724
725 // Determine the computation type. If the RHS is complex, then this is one of
726 // the add/sub/mul/div operators. All of these operators can be computed in
727 // with just their real component even though the computation domain really is
728 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000729 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000730
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000731 // If the computation type is complex, then the RHS is complex. Emit the RHS.
732 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
733 ComputeType = CT->getElementType();
734
735 // Emit the RHS, only keeping the real component.
736 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
737 RHSTy = RHSTy->getAsComplexType()->getElementType();
738 } else {
739 // Otherwise the RHS is a simple scalar value.
740 OpInfo.RHS = Visit(E->getRHS());
741 }
742
743 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000744 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000745
Devang Patel04011802007-10-25 22:19:13 +0000746 // Do not merge types for -= or += where the LHS is a pointer.
747 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000748 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000749 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000750 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000751 }
752 OpInfo.Ty = ComputeType;
753 OpInfo.E = E;
754
755 // Expand the binary operator.
756 Value *Result = (this->*Func)(OpInfo);
757
758 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000759 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000760
761 // Store the result value into the LHS lvalue.
762 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
763
764 return Result;
765}
766
767
Chris Lattner9fba49a2007-08-24 05:35:26 +0000768Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000769 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000770 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000771 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000772 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
773 else
774 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
775}
776
777Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
778 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000779 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000780 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
781 else
782 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
783}
784
785
786Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000787 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000788 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000789
790 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000791 Value *Ptr, *Idx;
792 Expr *IdxExp;
793 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
794 Ptr = Ops.LHS;
795 Idx = Ops.RHS;
796 IdxExp = Ops.E->getRHS();
797 } else { // int + pointer
798 Ptr = Ops.RHS;
799 Idx = Ops.LHS;
800 IdxExp = Ops.E->getLHS();
801 }
802
803 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
804 if (Width < CGF.LLVMPointerWidth) {
805 // Zero or sign extend the pointer value based on whether the index is
806 // signed or not.
807 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
808 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
809 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
810 else
811 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
812 }
813
814 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000815}
816
817Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
818 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
819 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
820
Chris Lattner660e31d2007-08-24 21:00:35 +0000821 // pointer - int
822 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
823 "ptr-ptr shouldn't get here");
824 // FIXME: The pointer could point to a VLA.
Chris Lattnere78c1ea2008-01-31 04:12:50 +0000825 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
826
827 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
828 if (Width < CGF.LLVMPointerWidth) {
829 // Zero or sign extend the pointer value based on whether the index is
830 // signed or not.
831 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
832 if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
833 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
834 else
835 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
836 }
837
838 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner660e31d2007-08-24 21:00:35 +0000839}
840
841Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
842 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
843 // the compound assignment case it is invalid, so just handle it here.
844 if (!E->getRHS()->getType()->isPointerType())
845 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000846
847 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000848 Value *LHS = Visit(E->getLHS());
849 Value *RHS = Visit(E->getRHS());
850
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000851 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000852 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner8cd0e932008-03-05 18:54:05 +0000853 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000854
855 const llvm::Type *ResultType = ConvertType(E->getType());
856 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
857 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
858 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000859
860 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
861 // remainder. As such, we handle common power-of-two cases here to generate
862 // better code.
863 if (llvm::isPowerOf2_64(ElementSize)) {
864 Value *ShAmt =
865 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
866 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
867 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000868
Chris Lattner9fba49a2007-08-24 05:35:26 +0000869 // Otherwise, do a full sdiv.
870 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
871 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
872}
873
Chris Lattner660e31d2007-08-24 21:00:35 +0000874
Chris Lattner9fba49a2007-08-24 05:35:26 +0000875Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
876 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
877 // RHS to the same size as the LHS.
878 Value *RHS = Ops.RHS;
879 if (Ops.LHS->getType() != RHS->getType())
880 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
881
882 return Builder.CreateShl(Ops.LHS, RHS, "shl");
883}
884
885Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
886 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
887 // RHS to the same size as the LHS.
888 Value *RHS = Ops.RHS;
889 if (Ops.LHS->getType() != RHS->getType())
890 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
891
Chris Lattner660e31d2007-08-24 21:00:35 +0000892 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000893 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
894 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
895}
896
897Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
898 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000899 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000900 QualType LHSTy = E->getLHS()->getType();
901 if (!LHSTy->isComplexType()) {
902 Value *LHS = Visit(E->getLHS());
903 Value *RHS = Visit(E->getRHS());
904
905 if (LHS->getType()->isFloatingPoint()) {
906 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
907 LHS, RHS, "cmp");
908 } else if (LHSTy->isUnsignedIntegerType()) {
909 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
910 LHS, RHS, "cmp");
911 } else {
912 // Signed integers and pointers.
913 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
914 LHS, RHS, "cmp");
915 }
916 } else {
917 // Complex Comparison: can only be an equality comparison.
918 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
919 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
920
921 QualType CETy =
922 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
923
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000924 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000925 if (CETy->isRealFloatingType()) {
926 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
927 LHS.first, RHS.first, "cmp.r");
928 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
929 LHS.second, RHS.second, "cmp.i");
930 } else {
931 // Complex comparisons can only be equality comparisons. As such, signed
932 // and unsigned opcodes are the same.
933 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
934 LHS.first, RHS.first, "cmp.r");
935 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
936 LHS.second, RHS.second, "cmp.i");
937 }
938
939 if (E->getOpcode() == BinaryOperator::EQ) {
940 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
941 } else {
942 assert(E->getOpcode() == BinaryOperator::NE &&
943 "Complex comparison other than == or != ?");
944 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
945 }
946 }
947
948 // ZExt result to int.
949 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
950}
951
952Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
953 LValue LHS = EmitLValue(E->getLHS());
954 Value *RHS = Visit(E->getRHS());
955
956 // Store the value into the LHS.
957 // FIXME: Volatility!
958 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
959
960 // Return the RHS.
961 return RHS;
962}
963
964Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
965 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
966
967 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
968 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
969
970 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
971 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
972
973 CGF.EmitBlock(RHSBlock);
974 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
975
976 // Reaquire the RHS block, as there may be subblocks inserted.
977 RHSBlock = Builder.GetInsertBlock();
978 CGF.EmitBlock(ContBlock);
979
980 // Create a PHI node. If we just evaluted the LHS condition, the result is
981 // false. If we evaluated both, the result is the RHS condition.
982 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
983 PN->reserveOperandSpace(2);
984 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
985 PN->addIncoming(RHSCond, RHSBlock);
986
987 // ZExt result to int.
988 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
989}
990
991Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
992 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
993
994 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
995 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
996
997 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
998 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
999
1000 CGF.EmitBlock(RHSBlock);
1001 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1002
1003 // Reaquire the RHS block, as there may be subblocks inserted.
1004 RHSBlock = Builder.GetInsertBlock();
1005 CGF.EmitBlock(ContBlock);
1006
1007 // Create a PHI node. If we just evaluted the LHS condition, the result is
1008 // true. If we evaluated both, the result is the RHS condition.
1009 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1010 PN->reserveOperandSpace(2);
1011 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1012 PN->addIncoming(RHSCond, RHSBlock);
1013
1014 // ZExt result to int.
1015 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1016}
1017
1018Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1019 CGF.EmitStmt(E->getLHS());
1020 return Visit(E->getRHS());
1021}
1022
1023//===----------------------------------------------------------------------===//
1024// Other Operators
1025//===----------------------------------------------------------------------===//
1026
1027Value *ScalarExprEmitter::
1028VisitConditionalOperator(const ConditionalOperator *E) {
1029 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1030 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1031 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1032
Chris Lattner98a425c2007-11-26 01:40:58 +00001033 // Evaluate the conditional, then convert it to bool. We do this explicitly
1034 // because we need the unconverted value if this is a GNU ?: expression with
1035 // missing middle value.
1036 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001037 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1038 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001039 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001040
1041 CGF.EmitBlock(LHSBlock);
1042
1043 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001044 Value *LHS;
1045 if (E->getLHS())
1046 LHS = Visit(E->getLHS());
1047 else // Perform promotions, to handle cases like "short ?: int"
1048 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1049
Chris Lattner9fba49a2007-08-24 05:35:26 +00001050 Builder.CreateBr(ContBlock);
1051 LHSBlock = Builder.GetInsertBlock();
1052
1053 CGF.EmitBlock(RHSBlock);
1054
1055 Value *RHS = Visit(E->getRHS());
1056 Builder.CreateBr(ContBlock);
1057 RHSBlock = Builder.GetInsertBlock();
1058
1059 CGF.EmitBlock(ContBlock);
1060
Chris Lattner307da022007-11-30 17:56:23 +00001061 if (!LHS) {
1062 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1063 return 0;
1064 }
1065
Chris Lattner9fba49a2007-08-24 05:35:26 +00001066 // Create a PHI node for the real part.
1067 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1068 PN->reserveOperandSpace(2);
1069 PN->addIncoming(LHS, LHSBlock);
1070 PN->addIncoming(RHS, RHSBlock);
1071 return PN;
1072}
1073
1074Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001075 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001076 return
1077 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001078}
1079
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001080Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001081 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1082 E->getNumArgs(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001083}
1084
Chris Lattner307da022007-11-30 17:56:23 +00001085Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001086 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1087
1088 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1089 return V;
1090}
1091
Chris Lattner307da022007-11-30 17:56:23 +00001092Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001093 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001094 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1095 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1096 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001097
1098 llvm::Constant *C = llvm::ConstantArray::get(str);
1099 C = new llvm::GlobalVariable(C->getType(), true,
1100 llvm::GlobalValue::InternalLinkage,
1101 C, ".str", &CGF.CGM.getModule());
1102 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1103 llvm::Constant *Zeros[] = { Zero, Zero };
1104 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1105
1106 return C;
1107}
1108
Chris Lattner9fba49a2007-08-24 05:35:26 +00001109//===----------------------------------------------------------------------===//
1110// Entry Point into this File
1111//===----------------------------------------------------------------------===//
1112
1113/// EmitComplexExpr - Emit the computation of the specified expression of
1114/// complex type, ignoring the result.
1115Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1116 assert(E && !hasAggregateLLVMType(E->getType()) &&
1117 "Invalid scalar expression to emit");
1118
1119 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1120}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001121
1122/// EmitScalarConversion - Emit a conversion from the specified type to the
1123/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001124Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1125 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001126 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1127 "Invalid scalar expression to emit");
1128 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1129}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001130
1131/// EmitComplexToScalarConversion - Emit a conversion from the specified
1132/// complex type to the specified destination type, where the destination
1133/// type is an LLVM scalar type.
1134Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1135 QualType SrcTy,
1136 QualType DstTy) {
1137 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1138 "Invalid complex -> scalar conversion");
1139 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1140 DstTy);
1141}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001142
1143Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1144 assert(V1->getType() == V2->getType() &&
1145 "Vector operands must be of the same type");
1146
1147 unsigned NumElements =
1148 cast<llvm::VectorType>(V1->getType())->getNumElements();
1149
1150 va_list va;
1151 va_start(va, V2);
1152
1153 llvm::SmallVector<llvm::Constant*, 16> Args;
1154
1155 for (unsigned i = 0; i < NumElements; i++) {
1156 int n = va_arg(va, int);
1157
1158 assert(n >= 0 && n < (int)NumElements * 2 &&
1159 "Vector shuffle index out of bounds!");
1160
1161 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1162 }
1163
1164 const char *Name = va_arg(va, const char *);
1165 va_end(va);
1166
1167 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1168
1169 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1170}
1171
Anders Carlsson68b8be92007-12-15 21:23:30 +00001172llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001173 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001174{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001175 llvm::Value *Vec
1176 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1177
1178 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001179 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001180 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001181 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001182 }
1183
1184 return Vec;
1185}