blob: 71f9f92f9c4f2696bd3da073e3b0b24a3d369228 [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000022#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000023#include "llvm/Intrinsics.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000024#include "llvm/Support/Compiler.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000025#include "llvm/Support/CFG.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000026#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000027
Chris Lattner7f02f722007-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 Lattner1f1ded92007-08-24 21:00:35 +000039 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000040 const BinaryOperator *E;
41};
42
43namespace {
44class VISIBILITY_HIDDEN ScalarExprEmitter
45 : public StmtVisitor<ScalarExprEmitter, Value*> {
46 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000047 CGBuilderTy &Builder;
Chris Lattner2b94fe32008-03-01 08:45:05 +000048
Chris Lattner7f02f722007-08-24 05:35:26 +000049public:
50
Chris Lattner2b94fe32008-03-01 08:45:05 +000051 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbared7c6182008-08-20 00:28:19 +000052 Builder(CGF.Builder) {
Chris Lattner7f02f722007-08-24 05:35:26 +000053 }
Chris Lattner7f02f722007-08-24 05:35:26 +000054
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 Lattner9b655512007-08-31 22:49:20 +000063 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-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 Lattner9abc84e2007-08-26 16:42:57 +000074 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000075 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000076 Value *EmitConversionToBool(Value *Src, QualType DstTy);
77
Chris Lattner3707b252007-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 Lattner4f1a7b32007-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 Lattner3707b252007-08-26 06:48:56 +000087
Chris Lattner7f02f722007-08-24 05:35:26 +000088 //===--------------------------------------------------------------------===//
89 // Visitor Methods
90 //===--------------------------------------------------------------------===//
91
92 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000093 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-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 Lattner59138ba2008-04-20 00:45:53 +0000105 return llvm::ConstantFP::get(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000106 }
107 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
108 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
109 }
Nate Begemane7579b52007-11-15 05:40:03 +0000110 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
111 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
112 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000113 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
114 return llvm::Constant::getNullValue(ConvertType(E->getType()));
115 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000116 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
117 return llvm::Constant::getNullValue(ConvertType(E->getType()));
118 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000119 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
120 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000121 CGF.getContext().typesAreCompatible(
122 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000123 }
Sebastian Redl05189992008-11-11 17:56:53 +0000124 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000125 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar54d19092008-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 Dunbar0ffb1252008-08-04 16:51:22 +0000131 }
Chris Lattner7f02f722007-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 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000139 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
140 return CGF.EmitObjCSelectorExpr(E);
141 }
142 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
143 return CGF.EmitObjCProtocolExpr(E);
144 }
145 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
146 return EmitLoadOfLValue(E);
147 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000148 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000149 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000150 }
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000151 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
152 return EmitLoadOfLValue(E);
153 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000154 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
155 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000156 }
157
Chris Lattner7f02f722007-08-24 05:35:26 +0000158 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000159 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000160 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000161 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000162 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
163 return EmitLoadOfLValue(E);
164 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000165 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerd9f69102008-08-10 01:53:14 +0000166 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000167
168 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000169 unsigned NumInitElements = E->getNumInits();
170
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000171 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000172 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
173
174 // We have a scalar in braces. Just use the first element.
175 if (!VType)
176 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000177
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000178 if (E->hadDesignators()) {
179 CGF.ErrorUnsupported(E, "initializer list with designators");
180 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
181 }
182
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000183 unsigned NumVectorElements = VType->getNumElements();
184 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000185
186 // Emit individual vector element stores.
187 llvm::Value *V = llvm::UndefValue::get(VType);
188
Anders Carlsson222d2c82007-12-18 02:45:33 +0000189 // Emit initializers
190 unsigned i;
191 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000192 Value *NewV = Visit(E->getInit(i));
193 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
194 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000195 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000196
197 // Emit remaining default initializers
198 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
199 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
200 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
201 V = Builder.CreateInsertElement(V, NewV, Idx);
202 }
203
Devang Patela83cc332007-10-24 18:05:48 +0000204 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000205 }
Chris Lattner04421082008-04-08 04:40:51 +0000206
Chris Lattner7f02f722007-08-24 05:35:26 +0000207 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
208 Value *VisitCastExpr(const CastExpr *E) {
209 return EmitCastExpr(E->getSubExpr(), E->getType());
210 }
211 Value *EmitCastExpr(const Expr *E, QualType T);
212
213 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattner9b655512007-08-31 22:49:20 +0000214 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000215 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000216
Chris Lattner33793202007-08-31 22:09:40 +0000217 Value *VisitStmtExpr(const StmtExpr *E);
218
Chris Lattner7f02f722007-08-24 05:35:26 +0000219 // Unary Operators.
220 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
221 Value *VisitUnaryPostDec(const UnaryOperator *E) {
222 return VisitPrePostIncDec(E, false, false);
223 }
224 Value *VisitUnaryPostInc(const UnaryOperator *E) {
225 return VisitPrePostIncDec(E, true, false);
226 }
227 Value *VisitUnaryPreDec(const UnaryOperator *E) {
228 return VisitPrePostIncDec(E, false, true);
229 }
230 Value *VisitUnaryPreInc(const UnaryOperator *E) {
231 return VisitPrePostIncDec(E, true, true);
232 }
233 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
234 return EmitLValue(E->getSubExpr()).getAddress();
235 }
236 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
237 Value *VisitUnaryPlus(const UnaryOperator *E) {
238 return Visit(E->getSubExpr());
239 }
240 Value *VisitUnaryMinus (const UnaryOperator *E);
241 Value *VisitUnaryNot (const UnaryOperator *E);
242 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000243 Value *VisitUnaryReal (const UnaryOperator *E);
244 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000245 Value *VisitUnaryExtension(const UnaryOperator *E) {
246 return Visit(E->getSubExpr());
247 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000248 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner04421082008-04-08 04:40:51 +0000249 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
250 return Visit(DAE->getExpr());
251 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000252
Chris Lattner7f02f722007-08-24 05:35:26 +0000253 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000254 Value *EmitMul(const BinOpInfo &Ops) {
255 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
256 }
257 Value *EmitDiv(const BinOpInfo &Ops);
258 Value *EmitRem(const BinOpInfo &Ops);
259 Value *EmitAdd(const BinOpInfo &Ops);
260 Value *EmitSub(const BinOpInfo &Ops);
261 Value *EmitShl(const BinOpInfo &Ops);
262 Value *EmitShr(const BinOpInfo &Ops);
263 Value *EmitAnd(const BinOpInfo &Ops) {
264 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
265 }
266 Value *EmitXor(const BinOpInfo &Ops) {
267 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
268 }
269 Value *EmitOr (const BinOpInfo &Ops) {
270 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
271 }
272
Chris Lattner1f1ded92007-08-24 21:00:35 +0000273 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000274 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000275 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
276
277 // Binary operators and binary compound assignment operators.
278#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000279 Value *VisitBin ## OP(const BinaryOperator *E) { \
280 return Emit ## OP(EmitBinOps(E)); \
281 } \
282 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
283 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000284 }
285 HANDLEBINOP(Mul);
286 HANDLEBINOP(Div);
287 HANDLEBINOP(Rem);
288 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000289 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000290 HANDLEBINOP(Shl);
291 HANDLEBINOP(Shr);
292 HANDLEBINOP(And);
293 HANDLEBINOP(Xor);
294 HANDLEBINOP(Or);
295#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000296
Chris Lattner7f02f722007-08-24 05:35:26 +0000297 // Comparisons.
298 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
299 unsigned SICmpOpc, unsigned FCmpOpc);
300#define VISITCOMP(CODE, UI, SI, FP) \
301 Value *VisitBin##CODE(const BinaryOperator *E) { \
302 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
303 llvm::FCmpInst::FP); }
304 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
305 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
306 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
307 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
308 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
309 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
310#undef VISITCOMP
311
312 Value *VisitBinAssign (const BinaryOperator *E);
313
314 Value *VisitBinLAnd (const BinaryOperator *E);
315 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000316 Value *VisitBinComma (const BinaryOperator *E);
317
318 // Other Operators.
319 Value *VisitConditionalOperator(const ConditionalOperator *CO);
320 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begemane2ce1d92008-01-17 17:46:27 +0000321 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000322 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000323 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
324 return CGF.EmitObjCStringLiteral(E);
325 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000326 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000327};
328} // end anonymous namespace.
329
330//===----------------------------------------------------------------------===//
331// Utilities
332//===----------------------------------------------------------------------===//
333
Chris Lattner9abc84e2007-08-26 16:42:57 +0000334/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000335/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000336Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
337 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
338
339 if (SrcType->isRealFloatingType()) {
340 // Compare against 0.0 for fp scalars.
341 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000342 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
343 }
344
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000345 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000346 "Unknown scalar type to convert");
347
348 // Because of the type rules of C, we often end up computing a logical value,
349 // then zero extending it to int, then wanting it as a logical value again.
350 // Optimize this common case.
351 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
352 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
353 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000354 // If there aren't any more uses, zap the instruction to save space.
355 // Note that there can be more uses, for example if this
356 // is the result of an assignment.
357 if (ZI->use_empty())
358 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000359 return Result;
360 }
361 }
362
363 // Compare against an integer or pointer null.
364 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
365 return Builder.CreateICmpNE(Src, Zero, "tobool");
366}
367
Chris Lattner3707b252007-08-26 06:48:56 +0000368/// EmitScalarConversion - Emit a conversion from the specified type to the
369/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000370Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
371 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000372 SrcType = CGF.getContext().getCanonicalType(SrcType);
373 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000374 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000375
376 if (DstType->isVoidType()) return 0;
Chris Lattner3707b252007-08-26 06:48:56 +0000377
378 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000379 if (DstType->isBooleanType())
380 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000381
382 const llvm::Type *DstTy = ConvertType(DstType);
383
384 // Ignore conversions like int -> uint.
385 if (Src->getType() == DstTy)
386 return Src;
387
Daniel Dunbar270cc662008-08-25 09:51:32 +0000388 // Handle pointer conversions next: pointers can only be converted
389 // to/from other pointers and integers. Check for pointer types in
390 // terms of LLVM, as some native types (like Obj-C id) may map to a
391 // pointer type.
392 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000393 // The source value may be an integer, or a pointer.
394 if (isa<llvm::PointerType>(Src->getType()))
395 return Builder.CreateBitCast(Src, DstTy, "conv");
396 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
397 return Builder.CreateIntToPtr(Src, DstTy, "conv");
398 }
399
Daniel Dunbar270cc662008-08-25 09:51:32 +0000400 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000401 // Must be an ptr to int cast.
402 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000403 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000404 }
405
Nate Begeman213541a2008-04-18 23:10:10 +0000406 // A scalar can be splatted to an extended vector of the same element type
407 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner3b1ae002008-02-02 04:51:41 +0000408 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begeman4119d1a2007-12-30 02:59:45 +0000409 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
410 true);
Nate Begeman4119d1a2007-12-30 02:59:45 +0000411
Chris Lattner3b1ae002008-02-02 04:51:41 +0000412 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000413 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000414 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000415 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000416
Chris Lattner3707b252007-08-26 06:48:56 +0000417 // Finally, we have the arithmetic types: real int/float.
418 if (isa<llvm::IntegerType>(Src->getType())) {
419 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000420 if (isa<llvm::IntegerType>(DstTy))
421 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
422 else if (InputSigned)
423 return Builder.CreateSIToFP(Src, DstTy, "conv");
424 else
425 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000426 }
427
428 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
429 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000430 if (DstType->isSignedIntegerType())
431 return Builder.CreateFPToSI(Src, DstTy, "conv");
432 else
433 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000434 }
435
436 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000437 if (DstTy->getTypeID() < Src->getType()->getTypeID())
438 return Builder.CreateFPTrunc(Src, DstTy, "conv");
439 else
440 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000441}
442
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000443/// EmitComplexToScalarConversion - Emit a conversion from the specified
444/// complex type to the specified destination type, where the destination
445/// type is an LLVM scalar type.
446Value *ScalarExprEmitter::
447EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
448 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000449 // Get the source element type.
Chris Lattner96196622008-07-26 22:37:01 +0000450 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnered70f0a2007-08-26 16:52:28 +0000451
452 // Handle conversions to bool first, they are special: comparisons against 0.
453 if (DstTy->isBooleanType()) {
454 // Complex != 0 -> (Real != 0) | (Imag != 0)
455 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
456 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
457 return Builder.CreateOr(Src.first, Src.second, "tobool");
458 }
459
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000460 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
461 // the imaginary part of the complex value is discarded and the value of the
462 // real part is converted according to the conversion rules for the
463 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000464 return EmitScalarConversion(Src.first, SrcTy, DstTy);
465}
466
467
Chris Lattner7f02f722007-08-24 05:35:26 +0000468//===----------------------------------------------------------------------===//
469// Visitor Methods
470//===----------------------------------------------------------------------===//
471
472Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000473 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000474 if (E->getType()->isVoidType())
475 return 0;
476 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
477}
478
Eli Friedmand38617c2008-05-14 19:38:39 +0000479Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
480 llvm::SmallVector<llvm::Constant*, 32> indices;
481 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
482 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
483 }
484 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
485 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
486 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
487 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
488}
489
Chris Lattner7f02f722007-08-24 05:35:26 +0000490Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
491 // Emit subscript expressions in rvalue context's. For most cases, this just
492 // loads the lvalue formed by the subscript expr. However, we have to be
493 // careful, because the base of a vector subscript is occasionally an rvalue,
494 // so we can't get it as an lvalue.
495 if (!E->getBase()->getType()->isVectorType())
496 return EmitLoadOfLValue(E);
497
498 // Handle the vector case. The base must be a vector, the index must be an
499 // integer value.
500 Value *Base = Visit(E->getBase());
501 Value *Idx = Visit(E->getIdx());
502
503 // FIXME: Convert Idx to i32 type.
504 return Builder.CreateExtractElement(Base, Idx, "vecext");
505}
506
507/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
508/// also handle things like function to pointer-to-function decay, and array to
509/// pointer decay.
510Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
511 const Expr *Op = E->getSubExpr();
512
513 // If this is due to array->pointer conversion, emit the array expression as
514 // an l-value.
515 if (Op->getType()->isArrayType()) {
516 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
517 // will not true when we add support for VLAs.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000518 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000519
520 if (!Op->getType()->isVariableArrayType()) {
521 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
522 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
523 ->getElementType()) &&
524 "Expected pointer to array");
525 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar662174c82008-08-29 17:28:43 +0000526 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000527
528 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerf31627f2008-07-23 06:31:27 +0000529 // types as well (e.g. void*) and can be implicitly converted to integer.
530 const llvm::Type *DestTy = ConvertType(E->getType());
531 if (V->getType() != DestTy) {
532 if (isa<llvm::PointerType>(DestTy))
533 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
534 else {
535 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
536 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
537 }
538 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000539 return V;
540
Anders Carlsson793680e2007-10-12 23:56:29 +0000541 } else if (E->getType()->isReferenceType()) {
Anders Carlsson793680e2007-10-12 23:56:29 +0000542 return EmitLValue(Op).getAddress();
Chris Lattner7f02f722007-08-24 05:35:26 +0000543 }
544
545 return EmitCastExpr(Op, E->getType());
546}
547
548
549// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
550// have to handle a more broad range of conversions than explicit casts, as they
551// handle things like function to ptr-to-function decay etc.
552Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner58a2e942007-08-26 07:26:12 +0000553 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000554
555 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000556 Value *Src = Visit(const_cast<Expr*>(E));
557
Chris Lattner3707b252007-08-26 06:48:56 +0000558 // Use EmitScalarConversion to perform the conversion.
559 return EmitScalarConversion(Src, E->getType(), DestTy);
560 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000561
Chris Lattner9b2dc282008-04-04 16:54:41 +0000562 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000563 // Handle cases where the source is a complex type.
564 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
565 DestTy);
566 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000567
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000568 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
569 // evaluate the result and return.
570 CGF.EmitAggExpr(E, 0, false);
571 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000572}
573
Chris Lattner33793202007-08-31 22:09:40 +0000574Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000575 return CGF.EmitCompoundStmt(*E->getSubStmt(),
576 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000577}
578
579
Chris Lattner7f02f722007-08-24 05:35:26 +0000580//===----------------------------------------------------------------------===//
581// Unary Operators
582//===----------------------------------------------------------------------===//
583
584Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000585 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000586 LValue LV = EmitLValue(E->getSubExpr());
587 // FIXME: Handle volatile!
Chris Lattnere936cc82007-08-26 05:10:16 +0000588 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattner9b655512007-08-31 22:49:20 +0000589 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000590
591 int AmountVal = isInc ? 1 : -1;
592
593 Value *NextVal;
Chris Lattnere936cc82007-08-26 05:10:16 +0000594 if (isa<llvm::PointerType>(InVal->getType())) {
595 // FIXME: This isn't right for VLAs.
596 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner36b6a0a2008-03-19 05:19:41 +0000597 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000598 } else {
599 // Add the inc/dec to the real part.
600 if (isa<llvm::IntegerType>(InVal->getType()))
601 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000602 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000603 NextVal =
Chris Lattner59138ba2008-04-20 00:45:53 +0000604 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000605 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000606 NextVal =
Chris Lattner59138ba2008-04-20 00:45:53 +0000607 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000608 else {
609 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000610 bool ignored;
611 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
612 &ignored);
Chris Lattner25ddea72008-04-20 00:50:39 +0000613 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000614 }
Chris Lattnere936cc82007-08-26 05:10:16 +0000615 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
616 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000617
618 // Store the updated result through the lvalue.
619 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
620 E->getSubExpr()->getType());
621
622 // If this is a postinc, return the value read from memory, otherwise use the
623 // updated value.
624 return isPre ? NextVal : InVal;
625}
626
627
628Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
629 Value *Op = Visit(E->getSubExpr());
630 return Builder.CreateNeg(Op, "neg");
631}
632
633Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
634 Value *Op = Visit(E->getSubExpr());
635 return Builder.CreateNot(Op, "neg");
636}
637
638Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
639 // Compare operand to zero.
640 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
641
642 // Invert value.
643 // TODO: Could dynamically modify easy computations here. For example, if
644 // the operand is an icmp ne, turn into icmp eq.
645 BoolVal = Builder.CreateNot(BoolVal, "lnot");
646
647 // ZExt result to int.
648 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
649}
650
Sebastian Redl05189992008-11-11 17:56:53 +0000651/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
652/// argument of the sizeof expression as an integer.
653Value *
654ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
655 QualType RetType = E->getType();
Chris Lattnera269ebf2008-02-21 05:45:29 +0000656 assert(RetType->isIntegerType() && "Result type must be an integer!");
657 uint32_t ResultWidth =
Chris Lattner98be4942008-03-05 18:54:05 +0000658 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattnera269ebf2008-02-21 05:45:29 +0000659
Sebastian Redl05189992008-11-11 17:56:53 +0000660 QualType TypeToSize = E->getTypeOfArgument();
Daniel Dunbar91408452008-07-22 01:35:47 +0000661 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
662 // for function types.
Daniel Dunbar8ee6a632008-07-22 19:44:18 +0000663 // FIXME: what is alignof a function type in gcc?
Daniel Dunbar91408452008-07-22 01:35:47 +0000664 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattnera269ebf2008-02-21 05:45:29 +0000665 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
666
Anders Carlsson5d463152008-12-12 07:38:43 +0000667 if (const VariableArrayType *VAT =
668 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
Anders Carlssonb50525b2008-12-21 03:33:21 +0000669 if (E->isSizeOf()) {
670 if (E->isArgumentType()) {
671 // sizeof(type) - make sure to emit the VLA size.
672 CGF.EmitVLASize(TypeToSize);
673 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000674 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000675 }
Anders Carlsson4a1424f2008-12-21 03:48:05 +0000676
677 // alignof
678 QualType BaseType = CGF.getContext().getBaseElementType(VAT);
679 uint64_t Align = CGF.getContext().getTypeAlign(BaseType);
680
681 Align /= 8; // Return alignment in bytes, not bits.
682 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Align));
Anders Carlsson5d463152008-12-12 07:38:43 +0000683 }
684
Chris Lattner98be4942008-03-05 18:54:05 +0000685 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner7f02f722007-08-24 05:35:26 +0000686
Sebastian Redl05189992008-11-11 17:56:53 +0000687 uint64_t Val = E->isSizeOf() ? Info.first : Info.second;
Chris Lattner7f02f722007-08-24 05:35:26 +0000688 Val /= 8; // Return size in bytes, not bits.
689
Chris Lattner7f02f722007-08-24 05:35:26 +0000690 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
691}
692
Chris Lattner46f93d02007-08-24 21:20:17 +0000693Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
694 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000695 if (Op->getType()->isAnyComplexType())
Chris Lattner46f93d02007-08-24 21:20:17 +0000696 return CGF.EmitComplexExpr(Op).first;
697 return Visit(Op);
698}
699Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
700 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000701 if (Op->getType()->isAnyComplexType())
Chris Lattner46f93d02007-08-24 21:20:17 +0000702 return CGF.EmitComplexExpr(Op).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000703
704 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
705 // effects are evaluated.
706 CGF.EmitScalarExpr(Op);
707 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000708}
709
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000710Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
711{
712 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
713
714 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
715
Chris Lattner98be4942008-03-05 18:54:05 +0000716 uint32_t ResultWidth =
717 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000718 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
719}
Chris Lattner46f93d02007-08-24 21:20:17 +0000720
Chris Lattner7f02f722007-08-24 05:35:26 +0000721//===----------------------------------------------------------------------===//
722// Binary Operators
723//===----------------------------------------------------------------------===//
724
725BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
726 BinOpInfo Result;
727 Result.LHS = Visit(E->getLHS());
728 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000729 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000730 Result.E = E;
731 return Result;
732}
733
Chris Lattner3ccf7742007-08-26 21:41:21 +0000734Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000735 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
736 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
737
738 BinOpInfo OpInfo;
739
740 // Load the LHS and RHS operands.
741 LValue LHSLV = EmitLValue(E->getLHS());
742 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner04dc7642007-08-26 22:37:40 +0000743
744 // Determine the computation type. If the RHS is complex, then this is one of
745 // the add/sub/mul/div operators. All of these operators can be computed in
746 // with just their real component even though the computation domain really is
747 // complex.
Chris Lattner3ccf7742007-08-26 21:41:21 +0000748 QualType ComputeType = E->getComputationType();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000749
Chris Lattner04dc7642007-08-26 22:37:40 +0000750 // If the computation type is complex, then the RHS is complex. Emit the RHS.
751 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
752 ComputeType = CT->getElementType();
753
754 // Emit the RHS, only keeping the real component.
755 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
756 RHSTy = RHSTy->getAsComplexType()->getElementType();
757 } else {
758 // Otherwise the RHS is a simple scalar value.
759 OpInfo.RHS = Visit(E->getRHS());
760 }
761
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000762 QualType LComputeTy, RComputeTy, ResultTy;
763
764 // Compound assignment does not contain enough information about all
765 // the types involved for pointer arithmetic cases. Figure it out
766 // here for now.
767 if (E->getLHS()->getType()->isPointerType()) {
768 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
769 assert((E->getOpcode() == BinaryOperator::AddAssign ||
770 E->getOpcode() == BinaryOperator::SubAssign) &&
771 "Invalid compound assignment operator on pointer type.");
772 LComputeTy = E->getLHS()->getType();
773
774 if (E->getRHS()->getType()->isPointerType()) {
775 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
776 // extension, the conversion from the pointer difference back to
777 // the LHS type is handled at the end.
778 assert(E->getOpcode() == BinaryOperator::SubAssign &&
779 "Invalid compound assignment operator on pointer type.");
780 RComputeTy = E->getLHS()->getType();
781 ResultTy = CGF.getContext().getPointerDiffType();
782 } else {
783 RComputeTy = E->getRHS()->getType();
784 ResultTy = LComputeTy;
785 }
786 } else if (E->getRHS()->getType()->isPointerType()) {
787 // Degenerate case of (int += ptr) allowed by GCC implicit cast
788 // extension.
789 assert(E->getOpcode() == BinaryOperator::AddAssign &&
790 "Invalid compound assignment operator on pointer type.");
791 LComputeTy = E->getLHS()->getType();
792 RComputeTy = E->getRHS()->getType();
793 ResultTy = RComputeTy;
794 } else {
795 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000796 }
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000797
798 // Convert the LHS/RHS values to the computation type.
799 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
800 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
801 OpInfo.Ty = ResultTy;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000802 OpInfo.E = E;
803
804 // Expand the binary operator.
805 Value *Result = (this->*Func)(OpInfo);
806
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000807 // Convert the result back to the LHS type.
808 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000809
Daniel Dunbared3849b2008-11-19 09:36:46 +0000810 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar371d16f2008-11-19 11:54:05 +0000811 // handled specially because the result is altered by the store,
812 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
813 // the left operand after the assignment...'.
Eli Friedman18491282008-05-25 14:13:57 +0000814 if (LHSLV.isBitfield())
Daniel Dunbared3849b2008-11-19 09:36:46 +0000815 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
816 &Result);
817 else
818 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
819
Chris Lattner1f1ded92007-08-24 21:00:35 +0000820 return Result;
821}
822
823
Chris Lattner7f02f722007-08-24 05:35:26 +0000824Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000825 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000826 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000827 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000828 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
829 else
830 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
831}
832
833Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
834 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000835 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000836 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
837 else
838 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
839}
840
841
842Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner1f1ded92007-08-24 21:00:35 +0000843 if (!Ops.Ty->isPointerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000844 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000845
846 // FIXME: What about a pointer to a VLA?
Chris Lattner8f925282008-01-03 06:36:51 +0000847 Value *Ptr, *Idx;
848 Expr *IdxExp;
849 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
850 Ptr = Ops.LHS;
851 Idx = Ops.RHS;
852 IdxExp = Ops.E->getRHS();
853 } else { // int + pointer
854 Ptr = Ops.RHS;
855 Idx = Ops.LHS;
856 IdxExp = Ops.E->getLHS();
857 }
858
859 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
860 if (Width < CGF.LLVMPointerWidth) {
861 // Zero or sign extend the pointer value based on whether the index is
862 // signed or not.
863 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +0000864 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +0000865 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
866 else
867 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
868 }
869
870 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +0000871}
872
873Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
874 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
875 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000876
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000877 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
878 // pointer - int
879 Value *Idx = Ops.RHS;
880 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
881 if (Width < CGF.LLVMPointerWidth) {
882 // Zero or sign extend the pointer value based on whether the index is
883 // signed or not.
884 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
885 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
886 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
887 else
888 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
889 }
890 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
891
892 // FIXME: The pointer could point to a VLA.
893 // The GNU void* - int case is automatically handled here because
894 // our LLVM type for void* is i8*.
895 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +0000896 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000897 // pointer - pointer
898 Value *LHS = Ops.LHS;
899 Value *RHS = Ops.RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000900
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000901 const QualType LHSType = Ops.E->getLHS()->getType();
902 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
903 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +0000904
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000905 // Handle GCC extension for pointer arithmetic on void* types.
906 if (LHSElementType->isVoidType()) {
907 ElementSize = 1;
908 } else {
909 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
910 }
911
912 const llvm::Type *ResultType = ConvertType(Ops.Ty);
913 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
914 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
915 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
916
917 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
918 // remainder. As such, we handle common power-of-two cases here to generate
919 // better code. See PR2247.
920 if (llvm::isPowerOf2_64(ElementSize)) {
921 Value *ShAmt =
922 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
923 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
924 }
925
926 // Otherwise, do a full sdiv.
927 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
928 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +0000929 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000930}
931
932Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
933 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
934 // RHS to the same size as the LHS.
935 Value *RHS = Ops.RHS;
936 if (Ops.LHS->getType() != RHS->getType())
937 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
938
939 return Builder.CreateShl(Ops.LHS, RHS, "shl");
940}
941
942Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
943 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
944 // RHS to the same size as the LHS.
945 Value *RHS = Ops.RHS;
946 if (Ops.LHS->getType() != RHS->getType())
947 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
948
Chris Lattner1f1ded92007-08-24 21:00:35 +0000949 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000950 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
951 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
952}
953
954Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
955 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000956 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +0000957 QualType LHSTy = E->getLHS()->getType();
Nate Begeman7a66d7b2008-07-25 20:16:05 +0000958 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000959 Value *LHS = Visit(E->getLHS());
960 Value *RHS = Visit(E->getRHS());
961
962 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +0000963 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +0000964 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +0000965 } else if (LHSTy->isSignedIntegerType()) {
966 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +0000967 LHS, RHS, "cmp");
968 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +0000969 // Unsigned integers and pointers.
970 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +0000971 LHS, RHS, "cmp");
972 }
Nate Begeman7a66d7b2008-07-25 20:16:05 +0000973 } else if (LHSTy->isVectorType()) {
974 Value *LHS = Visit(E->getLHS());
975 Value *RHS = Visit(E->getRHS());
976
977 if (LHS->getType()->isFPOrFPVector()) {
978 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
979 LHS, RHS, "cmp");
980 } else if (LHSTy->isUnsignedIntegerType()) {
981 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
982 LHS, RHS, "cmp");
983 } else {
984 // Signed integers and pointers.
985 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
986 LHS, RHS, "cmp");
987 }
988 return Result;
Chris Lattner7f02f722007-08-24 05:35:26 +0000989 } else {
990 // Complex Comparison: can only be an equality comparison.
991 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
992 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
993
Chris Lattner96196622008-07-26 22:37:01 +0000994 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000995
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000996 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +0000997 if (CETy->isRealFloatingType()) {
998 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
999 LHS.first, RHS.first, "cmp.r");
1000 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1001 LHS.second, RHS.second, "cmp.i");
1002 } else {
1003 // Complex comparisons can only be equality comparisons. As such, signed
1004 // and unsigned opcodes are the same.
1005 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1006 LHS.first, RHS.first, "cmp.r");
1007 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1008 LHS.second, RHS.second, "cmp.i");
1009 }
1010
1011 if (E->getOpcode() == BinaryOperator::EQ) {
1012 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1013 } else {
1014 assert(E->getOpcode() == BinaryOperator::NE &&
1015 "Complex comparison other than == or != ?");
1016 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1017 }
1018 }
1019
1020 // ZExt result to int.
1021 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1022}
1023
1024Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1025 LValue LHS = EmitLValue(E->getLHS());
1026 Value *RHS = Visit(E->getRHS());
1027
Daniel Dunbared3849b2008-11-19 09:36:46 +00001028 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001029 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1030 // 'An assignment expression has the value of the left operand after
1031 // the assignment...'.
Chris Lattner7f02f722007-08-24 05:35:26 +00001032 // FIXME: Volatility!
Eli Friedman18491282008-05-25 14:13:57 +00001033 if (LHS.isBitfield())
Daniel Dunbared3849b2008-11-19 09:36:46 +00001034 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1035 &RHS);
1036 else
1037 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbar85c59ed2008-08-29 08:11:39 +00001038
Chris Lattner7f02f722007-08-24 05:35:26 +00001039 // Return the RHS.
1040 return RHS;
1041}
1042
1043Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001044 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1045 // If we have 1 && X, just emit X without inserting the control flow.
1046 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1047 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001048 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1049 // ZExt result to int.
1050 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1051 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001052
1053 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1054 if (!CGF.ContainsLabel(E->getRHS()))
1055 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001056 }
1057
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001058 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1059 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001060
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001061 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1062 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1063
1064 // Any edges into the ContBlock are now from an (indeterminate number of)
1065 // edges from this first condition. All of these values will be false. Start
1066 // setting up the PHI node in the Cont Block for this.
1067 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1068 PN->reserveOperandSpace(2); // Normal case, two inputs.
1069 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1070 PI != PE; ++PI)
1071 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner7f02f722007-08-24 05:35:26 +00001072
1073 CGF.EmitBlock(RHSBlock);
1074 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1075
1076 // Reaquire the RHS block, as there may be subblocks inserted.
1077 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001078
1079 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1080 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001081 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001082 PN->addIncoming(RHSCond, RHSBlock);
1083
1084 // ZExt result to int.
1085 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1086}
1087
1088Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001089 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1090 // If we have 0 || X, just emit X without inserting the control flow.
1091 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1092 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001093 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1094 // ZExt result to int.
1095 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1096 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001097
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001098 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001099 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001100 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001101 }
1102
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001103 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1104 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner7f02f722007-08-24 05:35:26 +00001105
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001106 // Branch on the LHS first. If it is true, go to the success (cont) block.
1107 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1108
1109 // Any edges into the ContBlock are now from an (indeterminate number of)
1110 // edges from this first condition. All of these values will be true. Start
1111 // setting up the PHI node in the Cont Block for this.
1112 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1113 PN->reserveOperandSpace(2); // Normal case, two inputs.
1114 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1115 PI != PE; ++PI)
1116 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1117
1118 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001119 CGF.EmitBlock(RHSBlock);
1120 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1121
1122 // Reaquire the RHS block, as there may be subblocks inserted.
1123 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00001124
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001125 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1126 // into the phi node for the edge with the value of RHSCond.
1127 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001128 PN->addIncoming(RHSCond, RHSBlock);
1129
1130 // ZExt result to int.
1131 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1132}
1133
1134Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1135 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001136 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001137 return Visit(E->getRHS());
1138}
1139
1140//===----------------------------------------------------------------------===//
1141// Other Operators
1142//===----------------------------------------------------------------------===//
1143
Chris Lattner9802a512008-11-12 08:55:54 +00001144/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1145/// expression is cheap enough and side-effect-free enough to evaluate
1146/// unconditionally instead of conditionally. This is used to convert control
1147/// flow into selects in some cases.
1148static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1149 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1150 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1151
1152 // TODO: Allow anything we can constant fold to an integer or fp constant.
1153 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1154 isa<FloatingLiteral>(E))
1155 return true;
1156
1157 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1158 // X and Y are local variables.
1159 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1160 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1161 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1162 return true;
1163
1164 return false;
1165}
1166
1167
Chris Lattner7f02f722007-08-24 05:35:26 +00001168Value *ScalarExprEmitter::
1169VisitConditionalOperator(const ConditionalOperator *E) {
Chris Lattner31a09842008-11-12 08:04:58 +00001170 // If the condition constant folds and can be elided, try to avoid emitting
1171 // the condition and the dead arm.
1172 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001173 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001174 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001175 std::swap(Live, Dead);
Chris Lattner31a09842008-11-12 08:04:58 +00001176
1177 // If the dead side doesn't have labels we need, and if the Live side isn't
1178 // the gnu missing ?: extension (which we could handle, but don't bother
1179 // to), just emit the Live part.
1180 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1181 Live) // Live part isn't missing.
1182 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001183 }
1184
Chris Lattner9802a512008-11-12 08:55:54 +00001185
1186 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1187 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001188 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001189 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1190 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1191 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1192 llvm::Value *LHS = Visit(E->getLHS());
1193 llvm::Value *RHS = Visit(E->getRHS());
1194 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1195 }
1196
1197
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001198 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1199 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001200 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001201 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001202
Chris Lattner035cf422008-11-12 08:08:13 +00001203 // If we have the GNU missing condition extension, evaluate the conditional
1204 // and then convert it to bool the hard way. We do this explicitly
1205 // because we need the unconverted value for the missing middle value of
1206 // the ?:.
1207 if (E->getLHS() == 0) {
1208 CondVal = CGF.EmitScalarExpr(E->getCond());
1209 Value *CondBoolVal =
1210 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1211 CGF.getContext().BoolTy);
1212 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1213 } else {
1214 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1215 // the branch on bool.
1216 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1217 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001218
1219 CGF.EmitBlock(LHSBlock);
1220
1221 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001222 Value *LHS;
1223 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001224 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001225 else // Perform promotions, to handle cases like "short ?: int"
1226 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1227
Chris Lattner7f02f722007-08-24 05:35:26 +00001228 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001229 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001230
1231 CGF.EmitBlock(RHSBlock);
1232
Eli Friedman856226c2008-05-16 20:38:39 +00001233 Value *RHS = Visit(E->getRHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001234 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001235 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001236
1237 CGF.EmitBlock(ContBlock);
1238
Nuno Lopes108f55d2008-06-04 19:15:45 +00001239 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001240 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1241 return 0;
1242 }
1243
Chris Lattner7f02f722007-08-24 05:35:26 +00001244 // Create a PHI node for the real part.
1245 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1246 PN->reserveOperandSpace(2);
1247 PN->addIncoming(LHS, LHSBlock);
1248 PN->addIncoming(RHS, RHSBlock);
1249 return PN;
1250}
1251
1252Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001253 // Emit the LHS or RHS as appropriate.
Devang Patele9b8c0a2007-10-30 20:59:40 +00001254 return
1255 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001256}
1257
Nate Begemane2ce1d92008-01-17 17:46:27 +00001258Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begeman67295d02008-01-30 20:50:20 +00001259 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek55499762008-06-17 02:43:46 +00001260 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begemane2ce1d92008-01-17 17:46:27 +00001261}
1262
Chris Lattner2202bce2007-11-30 17:56:23 +00001263Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001264 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1265
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001266 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1267
1268 // If EmitVAArg fails, we fall back to the LLVM instruction.
1269 if (!ArgPtr)
1270 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1271
1272 // FIXME: volatile?
1273 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001274}
1275
Chris Lattner2202bce2007-11-30 17:56:23 +00001276Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001277 std::string str;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001278 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001279
1280 llvm::Constant *C = llvm::ConstantArray::get(str);
1281 C = new llvm::GlobalVariable(C->getType(), true,
1282 llvm::GlobalValue::InternalLinkage,
1283 C, ".str", &CGF.CGM.getModule());
1284 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1285 llvm::Constant *Zeros[] = { Zero, Zero };
1286 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1287
1288 return C;
1289}
1290
Chris Lattner7f02f722007-08-24 05:35:26 +00001291//===----------------------------------------------------------------------===//
1292// Entry Point into this File
1293//===----------------------------------------------------------------------===//
1294
1295/// EmitComplexExpr - Emit the computation of the specified expression of
1296/// complex type, ignoring the result.
1297Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1298 assert(E && !hasAggregateLLVMType(E->getType()) &&
1299 "Invalid scalar expression to emit");
1300
1301 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1302}
Chris Lattner3707b252007-08-26 06:48:56 +00001303
1304/// EmitScalarConversion - Emit a conversion from the specified type to the
1305/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001306Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1307 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001308 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1309 "Invalid scalar expression to emit");
1310 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1311}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001312
1313/// EmitComplexToScalarConversion - Emit a conversion from the specified
1314/// complex type to the specified destination type, where the destination
1315/// type is an LLVM scalar type.
1316Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1317 QualType SrcTy,
1318 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001319 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001320 "Invalid complex -> scalar conversion");
1321 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1322 DstTy);
1323}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001324
1325Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1326 assert(V1->getType() == V2->getType() &&
1327 "Vector operands must be of the same type");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001328 unsigned NumElements =
1329 cast<llvm::VectorType>(V1->getType())->getNumElements();
1330
1331 va_list va;
1332 va_start(va, V2);
1333
1334 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001335 for (unsigned i = 0; i < NumElements; i++) {
1336 int n = va_arg(va, int);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001337 assert(n >= 0 && n < (int)NumElements * 2 &&
1338 "Vector shuffle index out of bounds!");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001339 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1340 }
1341
1342 const char *Name = va_arg(va, const char *);
1343 va_end(va);
1344
1345 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1346
1347 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1348}
1349
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001350llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001351 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001352 llvm::Value *Vec
Chris Lattner345f7202008-07-26 20:15:14 +00001353 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001354
Chris Lattner345f7202008-07-26 20:15:14 +00001355 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001356 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001357 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001358 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001359 }
1360
1361 return Vec;
1362}