blob: 4eb906269aeaa1eda11997eebd854475cc003e6d [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"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000016#include "CGObjCRuntime.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000026#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000027
Chris Lattner9fba49a2007-08-24 05:35:26 +000028using namespace clang;
29using namespace CodeGen;
30using llvm::Value;
31
32//===----------------------------------------------------------------------===//
33// Scalar Expression Emitter
34//===----------------------------------------------------------------------===//
35
36struct BinOpInfo {
37 Value *LHS;
38 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000039 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000040 const BinaryOperator *E;
41};
42
43namespace {
44class VISIBILITY_HIDDEN ScalarExprEmitter
45 : public StmtVisitor<ScalarExprEmitter, Value*> {
46 CodeGenFunction &CGF;
Chris Lattnerfaf23db2008-08-08 19:57:58 +000047 llvm::IRBuilder<> &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000048 CGObjCRuntime *Runtime;
49
Chris Lattner9fba49a2007-08-24 05:35:26 +000050public:
51
Chris Lattnercbfb5512008-03-01 08:45:05 +000052 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
53 Builder(CGF.Builder),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000054 Runtime(0) {
55 if (CGF.CGM.hasObjCRuntime())
56 Runtime = &CGF.CGM.getObjCRuntime();
Chris Lattner9fba49a2007-08-24 05:35:26 +000057 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000058
59 //===--------------------------------------------------------------------===//
60 // Utilities
61 //===--------------------------------------------------------------------===//
62
63 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
64 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
65
66 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000067 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000068 }
69
70 /// EmitLoadOfLValue - Given an expression with complex type that represents a
71 /// value l-value, this method emits the address of the l-value, then loads
72 /// and returns the result.
73 Value *EmitLoadOfLValue(const Expr *E) {
74 // FIXME: Volatile
75 return EmitLoadOfLValue(EmitLValue(E), E->getType());
76 }
77
Chris Lattnerd8d44222007-08-26 16:42:57 +000078 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000079 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000080 Value *EmitConversionToBool(Value *Src, QualType DstTy);
81
Chris Lattner4e05d1e2007-08-26 06:48:56 +000082 /// EmitScalarConversion - Emit a conversion from the specified type to the
83 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000084 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
85
86 /// EmitComplexToScalarConversion - Emit a conversion from the specified
87 /// complex type to the specified destination type, where the destination
88 /// type is an LLVM scalar type.
89 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
90 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000091
Chris Lattner9fba49a2007-08-24 05:35:26 +000092 //===--------------------------------------------------------------------===//
93 // Visitor Methods
94 //===--------------------------------------------------------------------===//
95
96 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000097 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000098 assert(0 && "Stmt can't have complex result type!");
99 return 0;
100 }
101 Value *VisitExpr(Expr *S);
102 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
103
104 // Leaves.
105 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
106 return llvm::ConstantInt::get(E->getValue());
107 }
108 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000109 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000110 }
111 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
112 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
113 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000114 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
115 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
116 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000117 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
118 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000119 CGF.getContext().typesAreCompatible(
120 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000121 }
122 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
123 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
124 }
Daniel Dunbar879788d2008-08-04 16:51:22 +0000125 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000126 llvm::Value *V =
127 llvm::ConstantInt::get(llvm::Type::Int32Ty,
128 CGF.GetIDForAddrOfLabel(E->getLabel()));
129
130 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000131 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000132
133 // l-values.
134 Value *VisitDeclRefExpr(DeclRefExpr *E) {
135 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
136 return llvm::ConstantInt::get(EC->getInitVal());
137 return EmitLoadOfLValue(E);
138 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000139 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbara5a0cdb2008-08-12 03:55:34 +0000140 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E);
Daniel Dunbarfa456242008-08-12 05:08:18 +0000141 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E);
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000142 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000143 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000144 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000145 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000146 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000147 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000148 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattner69909292008-08-10 01:53:14 +0000149 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000150
151 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000152 unsigned NumInitElements = E->getNumInits();
153
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000154 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000155 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
156
157 // We have a scalar in braces. Just use the first element.
158 if (!VType)
159 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000160
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000161 unsigned NumVectorElements = VType->getNumElements();
162 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000163
164 // Emit individual vector element stores.
165 llvm::Value *V = llvm::UndefValue::get(VType);
166
Anders Carlsson323d5682007-12-18 02:45:33 +0000167 // Emit initializers
168 unsigned i;
169 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000170 Value *NewV = Visit(E->getInit(i));
171 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
172 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000173 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000174
175 // Emit remaining default initializers
176 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
177 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
178 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
179 V = Builder.CreateInsertElement(V, NewV, Idx);
180 }
181
Devang Patel32c39832007-10-24 18:05:48 +0000182 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000183 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000184
Chris Lattner9fba49a2007-08-24 05:35:26 +0000185 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
186 Value *VisitCastExpr(const CastExpr *E) {
187 return EmitCastExpr(E->getSubExpr(), E->getType());
188 }
189 Value *EmitCastExpr(const Expr *E, QualType T);
190
191 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000192 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000193 }
194
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000195 Value *VisitStmtExpr(const StmtExpr *E);
196
Chris Lattner9fba49a2007-08-24 05:35:26 +0000197 // Unary Operators.
198 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
199 Value *VisitUnaryPostDec(const UnaryOperator *E) {
200 return VisitPrePostIncDec(E, false, false);
201 }
202 Value *VisitUnaryPostInc(const UnaryOperator *E) {
203 return VisitPrePostIncDec(E, true, false);
204 }
205 Value *VisitUnaryPreDec(const UnaryOperator *E) {
206 return VisitPrePostIncDec(E, false, true);
207 }
208 Value *VisitUnaryPreInc(const UnaryOperator *E) {
209 return VisitPrePostIncDec(E, true, true);
210 }
211 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
212 return EmitLValue(E->getSubExpr()).getAddress();
213 }
214 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
215 Value *VisitUnaryPlus(const UnaryOperator *E) {
216 return Visit(E->getSubExpr());
217 }
218 Value *VisitUnaryMinus (const UnaryOperator *E);
219 Value *VisitUnaryNot (const UnaryOperator *E);
220 Value *VisitUnaryLNot (const UnaryOperator *E);
221 Value *VisitUnarySizeOf (const UnaryOperator *E) {
222 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
223 }
224 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
225 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
226 }
227 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000228 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000229 Value *VisitUnaryReal (const UnaryOperator *E);
230 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000231 Value *VisitUnaryExtension(const UnaryOperator *E) {
232 return Visit(E->getSubExpr());
233 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000234 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000235 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
236 return Visit(DAE->getExpr());
237 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000238
Chris Lattner9fba49a2007-08-24 05:35:26 +0000239 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000240 Value *EmitMul(const BinOpInfo &Ops) {
241 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
242 }
243 Value *EmitDiv(const BinOpInfo &Ops);
244 Value *EmitRem(const BinOpInfo &Ops);
245 Value *EmitAdd(const BinOpInfo &Ops);
246 Value *EmitSub(const BinOpInfo &Ops);
247 Value *EmitShl(const BinOpInfo &Ops);
248 Value *EmitShr(const BinOpInfo &Ops);
249 Value *EmitAnd(const BinOpInfo &Ops) {
250 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
251 }
252 Value *EmitXor(const BinOpInfo &Ops) {
253 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
254 }
255 Value *EmitOr (const BinOpInfo &Ops) {
256 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
257 }
258
Chris Lattner660e31d2007-08-24 21:00:35 +0000259 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000260 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000261 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
262
263 // Binary operators and binary compound assignment operators.
264#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000265 Value *VisitBin ## OP(const BinaryOperator *E) { \
266 return Emit ## OP(EmitBinOps(E)); \
267 } \
268 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
269 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000270 }
271 HANDLEBINOP(Mul);
272 HANDLEBINOP(Div);
273 HANDLEBINOP(Rem);
274 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000275 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000276 HANDLEBINOP(Shl);
277 HANDLEBINOP(Shr);
278 HANDLEBINOP(And);
279 HANDLEBINOP(Xor);
280 HANDLEBINOP(Or);
281#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000282
Chris Lattner9fba49a2007-08-24 05:35:26 +0000283 // Comparisons.
284 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
285 unsigned SICmpOpc, unsigned FCmpOpc);
286#define VISITCOMP(CODE, UI, SI, FP) \
287 Value *VisitBin##CODE(const BinaryOperator *E) { \
288 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
289 llvm::FCmpInst::FP); }
290 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
291 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
292 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
293 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
294 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
295 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
296#undef VISITCOMP
297
298 Value *VisitBinAssign (const BinaryOperator *E);
299
300 Value *VisitBinLAnd (const BinaryOperator *E);
301 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000302 Value *VisitBinComma (const BinaryOperator *E);
303
304 // Other Operators.
305 Value *VisitConditionalOperator(const ConditionalOperator *CO);
306 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000307 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000308 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000309 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
310 return CGF.EmitObjCStringLiteral(E);
311 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000312 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000313};
314} // end anonymous namespace.
315
316//===----------------------------------------------------------------------===//
317// Utilities
318//===----------------------------------------------------------------------===//
319
Chris Lattnerd8d44222007-08-26 16:42:57 +0000320/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000321/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000322Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
323 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
324
325 if (SrcType->isRealFloatingType()) {
326 // Compare against 0.0 for fp scalars.
327 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000328 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
329 }
330
331 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
332 "Unknown scalar type to convert");
333
334 // Because of the type rules of C, we often end up computing a logical value,
335 // then zero extending it to int, then wanting it as a logical value again.
336 // Optimize this common case.
337 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
338 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
339 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000340 // If there aren't any more uses, zap the instruction to save space.
341 // Note that there can be more uses, for example if this
342 // is the result of an assignment.
343 if (ZI->use_empty())
344 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000345 return Result;
346 }
347 }
348
349 // Compare against an integer or pointer null.
350 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
351 return Builder.CreateICmpNE(Src, Zero, "tobool");
352}
353
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000354/// EmitScalarConversion - Emit a conversion from the specified type to the
355/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000356Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
357 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000358 SrcType = CGF.getContext().getCanonicalType(SrcType);
359 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000360 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000361
362 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000363
364 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000365 if (DstType->isBooleanType())
366 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000367
368 const llvm::Type *DstTy = ConvertType(DstType);
369
370 // Ignore conversions like int -> uint.
371 if (Src->getType() == DstTy)
372 return Src;
373
374 // Handle pointer conversions next: pointers can only be converted to/from
375 // other pointers and integers.
376 if (isa<PointerType>(DstType)) {
377 // The source value may be an integer, or a pointer.
378 if (isa<llvm::PointerType>(Src->getType()))
379 return Builder.CreateBitCast(Src, DstTy, "conv");
380 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
381 return Builder.CreateIntToPtr(Src, DstTy, "conv");
382 }
383
384 if (isa<PointerType>(SrcType)) {
385 // Must be an ptr to int cast.
386 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000387 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000388 }
389
Nate Begemanaf6ed502008-04-18 23:10:10 +0000390 // A scalar can be splatted to an extended vector of the same element type
391 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner4f025a42008-02-02 04:51:41 +0000392 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000393 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
394 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000395
Chris Lattner4f025a42008-02-02 04:51:41 +0000396 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000397 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000398 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000399 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000400
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000401 // Finally, we have the arithmetic types: real int/float.
402 if (isa<llvm::IntegerType>(Src->getType())) {
403 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000404 if (isa<llvm::IntegerType>(DstTy))
405 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
406 else if (InputSigned)
407 return Builder.CreateSIToFP(Src, DstTy, "conv");
408 else
409 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000410 }
411
412 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
413 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000414 if (DstType->isSignedIntegerType())
415 return Builder.CreateFPToSI(Src, DstTy, "conv");
416 else
417 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000418 }
419
420 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000421 if (DstTy->getTypeID() < Src->getType()->getTypeID())
422 return Builder.CreateFPTrunc(Src, DstTy, "conv");
423 else
424 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000425}
426
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000427/// EmitComplexToScalarConversion - Emit a conversion from the specified
428/// complex type to the specified destination type, where the destination
429/// type is an LLVM scalar type.
430Value *ScalarExprEmitter::
431EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
432 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000433 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000434 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000435
436 // Handle conversions to bool first, they are special: comparisons against 0.
437 if (DstTy->isBooleanType()) {
438 // Complex != 0 -> (Real != 0) | (Imag != 0)
439 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
440 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
441 return Builder.CreateOr(Src.first, Src.second, "tobool");
442 }
443
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000444 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
445 // the imaginary part of the complex value is discarded and the value of the
446 // real part is converted according to the conversion rules for the
447 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000448 return EmitScalarConversion(Src.first, SrcTy, DstTy);
449}
450
451
Chris Lattner9fba49a2007-08-24 05:35:26 +0000452//===----------------------------------------------------------------------===//
453// Visitor Methods
454//===----------------------------------------------------------------------===//
455
456Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000457 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000458 if (E->getType()->isVoidType())
459 return 0;
460 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
461}
462
Eli Friedmand0e9d092008-05-14 19:38:39 +0000463Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
464 llvm::SmallVector<llvm::Constant*, 32> indices;
465 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
466 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
467 }
468 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
469 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
470 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
471 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
472}
473
Chris Lattnercbfb5512008-03-01 08:45:05 +0000474Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
475 // Only the lookup mechanism and first two arguments of the method
476 // implementation vary between runtimes. We can get the receiver and
477 // arguments in generic code.
478
479 // Find the receiver
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000480 llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000481
482 // Process the arguments
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000483 unsigned ArgC = E->getNumArgs();
Chris Lattnercbfb5512008-03-01 08:45:05 +0000484 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000485 for (unsigned i = 0; i != ArgC; ++i) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000486 Expr *ArgExpr = E->getArg(i);
487 QualType ArgTy = ArgExpr->getType();
488 if (!CGF.hasAggregateLLVMType(ArgTy)) {
489 // Scalar argument is passed by-value.
490 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
Chris Lattnerde0908b2008-04-04 16:54:41 +0000491 } else if (ArgTy->isAnyComplexType()) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000492 // Make a temporary alloca to pass the argument.
493 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
494 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
495 Args.push_back(DestMem);
496 } else {
497 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
498 CGF.EmitAggExpr(ArgExpr, DestMem, false);
499 Args.push_back(DestMem);
500 }
501 }
502
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000503 return Runtime->GenerateMessageSend(Builder, ConvertType(E->getType()),
Chris Lattner8384c142008-06-26 04:42:20 +0000504 Receiver, E->getSelector(),
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000505 &Args[0], Args.size());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000506}
507
Daniel Dunbara5a0cdb2008-08-12 03:55:34 +0000508Value *ScalarExprEmitter::VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
509 return Runtime->GetSelector(Builder, E->getSelector());
510}
511
Daniel Dunbarfa456242008-08-12 05:08:18 +0000512Value *ScalarExprEmitter::VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
513 // FIXME: This should pass the Decl not the name.
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000514 return Runtime->GenerateProtocolRef(Builder, E->getProtocol());
Daniel Dunbarfa456242008-08-12 05:08:18 +0000515}
516
Chris Lattner9fba49a2007-08-24 05:35:26 +0000517Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
518 // Emit subscript expressions in rvalue context's. For most cases, this just
519 // loads the lvalue formed by the subscript expr. However, we have to be
520 // careful, because the base of a vector subscript is occasionally an rvalue,
521 // so we can't get it as an lvalue.
522 if (!E->getBase()->getType()->isVectorType())
523 return EmitLoadOfLValue(E);
524
525 // Handle the vector case. The base must be a vector, the index must be an
526 // integer value.
527 Value *Base = Visit(E->getBase());
528 Value *Idx = Visit(E->getIdx());
529
530 // FIXME: Convert Idx to i32 type.
531 return Builder.CreateExtractElement(Base, Idx, "vecext");
532}
533
534/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
535/// also handle things like function to pointer-to-function decay, and array to
536/// pointer decay.
537Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
538 const Expr *Op = E->getSubExpr();
539
540 // If this is due to array->pointer conversion, emit the array expression as
541 // an l-value.
542 if (Op->getType()->isArrayType()) {
543 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
544 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000545 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000546
547 assert(isa<llvm::PointerType>(V->getType()) &&
548 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
549 ->getElementType()) &&
550 "Doesn't support VLAs yet!");
Chris Lattner07307562008-03-19 05:19:41 +0000551 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000552
553 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000554 // types as well (e.g. void*) and can be implicitly converted to integer.
555 const llvm::Type *DestTy = ConvertType(E->getType());
556 if (V->getType() != DestTy) {
557 if (isa<llvm::PointerType>(DestTy))
558 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
559 else {
560 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
561 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
562 }
563 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000564 return V;
565
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000566 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000567 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000568 }
569
570 return EmitCastExpr(Op, E->getType());
571}
572
573
574// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
575// have to handle a more broad range of conversions than explicit casts, as they
576// handle things like function to ptr-to-function decay etc.
577Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000578 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000579
580 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000581 Value *Src = Visit(const_cast<Expr*>(E));
582
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000583 // Use EmitScalarConversion to perform the conversion.
584 return EmitScalarConversion(Src, E->getType(), DestTy);
585 }
Chris Lattner77288792008-02-16 23:55:16 +0000586
Chris Lattnerde0908b2008-04-04 16:54:41 +0000587 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000588 // Handle cases where the source is a complex type.
589 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
590 DestTy);
591 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000592
Chris Lattner77288792008-02-16 23:55:16 +0000593 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
594 // evaluate the result and return.
595 CGF.EmitAggExpr(E, 0, false);
596 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000597}
598
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000599Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000600 return CGF.EmitCompoundStmt(*E->getSubStmt(),
601 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000602}
603
604
Chris Lattner9fba49a2007-08-24 05:35:26 +0000605//===----------------------------------------------------------------------===//
606// Unary Operators
607//===----------------------------------------------------------------------===//
608
609Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000610 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000611 LValue LV = EmitLValue(E->getSubExpr());
612 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000613 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000614 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000615
616 int AmountVal = isInc ? 1 : -1;
617
618 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000619 if (isa<llvm::PointerType>(InVal->getType())) {
620 // FIXME: This isn't right for VLAs.
621 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000622 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000623 } else {
624 // Add the inc/dec to the real part.
625 if (isa<llvm::IntegerType>(InVal->getType()))
626 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000627 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000628 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000629 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000630 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000631 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000632 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000633 else {
634 llvm::APFloat F(static_cast<float>(AmountVal));
Chris Lattner2a674dc2008-06-30 18:32:54 +0000635 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000636 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000637 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000638 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
639 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000640
641 // Store the updated result through the lvalue.
642 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
643 E->getSubExpr()->getType());
644
645 // If this is a postinc, return the value read from memory, otherwise use the
646 // updated value.
647 return isPre ? NextVal : InVal;
648}
649
650
651Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
652 Value *Op = Visit(E->getSubExpr());
653 return Builder.CreateNeg(Op, "neg");
654}
655
656Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
657 Value *Op = Visit(E->getSubExpr());
658 return Builder.CreateNot(Op, "neg");
659}
660
661Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
662 // Compare operand to zero.
663 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
664
665 // Invert value.
666 // TODO: Could dynamically modify easy computations here. For example, if
667 // the operand is an icmp ne, turn into icmp eq.
668 BoolVal = Builder.CreateNot(BoolVal, "lnot");
669
670 // ZExt result to int.
671 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
672}
673
674/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
675/// an integer (RetType).
676Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000677 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000678 assert(RetType->isIntegerType() && "Result type must be an integer!");
679 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000680 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000681
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000682 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
683 // for function types.
Daniel Dunbar1c73aa22008-07-22 19:44:18 +0000684 // FIXME: what is alignof a function type in gcc?
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000685 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattner20515462008-02-21 05:45:29 +0000686 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
687
Chris Lattner9fba49a2007-08-24 05:35:26 +0000688 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000689 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000690
691 uint64_t Val = isSizeOf ? Info.first : Info.second;
692 Val /= 8; // Return size in bytes, not bits.
693
Chris Lattner9fba49a2007-08-24 05:35:26 +0000694 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
695}
696
Chris Lattner01211af2007-08-24 21:20:17 +0000697Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
698 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000699 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000700 return CGF.EmitComplexExpr(Op).first;
701 return Visit(Op);
702}
703Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
704 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000705 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000706 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000707
708 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
709 // effects are evaluated.
710 CGF.EmitScalarExpr(Op);
711 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000712}
713
Anders Carlsson52774ad2008-01-29 15:56:48 +0000714Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
715{
716 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
717
718 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
719
Chris Lattner8cd0e932008-03-05 18:54:05 +0000720 uint32_t ResultWidth =
721 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000722 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
723}
Chris Lattner01211af2007-08-24 21:20:17 +0000724
Chris Lattner9fba49a2007-08-24 05:35:26 +0000725//===----------------------------------------------------------------------===//
726// Binary Operators
727//===----------------------------------------------------------------------===//
728
729BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
730 BinOpInfo Result;
731 Result.LHS = Visit(E->getLHS());
732 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000733 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000734 Result.E = E;
735 return Result;
736}
737
Chris Lattner0d965302007-08-26 21:41:21 +0000738Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000739 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
740 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
741
742 BinOpInfo OpInfo;
743
744 // Load the LHS and RHS operands.
745 LValue LHSLV = EmitLValue(E->getLHS());
746 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000747
748 // Determine the computation type. If the RHS is complex, then this is one of
749 // the add/sub/mul/div operators. All of these operators can be computed in
750 // with just their real component even though the computation domain really is
751 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000752 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000753
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000754 // If the computation type is complex, then the RHS is complex. Emit the RHS.
755 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
756 ComputeType = CT->getElementType();
757
758 // Emit the RHS, only keeping the real component.
759 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
760 RHSTy = RHSTy->getAsComplexType()->getElementType();
761 } else {
762 // Otherwise the RHS is a simple scalar value.
763 OpInfo.RHS = Visit(E->getRHS());
764 }
765
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000766 QualType LComputeTy, RComputeTy, ResultTy;
767
768 // Compound assignment does not contain enough information about all
769 // the types involved for pointer arithmetic cases. Figure it out
770 // here for now.
771 if (E->getLHS()->getType()->isPointerType()) {
772 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
773 assert((E->getOpcode() == BinaryOperator::AddAssign ||
774 E->getOpcode() == BinaryOperator::SubAssign) &&
775 "Invalid compound assignment operator on pointer type.");
776 LComputeTy = E->getLHS()->getType();
777
778 if (E->getRHS()->getType()->isPointerType()) {
779 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
780 // extension, the conversion from the pointer difference back to
781 // the LHS type is handled at the end.
782 assert(E->getOpcode() == BinaryOperator::SubAssign &&
783 "Invalid compound assignment operator on pointer type.");
784 RComputeTy = E->getLHS()->getType();
785 ResultTy = CGF.getContext().getPointerDiffType();
786 } else {
787 RComputeTy = E->getRHS()->getType();
788 ResultTy = LComputeTy;
789 }
790 } else if (E->getRHS()->getType()->isPointerType()) {
791 // Degenerate case of (int += ptr) allowed by GCC implicit cast
792 // extension.
793 assert(E->getOpcode() == BinaryOperator::AddAssign &&
794 "Invalid compound assignment operator on pointer type.");
795 LComputeTy = E->getLHS()->getType();
796 RComputeTy = E->getRHS()->getType();
797 ResultTy = RComputeTy;
798 } else {
799 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000800 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000801
802 // Convert the LHS/RHS values to the computation type.
803 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
804 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
805 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000806 OpInfo.E = E;
807
808 // Expand the binary operator.
809 Value *Result = (this->*Func)(OpInfo);
810
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000811 // Convert the result back to the LHS type.
812 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000813
814 // Store the result value into the LHS lvalue.
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000815 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000816
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000817 // For bitfields, we need the value in the bitfield
818 // FIXME: This adds an extra bitfield load
819 if (LHSLV.isBitfield())
820 Result = EmitLoadOfLValue(LHSLV, LHSTy);
821
Chris Lattner660e31d2007-08-24 21:00:35 +0000822 return Result;
823}
824
825
Chris Lattner9fba49a2007-08-24 05:35:26 +0000826Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000827 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000828 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000829 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000830 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
831 else
832 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
833}
834
835Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
836 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000837 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000838 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
839 else
840 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
841}
842
843
844Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000845 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000846 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000847
848 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000849 Value *Ptr, *Idx;
850 Expr *IdxExp;
851 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
852 Ptr = Ops.LHS;
853 Idx = Ops.RHS;
854 IdxExp = Ops.E->getRHS();
855 } else { // int + pointer
856 Ptr = Ops.RHS;
857 Idx = Ops.LHS;
858 IdxExp = Ops.E->getLHS();
859 }
860
861 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
862 if (Width < CGF.LLVMPointerWidth) {
863 // Zero or sign extend the pointer value based on whether the index is
864 // signed or not.
865 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000866 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000867 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
868 else
869 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
870 }
871
872 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000873}
874
875Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
876 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
877 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000878
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000879 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
880 // pointer - int
881 Value *Idx = Ops.RHS;
882 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
883 if (Width < CGF.LLVMPointerWidth) {
884 // Zero or sign extend the pointer value based on whether the index is
885 // signed or not.
886 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
887 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
888 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
889 else
890 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
891 }
892 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
893
894 // FIXME: The pointer could point to a VLA.
895 // The GNU void* - int case is automatically handled here because
896 // our LLVM type for void* is i8*.
897 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000898 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000899 // pointer - pointer
900 Value *LHS = Ops.LHS;
901 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000902
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000903 const QualType LHSType = Ops.E->getLHS()->getType();
904 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
905 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000906
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000907 // Handle GCC extension for pointer arithmetic on void* types.
908 if (LHSElementType->isVoidType()) {
909 ElementSize = 1;
910 } else {
911 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
912 }
913
914 const llvm::Type *ResultType = ConvertType(Ops.Ty);
915 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
916 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
917 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
918
919 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
920 // remainder. As such, we handle common power-of-two cases here to generate
921 // better code. See PR2247.
922 if (llvm::isPowerOf2_64(ElementSize)) {
923 Value *ShAmt =
924 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
925 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
926 }
927
928 // Otherwise, do a full sdiv.
929 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
930 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000931 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000932}
933
934Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
935 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
936 // RHS to the same size as the LHS.
937 Value *RHS = Ops.RHS;
938 if (Ops.LHS->getType() != RHS->getType())
939 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
940
941 return Builder.CreateShl(Ops.LHS, RHS, "shl");
942}
943
944Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
945 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
946 // RHS to the same size as the LHS.
947 Value *RHS = Ops.RHS;
948 if (Ops.LHS->getType() != RHS->getType())
949 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
950
Chris Lattner660e31d2007-08-24 21:00:35 +0000951 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000952 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
953 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
954}
955
956Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
957 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000958 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000959 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +0000960 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000961 Value *LHS = Visit(E->getLHS());
962 Value *RHS = Visit(E->getRHS());
963
964 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +0000965 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000966 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000967 } else if (LHSTy->isSignedIntegerType()) {
968 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000969 LHS, RHS, "cmp");
970 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000971 // Unsigned integers and pointers.
972 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000973 LHS, RHS, "cmp");
974 }
Nate Begeman1591bc52008-07-25 20:16:05 +0000975 } else if (LHSTy->isVectorType()) {
976 Value *LHS = Visit(E->getLHS());
977 Value *RHS = Visit(E->getRHS());
978
979 if (LHS->getType()->isFPOrFPVector()) {
980 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
981 LHS, RHS, "cmp");
982 } else if (LHSTy->isUnsignedIntegerType()) {
983 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
984 LHS, RHS, "cmp");
985 } else {
986 // Signed integers and pointers.
987 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
988 LHS, RHS, "cmp");
989 }
990 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000991 } else {
992 // Complex Comparison: can only be an equality comparison.
993 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
994 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
995
Chris Lattnerc154ac12008-07-26 22:37:01 +0000996 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000997
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000998 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000999 if (CETy->isRealFloatingType()) {
1000 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1001 LHS.first, RHS.first, "cmp.r");
1002 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1003 LHS.second, RHS.second, "cmp.i");
1004 } else {
1005 // Complex comparisons can only be equality comparisons. As such, signed
1006 // and unsigned opcodes are the same.
1007 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1008 LHS.first, RHS.first, "cmp.r");
1009 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1010 LHS.second, RHS.second, "cmp.i");
1011 }
1012
1013 if (E->getOpcode() == BinaryOperator::EQ) {
1014 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1015 } else {
1016 assert(E->getOpcode() == BinaryOperator::NE &&
1017 "Complex comparison other than == or != ?");
1018 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1019 }
1020 }
1021
1022 // ZExt result to int.
1023 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1024}
1025
1026Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1027 LValue LHS = EmitLValue(E->getLHS());
1028 Value *RHS = Visit(E->getRHS());
1029
1030 // Store the value into the LHS.
1031 // FIXME: Volatility!
1032 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001033
1034 // For bitfields, we need the value in the bitfield
1035 // FIXME: This adds an extra bitfield load
1036 if (LHS.isBitfield())
1037 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001038 // Return the RHS.
1039 return RHS;
1040}
1041
1042Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1043 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1044
Gabor Greif815e2c12008-04-06 20:42:52 +00001045 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1046 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001047
1048 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1049 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1050
1051 CGF.EmitBlock(RHSBlock);
1052 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1053
1054 // Reaquire the RHS block, as there may be subblocks inserted.
1055 RHSBlock = Builder.GetInsertBlock();
1056 CGF.EmitBlock(ContBlock);
1057
1058 // Create a PHI node. If we just evaluted the LHS condition, the result is
1059 // false. If we evaluated both, the result is the RHS condition.
1060 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1061 PN->reserveOperandSpace(2);
1062 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1063 PN->addIncoming(RHSCond, RHSBlock);
1064
1065 // ZExt result to int.
1066 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1067}
1068
1069Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1070 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1071
Gabor Greif815e2c12008-04-06 20:42:52 +00001072 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1073 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001074
1075 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1076 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1077
1078 CGF.EmitBlock(RHSBlock);
1079 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1080
1081 // Reaquire the RHS block, as there may be subblocks inserted.
1082 RHSBlock = Builder.GetInsertBlock();
1083 CGF.EmitBlock(ContBlock);
1084
1085 // Create a PHI node. If we just evaluted the LHS condition, the result is
1086 // true. If we evaluated both, the result is the RHS condition.
1087 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1088 PN->reserveOperandSpace(2);
1089 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1090 PN->addIncoming(RHSCond, RHSBlock);
1091
1092 // ZExt result to int.
1093 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1094}
1095
1096Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1097 CGF.EmitStmt(E->getLHS());
1098 return Visit(E->getRHS());
1099}
1100
1101//===----------------------------------------------------------------------===//
1102// Other Operators
1103//===----------------------------------------------------------------------===//
1104
1105Value *ScalarExprEmitter::
1106VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001107 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1108 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1109 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001110
Chris Lattner98a425c2007-11-26 01:40:58 +00001111 // Evaluate the conditional, then convert it to bool. We do this explicitly
1112 // because we need the unconverted value if this is a GNU ?: expression with
1113 // missing middle value.
1114 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001115 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1116 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001117 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001118
1119 CGF.EmitBlock(LHSBlock);
1120
1121 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001122 Value *LHS;
1123 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001124 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001125 else // Perform promotions, to handle cases like "short ?: int"
1126 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1127
Chris Lattner9fba49a2007-08-24 05:35:26 +00001128 Builder.CreateBr(ContBlock);
1129 LHSBlock = Builder.GetInsertBlock();
1130
1131 CGF.EmitBlock(RHSBlock);
1132
Eli Friedmance8d7032008-05-16 20:38:39 +00001133 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001134 Builder.CreateBr(ContBlock);
1135 RHSBlock = Builder.GetInsertBlock();
1136
1137 CGF.EmitBlock(ContBlock);
1138
Nuno Lopesb62ff242008-06-04 19:15:45 +00001139 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001140 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1141 return 0;
1142 }
1143
Chris Lattner9fba49a2007-08-24 05:35:26 +00001144 // Create a PHI node for the real part.
1145 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1146 PN->reserveOperandSpace(2);
1147 PN->addIncoming(LHS, LHSBlock);
1148 PN->addIncoming(RHS, RHSBlock);
1149 return PN;
1150}
1151
1152Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001153 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001154 return
1155 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001156}
1157
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001158Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001159 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001160 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001161}
1162
Chris Lattner307da022007-11-30 17:56:23 +00001163Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001164 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1165
1166 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1167 return V;
1168}
1169
Chris Lattner307da022007-11-30 17:56:23 +00001170Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001171 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001172 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1173 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1174 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001175
1176 llvm::Constant *C = llvm::ConstantArray::get(str);
1177 C = new llvm::GlobalVariable(C->getType(), true,
1178 llvm::GlobalValue::InternalLinkage,
1179 C, ".str", &CGF.CGM.getModule());
1180 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1181 llvm::Constant *Zeros[] = { Zero, Zero };
1182 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1183
1184 return C;
1185}
1186
Chris Lattner9fba49a2007-08-24 05:35:26 +00001187//===----------------------------------------------------------------------===//
1188// Entry Point into this File
1189//===----------------------------------------------------------------------===//
1190
1191/// EmitComplexExpr - Emit the computation of the specified expression of
1192/// complex type, ignoring the result.
1193Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1194 assert(E && !hasAggregateLLVMType(E->getType()) &&
1195 "Invalid scalar expression to emit");
1196
1197 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1198}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001199
1200/// EmitScalarConversion - Emit a conversion from the specified type to the
1201/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001202Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1203 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001204 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1205 "Invalid scalar expression to emit");
1206 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1207}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001208
1209/// EmitComplexToScalarConversion - Emit a conversion from the specified
1210/// complex type to the specified destination type, where the destination
1211/// type is an LLVM scalar type.
1212Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1213 QualType SrcTy,
1214 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001215 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001216 "Invalid complex -> scalar conversion");
1217 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1218 DstTy);
1219}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001220
1221Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1222 assert(V1->getType() == V2->getType() &&
1223 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001224 unsigned NumElements =
1225 cast<llvm::VectorType>(V1->getType())->getNumElements();
1226
1227 va_list va;
1228 va_start(va, V2);
1229
1230 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001231 for (unsigned i = 0; i < NumElements; i++) {
1232 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001233 assert(n >= 0 && n < (int)NumElements * 2 &&
1234 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001235 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1236 }
1237
1238 const char *Name = va_arg(va, const char *);
1239 va_end(va);
1240
1241 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1242
1243 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1244}
1245
Anders Carlsson68b8be92007-12-15 21:23:30 +00001246llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001247 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001248 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001249 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001250
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001251 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001252 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001253 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001254 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001255 }
1256
1257 return Vec;
1258}