blob: 80aa755e189794fa531e0bc0d97c470f61fb112e [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"
Eli Friedman769e4112009-01-24 22:38:55 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000026#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000028#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000029
Chris Lattner7f02f722007-08-24 05:35:26 +000030using namespace clang;
31using namespace CodeGen;
32using llvm::Value;
33
34//===----------------------------------------------------------------------===//
35// Scalar Expression Emitter
36//===----------------------------------------------------------------------===//
37
38struct BinOpInfo {
39 Value *LHS;
40 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000041 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000042 const BinaryOperator *E;
43};
44
45namespace {
46class VISIBILITY_HIDDEN ScalarExprEmitter
47 : public StmtVisitor<ScalarExprEmitter, Value*> {
48 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000049 CGBuilderTy &Builder;
Chris Lattner2b94fe32008-03-01 08:45:05 +000050
Chris Lattner7f02f722007-08-24 05:35:26 +000051public:
52
Chris Lattner2b94fe32008-03-01 08:45:05 +000053 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbared7c6182008-08-20 00:28:19 +000054 Builder(CGF.Builder) {
Chris Lattner7f02f722007-08-24 05:35:26 +000055 }
Chris Lattner7f02f722007-08-24 05:35:26 +000056
57 //===--------------------------------------------------------------------===//
58 // Utilities
59 //===--------------------------------------------------------------------===//
60
61 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
62 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
63
64 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000065 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000066 }
67
68 /// EmitLoadOfLValue - Given an expression with complex type that represents a
69 /// value l-value, this method emits the address of the l-value, then loads
70 /// and returns the result.
71 Value *EmitLoadOfLValue(const Expr *E) {
72 // FIXME: Volatile
73 return EmitLoadOfLValue(EmitLValue(E), E->getType());
74 }
75
Chris Lattner9abc84e2007-08-26 16:42:57 +000076 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000077 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000078 Value *EmitConversionToBool(Value *Src, QualType DstTy);
79
Chris Lattner3707b252007-08-26 06:48:56 +000080 /// EmitScalarConversion - Emit a conversion from the specified type to the
81 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000082 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
83
84 /// EmitComplexToScalarConversion - Emit a conversion from the specified
85 /// complex type to the specified destination type, where the destination
86 /// type is an LLVM scalar type.
87 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
88 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000089
Chris Lattner7f02f722007-08-24 05:35:26 +000090 //===--------------------------------------------------------------------===//
91 // Visitor Methods
92 //===--------------------------------------------------------------------===//
93
94 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000095 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +000096 assert(0 && "Stmt can't have complex result type!");
97 return 0;
98 }
99 Value *VisitExpr(Expr *S);
100 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
101
102 // Leaves.
103 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
104 return llvm::ConstantInt::get(E->getValue());
105 }
106 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner59138ba2008-04-20 00:45:53 +0000107 return llvm::ConstantFP::get(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000108 }
109 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Nate Begemane7579b52007-11-15 05:40:03 +0000112 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
114 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000115 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
116 return llvm::Constant::getNullValue(ConvertType(E->getType()));
117 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000118 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
119 return llvm::Constant::getNullValue(ConvertType(E->getType()));
120 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000121 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
122 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000123 CGF.getContext().typesAreCompatible(
124 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000125 }
Sebastian Redl05189992008-11-11 17:56:53 +0000126 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000127 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar54d19092008-08-16 01:41:47 +0000128 llvm::Value *V =
129 llvm::ConstantInt::get(llvm::Type::Int32Ty,
130 CGF.GetIDForAddrOfLabel(E->getLabel()));
131
132 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000133 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000134
135 // l-values.
136 Value *VisitDeclRefExpr(DeclRefExpr *E) {
137 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
138 return llvm::ConstantInt::get(EC->getInitVal());
139 return EmitLoadOfLValue(E);
140 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000141 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
142 return CGF.EmitObjCSelectorExpr(E);
143 }
144 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
145 return CGF.EmitObjCProtocolExpr(E);
146 }
147 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
148 return EmitLoadOfLValue(E);
149 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000150 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000151 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000152 }
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000153 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
154 return EmitLoadOfLValue(E);
155 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000156 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
157 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000158 }
159
Chris Lattner7f02f722007-08-24 05:35:26 +0000160 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000161 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000162 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000163 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000164 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
165 return EmitLoadOfLValue(E);
166 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000167 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000168 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
169 return EmitLValue(E).getAddress();
170 }
171
Chris Lattnerd9f69102008-08-10 01:53:14 +0000172 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000173
174 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000175 unsigned NumInitElements = E->getNumInits();
176
Douglas Gregora9c87802009-01-29 19:42:23 +0000177 if (E->hadArrayRangeDesignator()) {
178 CGF.ErrorUnsupported(E, "GNU array range designator extension");
179 }
180
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000181 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000182 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
183
184 // We have a scalar in braces. Just use the first element.
185 if (!VType)
186 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000187
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000188 unsigned NumVectorElements = VType->getNumElements();
189 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000190
191 // Emit individual vector element stores.
192 llvm::Value *V = llvm::UndefValue::get(VType);
193
Anders Carlsson222d2c82007-12-18 02:45:33 +0000194 // Emit initializers
195 unsigned i;
196 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000197 Value *NewV = Visit(E->getInit(i));
198 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
199 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000200 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000201
202 // Emit remaining default initializers
203 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
204 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
205 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
206 V = Builder.CreateInsertElement(V, NewV, Idx);
207 }
208
Devang Patela83cc332007-10-24 18:05:48 +0000209 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000210 }
Chris Lattner04421082008-04-08 04:40:51 +0000211
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000212 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
213 return llvm::Constant::getNullValue(ConvertType(E->getType()));
214 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000215 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
216 Value *VisitCastExpr(const CastExpr *E) {
217 return EmitCastExpr(E->getSubExpr(), E->getType());
218 }
219 Value *EmitCastExpr(const Expr *E, QualType T);
220
221 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattner9b655512007-08-31 22:49:20 +0000222 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000223 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000224
Chris Lattner33793202007-08-31 22:09:40 +0000225 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000226
Mike Stumpa99038c2009-02-28 09:07:16 +0000227 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattner33793202007-08-31 22:09:40 +0000228
Chris Lattner7f02f722007-08-24 05:35:26 +0000229 // Unary Operators.
230 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
231 Value *VisitUnaryPostDec(const UnaryOperator *E) {
232 return VisitPrePostIncDec(E, false, false);
233 }
234 Value *VisitUnaryPostInc(const UnaryOperator *E) {
235 return VisitPrePostIncDec(E, true, false);
236 }
237 Value *VisitUnaryPreDec(const UnaryOperator *E) {
238 return VisitPrePostIncDec(E, false, true);
239 }
240 Value *VisitUnaryPreInc(const UnaryOperator *E) {
241 return VisitPrePostIncDec(E, true, true);
242 }
243 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
244 return EmitLValue(E->getSubExpr()).getAddress();
245 }
246 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
247 Value *VisitUnaryPlus(const UnaryOperator *E) {
248 return Visit(E->getSubExpr());
249 }
250 Value *VisitUnaryMinus (const UnaryOperator *E);
251 Value *VisitUnaryNot (const UnaryOperator *E);
252 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000253 Value *VisitUnaryReal (const UnaryOperator *E);
254 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000255 Value *VisitUnaryExtension(const UnaryOperator *E) {
256 return Visit(E->getSubExpr());
257 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000258 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner04421082008-04-08 04:40:51 +0000259 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
260 return Visit(DAE->getExpr());
261 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000262
Chris Lattner7f02f722007-08-24 05:35:26 +0000263 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000264 Value *EmitMul(const BinOpInfo &Ops) {
265 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
266 }
267 Value *EmitDiv(const BinOpInfo &Ops);
268 Value *EmitRem(const BinOpInfo &Ops);
269 Value *EmitAdd(const BinOpInfo &Ops);
270 Value *EmitSub(const BinOpInfo &Ops);
271 Value *EmitShl(const BinOpInfo &Ops);
272 Value *EmitShr(const BinOpInfo &Ops);
273 Value *EmitAnd(const BinOpInfo &Ops) {
274 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
275 }
276 Value *EmitXor(const BinOpInfo &Ops) {
277 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
278 }
279 Value *EmitOr (const BinOpInfo &Ops) {
280 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
281 }
282
Chris Lattner1f1ded92007-08-24 21:00:35 +0000283 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000284 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000285 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
286
287 // Binary operators and binary compound assignment operators.
288#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000289 Value *VisitBin ## OP(const BinaryOperator *E) { \
290 return Emit ## OP(EmitBinOps(E)); \
291 } \
292 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
293 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000294 }
295 HANDLEBINOP(Mul);
296 HANDLEBINOP(Div);
297 HANDLEBINOP(Rem);
298 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000299 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000300 HANDLEBINOP(Shl);
301 HANDLEBINOP(Shr);
302 HANDLEBINOP(And);
303 HANDLEBINOP(Xor);
304 HANDLEBINOP(Or);
305#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000306
Chris Lattner7f02f722007-08-24 05:35:26 +0000307 // Comparisons.
308 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
309 unsigned SICmpOpc, unsigned FCmpOpc);
310#define VISITCOMP(CODE, UI, SI, FP) \
311 Value *VisitBin##CODE(const BinaryOperator *E) { \
312 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
313 llvm::FCmpInst::FP); }
314 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
315 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
316 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
317 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
318 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
319 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
320#undef VISITCOMP
321
322 Value *VisitBinAssign (const BinaryOperator *E);
323
324 Value *VisitBinLAnd (const BinaryOperator *E);
325 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000326 Value *VisitBinComma (const BinaryOperator *E);
327
328 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000329 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000330 Value *VisitConditionalOperator(const ConditionalOperator *CO);
331 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000332 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000333 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
334 return CGF.EmitObjCStringLiteral(E);
335 }
336};
337} // end anonymous namespace.
338
339//===----------------------------------------------------------------------===//
340// Utilities
341//===----------------------------------------------------------------------===//
342
Chris Lattner9abc84e2007-08-26 16:42:57 +0000343/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000344/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000345Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
346 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
347
348 if (SrcType->isRealFloatingType()) {
349 // Compare against 0.0 for fp scalars.
350 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000351 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
352 }
353
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000354 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000355 "Unknown scalar type to convert");
356
357 // Because of the type rules of C, we often end up computing a logical value,
358 // then zero extending it to int, then wanting it as a logical value again.
359 // Optimize this common case.
360 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
361 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
362 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000363 // If there aren't any more uses, zap the instruction to save space.
364 // Note that there can be more uses, for example if this
365 // is the result of an assignment.
366 if (ZI->use_empty())
367 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000368 return Result;
369 }
370 }
371
372 // Compare against an integer or pointer null.
373 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
374 return Builder.CreateICmpNE(Src, Zero, "tobool");
375}
376
Chris Lattner3707b252007-08-26 06:48:56 +0000377/// EmitScalarConversion - Emit a conversion from the specified type to the
378/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000379Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
380 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000381 SrcType = CGF.getContext().getCanonicalType(SrcType);
382 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000383 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000384
385 if (DstType->isVoidType()) return 0;
Chris Lattner3707b252007-08-26 06:48:56 +0000386
387 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000388 if (DstType->isBooleanType())
389 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000390
391 const llvm::Type *DstTy = ConvertType(DstType);
392
393 // Ignore conversions like int -> uint.
394 if (Src->getType() == DstTy)
395 return Src;
396
Daniel Dunbar270cc662008-08-25 09:51:32 +0000397 // Handle pointer conversions next: pointers can only be converted
398 // to/from other pointers and integers. Check for pointer types in
399 // terms of LLVM, as some native types (like Obj-C id) may map to a
400 // pointer type.
401 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000402 // The source value may be an integer, or a pointer.
403 if (isa<llvm::PointerType>(Src->getType()))
404 return Builder.CreateBitCast(Src, DstTy, "conv");
405 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000406 // First, convert to the correct width so that we control the kind of
407 // extension.
408 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
409 bool InputSigned = SrcType->isSignedIntegerType();
410 llvm::Value* IntResult =
411 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
412 // Then, cast to pointer.
413 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000414 }
415
Daniel Dunbar270cc662008-08-25 09:51:32 +0000416 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000417 // Must be an ptr to int cast.
418 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000419 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000420 }
421
Nate Begeman213541a2008-04-18 23:10:10 +0000422 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000423 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
424 // Cast the scalar to element type
425 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
426 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
427
428 // Insert the element in element zero of an undef vector
429 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
430 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
431 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
432
433 // Splat the element across to all elements
434 llvm::SmallVector<llvm::Constant*, 16> Args;
435 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
436 for (unsigned i = 0; i < NumElements; i++)
437 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
438
439 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
440 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
441 return Yay;
442 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000443
Chris Lattner3b1ae002008-02-02 04:51:41 +0000444 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000445 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000446 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000447 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000448
Chris Lattner3707b252007-08-26 06:48:56 +0000449 // Finally, we have the arithmetic types: real int/float.
450 if (isa<llvm::IntegerType>(Src->getType())) {
451 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000452 if (isa<llvm::IntegerType>(DstTy))
453 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
454 else if (InputSigned)
455 return Builder.CreateSIToFP(Src, DstTy, "conv");
456 else
457 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000458 }
459
460 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
461 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000462 if (DstType->isSignedIntegerType())
463 return Builder.CreateFPToSI(Src, DstTy, "conv");
464 else
465 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000466 }
467
468 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000469 if (DstTy->getTypeID() < Src->getType()->getTypeID())
470 return Builder.CreateFPTrunc(Src, DstTy, "conv");
471 else
472 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000473}
474
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000475/// EmitComplexToScalarConversion - Emit a conversion from the specified
476/// complex type to the specified destination type, where the destination
477/// type is an LLVM scalar type.
478Value *ScalarExprEmitter::
479EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
480 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000481 // Get the source element type.
Chris Lattner96196622008-07-26 22:37:01 +0000482 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnered70f0a2007-08-26 16:52:28 +0000483
484 // Handle conversions to bool first, they are special: comparisons against 0.
485 if (DstTy->isBooleanType()) {
486 // Complex != 0 -> (Real != 0) | (Imag != 0)
487 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
488 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
489 return Builder.CreateOr(Src.first, Src.second, "tobool");
490 }
491
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000492 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
493 // the imaginary part of the complex value is discarded and the value of the
494 // real part is converted according to the conversion rules for the
495 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000496 return EmitScalarConversion(Src.first, SrcTy, DstTy);
497}
498
499
Chris Lattner7f02f722007-08-24 05:35:26 +0000500//===----------------------------------------------------------------------===//
501// Visitor Methods
502//===----------------------------------------------------------------------===//
503
504Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000505 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000506 if (E->getType()->isVoidType())
507 return 0;
508 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
509}
510
Eli Friedmand38617c2008-05-14 19:38:39 +0000511Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
512 llvm::SmallVector<llvm::Constant*, 32> indices;
513 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
514 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
515 }
516 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
517 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
518 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
519 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
520}
521
Chris Lattner7f02f722007-08-24 05:35:26 +0000522Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
523 // Emit subscript expressions in rvalue context's. For most cases, this just
524 // loads the lvalue formed by the subscript expr. However, we have to be
525 // careful, because the base of a vector subscript is occasionally an rvalue,
526 // so we can't get it as an lvalue.
527 if (!E->getBase()->getType()->isVectorType())
528 return EmitLoadOfLValue(E);
529
530 // Handle the vector case. The base must be a vector, the index must be an
531 // integer value.
532 Value *Base = Visit(E->getBase());
533 Value *Idx = Visit(E->getIdx());
534
535 // FIXME: Convert Idx to i32 type.
536 return Builder.CreateExtractElement(Base, Idx, "vecext");
537}
538
539/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
540/// also handle things like function to pointer-to-function decay, and array to
541/// pointer decay.
542Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
543 const Expr *Op = E->getSubExpr();
544
545 // If this is due to array->pointer conversion, emit the array expression as
546 // an l-value.
547 if (Op->getType()->isArrayType()) {
548 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
549 // will not true when we add support for VLAs.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000550 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000551
552 if (!Op->getType()->isVariableArrayType()) {
553 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
554 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
555 ->getElementType()) &&
556 "Expected pointer to array");
557 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar662174c82008-08-29 17:28:43 +0000558 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000559
560 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerf31627f2008-07-23 06:31:27 +0000561 // types as well (e.g. void*) and can be implicitly converted to integer.
562 const llvm::Type *DestTy = ConvertType(E->getType());
563 if (V->getType() != DestTy) {
564 if (isa<llvm::PointerType>(DestTy))
565 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
566 else {
567 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
568 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
569 }
570 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000571 return V;
572
Anders Carlsson793680e2007-10-12 23:56:29 +0000573 } else if (E->getType()->isReferenceType()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000574 // FIXME: An expression cannot have reference type.
Anders Carlsson793680e2007-10-12 23:56:29 +0000575 return EmitLValue(Op).getAddress();
Chris Lattner7f02f722007-08-24 05:35:26 +0000576 }
577
578 return EmitCastExpr(Op, E->getType());
579}
580
581
582// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
583// have to handle a more broad range of conversions than explicit casts, as they
584// handle things like function to ptr-to-function decay etc.
585Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner58a2e942007-08-26 07:26:12 +0000586 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000587
588 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000589 Value *Src = Visit(const_cast<Expr*>(E));
590
Chris Lattner3707b252007-08-26 06:48:56 +0000591 // Use EmitScalarConversion to perform the conversion.
592 return EmitScalarConversion(Src, E->getType(), DestTy);
593 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000594
Chris Lattner9b2dc282008-04-04 16:54:41 +0000595 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000596 // Handle cases where the source is a complex type.
597 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
598 DestTy);
599 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000600
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000601 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
602 // evaluate the result and return.
603 CGF.EmitAggExpr(E, 0, false);
604 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000605}
606
Chris Lattner33793202007-08-31 22:09:40 +0000607Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000608 return CGF.EmitCompoundStmt(*E->getSubStmt(),
609 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000610}
611
Mike Stumpa99038c2009-02-28 09:07:16 +0000612Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
613 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +0000614}
Chris Lattner33793202007-08-31 22:09:40 +0000615
Chris Lattner7f02f722007-08-24 05:35:26 +0000616//===----------------------------------------------------------------------===//
617// Unary Operators
618//===----------------------------------------------------------------------===//
619
620Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000621 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000622 LValue LV = EmitLValue(E->getSubExpr());
623 // FIXME: Handle volatile!
Chris Lattnere936cc82007-08-26 05:10:16 +0000624 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattner9b655512007-08-31 22:49:20 +0000625 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000626
627 int AmountVal = isInc ? 1 : -1;
628
629 Value *NextVal;
Chris Lattner8cc9d082009-03-18 04:25:13 +0000630 if (const llvm::PointerType *PT =
631 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattnere936cc82007-08-26 05:10:16 +0000632 // FIXME: This isn't right for VLAs.
Chris Lattner8cc9d082009-03-18 04:25:13 +0000633 llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
634 if (!isa<llvm::FunctionType>(PT->getElementType())) {
635 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
636 } else {
637 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
638 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
639 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
640 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
641 }
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +0000642 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
643 // Bool++ is an interesting case, due to promotion rules, we get:
644 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
645 // Bool = ((int)Bool+1) != 0
646 // An interesting aspect of this is that increment is always true.
647 // Decrement does not have this property.
648 NextVal = llvm::ConstantInt::getTrue();
Chris Lattnere936cc82007-08-26 05:10:16 +0000649 } else {
650 // Add the inc/dec to the real part.
651 if (isa<llvm::IntegerType>(InVal->getType()))
652 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000653 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000654 NextVal =
Chris Lattner59138ba2008-04-20 00:45:53 +0000655 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000656 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000657 NextVal =
Chris Lattner59138ba2008-04-20 00:45:53 +0000658 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000659 else {
660 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000661 bool ignored;
662 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
663 &ignored);
Chris Lattner25ddea72008-04-20 00:50:39 +0000664 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000665 }
Chris Lattnere936cc82007-08-26 05:10:16 +0000666 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
667 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000668
669 // Store the updated result through the lvalue.
670 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
671 E->getSubExpr()->getType());
672
673 // If this is a postinc, return the value read from memory, otherwise use the
674 // updated value.
675 return isPre ? NextVal : InVal;
676}
677
678
679Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
680 Value *Op = Visit(E->getSubExpr());
681 return Builder.CreateNeg(Op, "neg");
682}
683
684Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
685 Value *Op = Visit(E->getSubExpr());
686 return Builder.CreateNot(Op, "neg");
687}
688
689Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
690 // Compare operand to zero.
691 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
692
693 // Invert value.
694 // TODO: Could dynamically modify easy computations here. For example, if
695 // the operand is an icmp ne, turn into icmp eq.
696 BoolVal = Builder.CreateNot(BoolVal, "lnot");
697
698 // ZExt result to int.
699 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
700}
701
Sebastian Redl05189992008-11-11 17:56:53 +0000702/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
703/// argument of the sizeof expression as an integer.
704Value *
705ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +0000706 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000707 if (E->isSizeOf()) {
708 if (const VariableArrayType *VAT =
709 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
710 if (E->isArgumentType()) {
711 // sizeof(type) - make sure to emit the VLA size.
712 CGF.EmitVLASize(TypeToSize);
713 }
Anders Carlsson6cd586d2009-01-30 16:41:04 +0000714
Anders Carlsson96f21472009-02-05 19:43:10 +0000715 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000716 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000717 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000718
719 // If this isn't sizeof(vla), the result must be constant; use the
720 // constant folding logic so we don't have to duplicate it here.
721 Expr::EvalResult Result;
722 E->Evaluate(Result, CGF.getContext());
723 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +0000724}
725
Chris Lattner46f93d02007-08-24 21:20:17 +0000726Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
727 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000728 if (Op->getType()->isAnyComplexType())
Chris Lattner46f93d02007-08-24 21:20:17 +0000729 return CGF.EmitComplexExpr(Op).first;
730 return Visit(Op);
731}
732Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
733 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000734 if (Op->getType()->isAnyComplexType())
Chris Lattner46f93d02007-08-24 21:20:17 +0000735 return CGF.EmitComplexExpr(Op).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000736
737 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
738 // effects are evaluated.
739 CGF.EmitScalarExpr(Op);
740 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000741}
742
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000743Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
744{
Eli Friedman35183ac2009-02-27 06:44:11 +0000745 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +0000746 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +0000747 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000748}
Chris Lattner46f93d02007-08-24 21:20:17 +0000749
Chris Lattner7f02f722007-08-24 05:35:26 +0000750//===----------------------------------------------------------------------===//
751// Binary Operators
752//===----------------------------------------------------------------------===//
753
754BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
755 BinOpInfo Result;
756 Result.LHS = Visit(E->getLHS());
757 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000758 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000759 Result.E = E;
760 return Result;
761}
762
Chris Lattner3ccf7742007-08-26 21:41:21 +0000763Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000764 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
765 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
766
767 BinOpInfo OpInfo;
768
769 // Load the LHS and RHS operands.
770 LValue LHSLV = EmitLValue(E->getLHS());
771 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner04dc7642007-08-26 22:37:40 +0000772
773 // Determine the computation type. If the RHS is complex, then this is one of
774 // the add/sub/mul/div operators. All of these operators can be computed in
775 // with just their real component even though the computation domain really is
776 // complex.
Chris Lattner3ccf7742007-08-26 21:41:21 +0000777 QualType ComputeType = E->getComputationType();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000778
Chris Lattner04dc7642007-08-26 22:37:40 +0000779 // If the computation type is complex, then the RHS is complex. Emit the RHS.
780 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
781 ComputeType = CT->getElementType();
782
783 // Emit the RHS, only keeping the real component.
784 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
785 RHSTy = RHSTy->getAsComplexType()->getElementType();
786 } else {
787 // Otherwise the RHS is a simple scalar value.
788 OpInfo.RHS = Visit(E->getRHS());
789 }
790
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000791 QualType LComputeTy, RComputeTy, ResultTy;
792
793 // Compound assignment does not contain enough information about all
794 // the types involved for pointer arithmetic cases. Figure it out
795 // here for now.
796 if (E->getLHS()->getType()->isPointerType()) {
797 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
798 assert((E->getOpcode() == BinaryOperator::AddAssign ||
799 E->getOpcode() == BinaryOperator::SubAssign) &&
800 "Invalid compound assignment operator on pointer type.");
801 LComputeTy = E->getLHS()->getType();
802
803 if (E->getRHS()->getType()->isPointerType()) {
804 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
805 // extension, the conversion from the pointer difference back to
806 // the LHS type is handled at the end.
807 assert(E->getOpcode() == BinaryOperator::SubAssign &&
808 "Invalid compound assignment operator on pointer type.");
809 RComputeTy = E->getLHS()->getType();
810 ResultTy = CGF.getContext().getPointerDiffType();
811 } else {
812 RComputeTy = E->getRHS()->getType();
813 ResultTy = LComputeTy;
814 }
815 } else if (E->getRHS()->getType()->isPointerType()) {
816 // Degenerate case of (int += ptr) allowed by GCC implicit cast
817 // extension.
818 assert(E->getOpcode() == BinaryOperator::AddAssign &&
819 "Invalid compound assignment operator on pointer type.");
820 LComputeTy = E->getLHS()->getType();
821 RComputeTy = E->getRHS()->getType();
822 ResultTy = RComputeTy;
823 } else {
824 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000825 }
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000826
827 // Convert the LHS/RHS values to the computation type.
828 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
829 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
830 OpInfo.Ty = ResultTy;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000831 OpInfo.E = E;
832
833 // Expand the binary operator.
834 Value *Result = (this->*Func)(OpInfo);
835
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000836 // Convert the result back to the LHS type.
837 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000838
Daniel Dunbared3849b2008-11-19 09:36:46 +0000839 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar371d16f2008-11-19 11:54:05 +0000840 // handled specially because the result is altered by the store,
841 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
842 // the left operand after the assignment...'.
Eli Friedman18491282008-05-25 14:13:57 +0000843 if (LHSLV.isBitfield())
Daniel Dunbared3849b2008-11-19 09:36:46 +0000844 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
845 &Result);
846 else
847 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
848
Chris Lattner1f1ded92007-08-24 21:00:35 +0000849 return Result;
850}
851
852
Chris Lattner7f02f722007-08-24 05:35:26 +0000853Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000854 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000855 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000856 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000857 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
858 else
859 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
860}
861
862Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
863 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000864 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000865 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
866 else
867 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
868}
869
870
871Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner1f1ded92007-08-24 21:00:35 +0000872 if (!Ops.Ty->isPointerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000873 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000874
875 // FIXME: What about a pointer to a VLA?
Chris Lattner8f925282008-01-03 06:36:51 +0000876 Value *Ptr, *Idx;
877 Expr *IdxExp;
Daniel Dunbarb09fae72009-01-23 18:51:09 +0000878 const PointerType *PT;
879 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner8f925282008-01-03 06:36:51 +0000880 Ptr = Ops.LHS;
881 Idx = Ops.RHS;
882 IdxExp = Ops.E->getRHS();
883 } else { // int + pointer
Daniel Dunbarb09fae72009-01-23 18:51:09 +0000884 PT = Ops.E->getRHS()->getType()->getAsPointerType();
885 assert(PT && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +0000886 Ptr = Ops.RHS;
887 Idx = Ops.LHS;
888 IdxExp = Ops.E->getLHS();
889 }
890
891 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
892 if (Width < CGF.LLVMPointerWidth) {
893 // Zero or sign extend the pointer value based on whether the index is
894 // signed or not.
895 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +0000896 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +0000897 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
898 else
899 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
900 }
Daniel Dunbarb09fae72009-01-23 18:51:09 +0000901
902 // Explicitly handle GNU void* and function pointer arithmetic
903 // extensions. The GNU void* casts amount to no-ops since our void*
904 // type is i8*, but this is future proof.
905 const QualType ElementType = PT->getPointeeType();
906 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
907 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
908 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
909 Value *Res = Builder.CreateGEP(Casted, Idx, "sub.ptr");
910 return Builder.CreateBitCast(Res, Ptr->getType());
911 }
Chris Lattner8f925282008-01-03 06:36:51 +0000912
913 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +0000914}
915
916Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
917 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
918 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000919
Daniel Dunbarb09fae72009-01-23 18:51:09 +0000920 const QualType LHSType = Ops.E->getLHS()->getType();
921 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000922 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
923 // pointer - int
924 Value *Idx = Ops.RHS;
925 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
926 if (Width < CGF.LLVMPointerWidth) {
927 // Zero or sign extend the pointer value based on whether the index is
928 // signed or not.
929 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
930 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
931 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
932 else
933 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
934 }
935 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
936
937 // FIXME: The pointer could point to a VLA.
Daniel Dunbarb09fae72009-01-23 18:51:09 +0000938
939 // Explicitly handle GNU void* and function pointer arithmetic
940 // extensions. The GNU void* casts amount to no-ops since our
941 // void* type is i8*, but this is future proof.
942 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
943 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
944 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
945 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
946 return Builder.CreateBitCast(Res, Ops.LHS->getType());
947 }
948
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000949 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +0000950 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000951 // pointer - pointer
952 Value *LHS = Ops.LHS;
953 Value *RHS = Ops.RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000954
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000955 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +0000956
Chris Lattnere5ed1512009-02-11 07:21:43 +0000957 // Handle GCC extension for pointer arithmetic on void* and function pointer
958 // types.
959 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000960 ElementSize = 1;
961 } else {
962 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
963 }
964
965 const llvm::Type *ResultType = ConvertType(Ops.Ty);
966 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
967 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
968 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
969
Chris Lattnere5ed1512009-02-11 07:21:43 +0000970 // Optimize out the shift for element size of 1.
971 if (ElementSize == 1)
972 return BytesBetween;
973
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000974 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
975 // remainder. As such, we handle common power-of-two cases here to generate
976 // better code. See PR2247.
977 if (llvm::isPowerOf2_64(ElementSize)) {
978 Value *ShAmt =
979 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
980 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
981 }
982
983 // Otherwise, do a full sdiv.
984 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
985 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +0000986 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000987}
988
989Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
990 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
991 // RHS to the same size as the LHS.
992 Value *RHS = Ops.RHS;
993 if (Ops.LHS->getType() != RHS->getType())
994 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
995
996 return Builder.CreateShl(Ops.LHS, RHS, "shl");
997}
998
999Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1000 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1001 // RHS to the same size as the LHS.
1002 Value *RHS = Ops.RHS;
1003 if (Ops.LHS->getType() != RHS->getType())
1004 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1005
Chris Lattner1f1ded92007-08-24 21:00:35 +00001006 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001007 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1008 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1009}
1010
1011Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1012 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001013 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001014 QualType LHSTy = E->getLHS()->getType();
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001015 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001016 Value *LHS = Visit(E->getLHS());
1017 Value *RHS = Visit(E->getRHS());
1018
1019 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001020 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001021 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001022 } else if (LHSTy->isSignedIntegerType()) {
1023 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001024 LHS, RHS, "cmp");
1025 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001026 // Unsigned integers and pointers.
1027 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001028 LHS, RHS, "cmp");
1029 }
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001030 } else if (LHSTy->isVectorType()) {
1031 Value *LHS = Visit(E->getLHS());
1032 Value *RHS = Visit(E->getRHS());
1033
1034 if (LHS->getType()->isFPOrFPVector()) {
1035 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1036 LHS, RHS, "cmp");
1037 } else if (LHSTy->isUnsignedIntegerType()) {
1038 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1039 LHS, RHS, "cmp");
1040 } else {
1041 // Signed integers and pointers.
1042 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1043 LHS, RHS, "cmp");
1044 }
1045 return Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001046 } else {
1047 // Complex Comparison: can only be an equality comparison.
1048 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1049 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1050
Chris Lattner96196622008-07-26 22:37:01 +00001051 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner7f02f722007-08-24 05:35:26 +00001052
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001053 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001054 if (CETy->isRealFloatingType()) {
1055 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1056 LHS.first, RHS.first, "cmp.r");
1057 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1058 LHS.second, RHS.second, "cmp.i");
1059 } else {
1060 // Complex comparisons can only be equality comparisons. As such, signed
1061 // and unsigned opcodes are the same.
1062 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1063 LHS.first, RHS.first, "cmp.r");
1064 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1065 LHS.second, RHS.second, "cmp.i");
1066 }
1067
1068 if (E->getOpcode() == BinaryOperator::EQ) {
1069 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1070 } else {
1071 assert(E->getOpcode() == BinaryOperator::NE &&
1072 "Complex comparison other than == or != ?");
1073 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1074 }
1075 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001076
1077 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001078}
1079
1080Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1081 LValue LHS = EmitLValue(E->getLHS());
1082 Value *RHS = Visit(E->getRHS());
1083
Daniel Dunbared3849b2008-11-19 09:36:46 +00001084 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001085 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1086 // 'An assignment expression has the value of the left operand after
1087 // the assignment...'.
Chris Lattner7f02f722007-08-24 05:35:26 +00001088 // FIXME: Volatility!
Eli Friedman18491282008-05-25 14:13:57 +00001089 if (LHS.isBitfield())
Daniel Dunbared3849b2008-11-19 09:36:46 +00001090 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1091 &RHS);
1092 else
1093 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbar85c59ed2008-08-29 08:11:39 +00001094
Chris Lattner7f02f722007-08-24 05:35:26 +00001095 // Return the RHS.
1096 return RHS;
1097}
1098
1099Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001100 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1101 // If we have 1 && X, just emit X without inserting the control flow.
1102 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1103 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001104 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1105 // ZExt result to int.
1106 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1107 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001108
1109 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1110 if (!CGF.ContainsLabel(E->getRHS()))
1111 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001112 }
1113
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001114 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1115 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001116
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001117 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1118 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1119
1120 // Any edges into the ContBlock are now from an (indeterminate number of)
1121 // edges from this first condition. All of these values will be false. Start
1122 // setting up the PHI node in the Cont Block for this.
1123 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1124 PN->reserveOperandSpace(2); // Normal case, two inputs.
1125 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1126 PI != PE; ++PI)
1127 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner7f02f722007-08-24 05:35:26 +00001128
1129 CGF.EmitBlock(RHSBlock);
1130 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1131
1132 // Reaquire the RHS block, as there may be subblocks inserted.
1133 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001134
1135 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1136 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001137 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001138 PN->addIncoming(RHSCond, RHSBlock);
1139
1140 // ZExt result to int.
1141 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1142}
1143
1144Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001145 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1146 // If we have 0 || X, just emit X without inserting the control flow.
1147 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1148 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001149 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1150 // ZExt result to int.
1151 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1152 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001153
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001154 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001155 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001156 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001157 }
1158
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001159 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1160 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner7f02f722007-08-24 05:35:26 +00001161
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001162 // Branch on the LHS first. If it is true, go to the success (cont) block.
1163 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1164
1165 // Any edges into the ContBlock are now from an (indeterminate number of)
1166 // edges from this first condition. All of these values will be true. Start
1167 // setting up the PHI node in the Cont Block for this.
1168 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1169 PN->reserveOperandSpace(2); // Normal case, two inputs.
1170 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1171 PI != PE; ++PI)
1172 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1173
1174 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001175 CGF.EmitBlock(RHSBlock);
1176 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1177
1178 // Reaquire the RHS block, as there may be subblocks inserted.
1179 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00001180
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001181 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1182 // into the phi node for the edge with the value of RHSCond.
1183 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001184 PN->addIncoming(RHSCond, RHSBlock);
1185
1186 // ZExt result to int.
1187 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1188}
1189
1190Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1191 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001192 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001193 return Visit(E->getRHS());
1194}
1195
1196//===----------------------------------------------------------------------===//
1197// Other Operators
1198//===----------------------------------------------------------------------===//
1199
Chris Lattner9802a512008-11-12 08:55:54 +00001200/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1201/// expression is cheap enough and side-effect-free enough to evaluate
1202/// unconditionally instead of conditionally. This is used to convert control
1203/// flow into selects in some cases.
1204static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1205 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1206 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1207
1208 // TODO: Allow anything we can constant fold to an integer or fp constant.
1209 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1210 isa<FloatingLiteral>(E))
1211 return true;
1212
1213 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1214 // X and Y are local variables.
1215 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1216 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1217 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1218 return true;
1219
1220 return false;
1221}
1222
1223
Chris Lattner7f02f722007-08-24 05:35:26 +00001224Value *ScalarExprEmitter::
1225VisitConditionalOperator(const ConditionalOperator *E) {
Chris Lattner31a09842008-11-12 08:04:58 +00001226 // If the condition constant folds and can be elided, try to avoid emitting
1227 // the condition and the dead arm.
1228 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001229 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001230 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001231 std::swap(Live, Dead);
Chris Lattner31a09842008-11-12 08:04:58 +00001232
1233 // If the dead side doesn't have labels we need, and if the Live side isn't
1234 // the gnu missing ?: extension (which we could handle, but don't bother
1235 // to), just emit the Live part.
1236 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1237 Live) // Live part isn't missing.
1238 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001239 }
1240
Chris Lattner9802a512008-11-12 08:55:54 +00001241
1242 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1243 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001244 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001245 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1246 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1247 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1248 llvm::Value *LHS = Visit(E->getLHS());
1249 llvm::Value *RHS = Visit(E->getRHS());
1250 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1251 }
1252
1253
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001254 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1255 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001256 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001257 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001258
Chris Lattner12d152f2009-02-13 23:35:32 +00001259 // If we don't have the GNU missing condition extension, emit a branch on
1260 // bool the normal way.
1261 if (E->getLHS()) {
1262 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1263 // the branch on bool.
1264 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1265 } else {
1266 // Otherwise, for the ?: extension, evaluate the conditional and then
1267 // convert it to bool the hard way. We do this explicitly because we need
1268 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001269 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00001270
1271 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1272 // if there are no extra uses (an optimization). Inhibit this by making an
1273 // extra dead use, because we're going to add a use of CondVal later. We
1274 // don't use the builder for this, because we don't want it to get optimized
1275 // away. This leaves dead code, but the ?: extension isn't common.
1276 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1277 Builder.GetInsertBlock());
1278
Chris Lattner035cf422008-11-12 08:08:13 +00001279 Value *CondBoolVal =
1280 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1281 CGF.getContext().BoolTy);
1282 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001283 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001284
1285 CGF.EmitBlock(LHSBlock);
1286
1287 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001288 Value *LHS;
1289 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001290 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001291 else // Perform promotions, to handle cases like "short ?: int"
1292 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1293
Chris Lattner7f02f722007-08-24 05:35:26 +00001294 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001295 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001296
1297 CGF.EmitBlock(RHSBlock);
1298
Eli Friedman856226c2008-05-16 20:38:39 +00001299 Value *RHS = Visit(E->getRHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001300 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001301 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001302
1303 CGF.EmitBlock(ContBlock);
1304
Nuno Lopes108f55d2008-06-04 19:15:45 +00001305 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001306 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1307 return 0;
1308 }
1309
Chris Lattner7f02f722007-08-24 05:35:26 +00001310 // Create a PHI node for the real part.
1311 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1312 PN->reserveOperandSpace(2);
1313 PN->addIncoming(LHS, LHSBlock);
1314 PN->addIncoming(RHS, RHSBlock);
1315 return PN;
1316}
1317
1318Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001319 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001320}
1321
Chris Lattner2202bce2007-11-30 17:56:23 +00001322Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001323 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001324 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1325
1326 // If EmitVAArg fails, we fall back to the LLVM instruction.
1327 if (!ArgPtr)
1328 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1329
1330 // FIXME: volatile?
1331 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001332}
1333
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001334Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001335 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001336}
1337
Chris Lattner7f02f722007-08-24 05:35:26 +00001338//===----------------------------------------------------------------------===//
1339// Entry Point into this File
1340//===----------------------------------------------------------------------===//
1341
1342/// EmitComplexExpr - Emit the computation of the specified expression of
1343/// complex type, ignoring the result.
1344Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1345 assert(E && !hasAggregateLLVMType(E->getType()) &&
1346 "Invalid scalar expression to emit");
1347
1348 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1349}
Chris Lattner3707b252007-08-26 06:48:56 +00001350
1351/// EmitScalarConversion - Emit a conversion from the specified type to the
1352/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001353Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1354 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001355 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1356 "Invalid scalar expression to emit");
1357 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1358}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001359
1360/// EmitComplexToScalarConversion - Emit a conversion from the specified
1361/// complex type to the specified destination type, where the destination
1362/// type is an LLVM scalar type.
1363Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1364 QualType SrcTy,
1365 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001366 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001367 "Invalid complex -> scalar conversion");
1368 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1369 DstTy);
1370}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001371
1372Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1373 assert(V1->getType() == V2->getType() &&
1374 "Vector operands must be of the same type");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001375 unsigned NumElements =
1376 cast<llvm::VectorType>(V1->getType())->getNumElements();
1377
1378 va_list va;
1379 va_start(va, V2);
1380
1381 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001382 for (unsigned i = 0; i < NumElements; i++) {
1383 int n = va_arg(va, int);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001384 assert(n >= 0 && n < (int)NumElements * 2 &&
1385 "Vector shuffle index out of bounds!");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001386 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1387 }
1388
1389 const char *Name = va_arg(va, const char *);
1390 va_end(va);
1391
1392 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1393
1394 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1395}
1396
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001397llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001398 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001399 llvm::Value *Vec
Chris Lattner345f7202008-07-26 20:15:14 +00001400 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001401
Chris Lattner345f7202008-07-26 20:15:14 +00001402 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001403 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001404 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001405 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001406 }
1407
1408 return Vec;
1409}