blob: cc81256032afbc69194f7ff89bf8a96bcba80e2b [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"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000015#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000016#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000018#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000022#include "llvm/Constants.h"
23#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000025#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000026#include "llvm/Module.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000027#include "llvm/Support/Compiler.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000028#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000029#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000030#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000031
Chris Lattner7f02f722007-08-24 05:35:26 +000032using namespace clang;
33using namespace CodeGen;
34using llvm::Value;
35
36//===----------------------------------------------------------------------===//
37// Scalar Expression Emitter
38//===----------------------------------------------------------------------===//
39
40struct BinOpInfo {
41 Value *LHS;
42 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000043 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000044 const BinaryOperator *E;
45};
46
47namespace {
48class VISIBILITY_HIDDEN ScalarExprEmitter
49 : public StmtVisitor<ScalarExprEmitter, Value*> {
50 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000051 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000052 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000053 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000054public:
55
Mike Stump7f79f9b2009-05-29 15:46:01 +000056 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000057 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000058 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000059 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000060
Chris Lattner7f02f722007-08-24 05:35:26 +000061 //===--------------------------------------------------------------------===//
62 // Utilities
63 //===--------------------------------------------------------------------===//
64
Mike Stump7f79f9b2009-05-29 15:46:01 +000065 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000066 bool I = IgnoreResultAssign;
67 IgnoreResultAssign = false;
68 return I;
69 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
72 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
73
74 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000075 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000076 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000077
Chris Lattner7f02f722007-08-24 05:35:26 +000078 /// EmitLoadOfLValue - Given an expression with complex type that represents a
79 /// value l-value, this method emits the address of the l-value, then loads
80 /// and returns the result.
81 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +000082 return EmitLoadOfLValue(EmitLValue(E), E->getType());
83 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000084
Chris Lattner9abc84e2007-08-26 16:42:57 +000085 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000086 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000087 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000088
Chris Lattner3707b252007-08-26 06:48:56 +000089 /// EmitScalarConversion - Emit a conversion from the specified type to the
90 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000091 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
92
93 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +000094 /// complex type to the specified destination type, where the destination type
95 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000096 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
97 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000098
Chris Lattner7f02f722007-08-24 05:35:26 +000099 //===--------------------------------------------------------------------===//
100 // Visitor Methods
101 //===--------------------------------------------------------------------===//
102
103 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000104 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000105 assert(0 && "Stmt can't have complex result type!");
106 return 0;
107 }
108 Value *VisitExpr(Expr *S);
109 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
110
111 // Leaves.
112 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000113 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000114 }
115 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000116 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000117 }
118 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000119 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000120 }
Nate Begemane7579b52007-11-15 05:40:03 +0000121 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000122 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000123 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000124 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000125 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000126 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000127 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000128 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Anders Carlsson3f704562008-12-21 22:39:40 +0000129 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000130 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000131 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000132 CGF.getContext().typesAreCompatible(
133 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000134 }
Sebastian Redl05189992008-11-11 17:56:53 +0000135 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000136 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000137 llvm::Value *V =
Owen Anderson0032b272009-08-13 21:57:51 +0000138 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
Daniel Dunbar54d19092008-08-16 01:41:47 +0000139 CGF.GetIDForAddrOfLabel(E->getLabel()));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000140
Daniel Dunbar54d19092008-08-16 01:41:47 +0000141 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000142 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000143
Chris Lattner7f02f722007-08-24 05:35:26 +0000144 // l-values.
145 Value *VisitDeclRefExpr(DeclRefExpr *E) {
146 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000147 return llvm::ConstantInt::get(VMContext, EC->getInitVal());
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 return EmitLoadOfLValue(E);
149 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000150 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
151 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000152 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000153 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
154 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000155 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000156 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000157 return EmitLoadOfLValue(E);
158 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000159 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000160 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000161 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000162 Value *VisitObjCImplicitSetterGetterRefExpr(
163 ObjCImplicitSetterGetterRefExpr *E) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000164 return EmitLoadOfLValue(E);
165 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000166 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
167 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000168 }
169
Chris Lattner7f02f722007-08-24 05:35:26 +0000170 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000171 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000172 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000173 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000174 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
175 return EmitLoadOfLValue(E);
176 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000177 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000178 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
179 return EmitLValue(E).getAddress();
180 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000181
Chris Lattnerd9f69102008-08-10 01:53:14 +0000182 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000183
184 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000185 bool Ignore = TestAndClearIgnoreResultAssign();
186 (void)Ignore;
187 assert (Ignore == false && "init list ignored");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000188 unsigned NumInitElements = E->getNumInits();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000189
Douglas Gregora9c87802009-01-29 19:42:23 +0000190 if (E->hadArrayRangeDesignator()) {
191 CGF.ErrorUnsupported(E, "GNU array range designator extension");
192 }
193
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000194 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000195 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000196
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000197 // We have a scalar in braces. Just use the first element.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000198 if (!VType)
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000199 return Visit(E->getInit(0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000200
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000201 unsigned NumVectorElements = VType->getNumElements();
202 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000203
204 // Emit individual vector element stores.
Owen Anderson03e20502009-07-30 23:11:26 +0000205 llvm::Value *V = llvm::UndefValue::get(VType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000206
Anders Carlsson222d2c82007-12-18 02:45:33 +0000207 // Emit initializers
208 unsigned i;
209 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000210 Value *NewV = Visit(E->getInit(i));
Owen Anderson0032b272009-08-13 21:57:51 +0000211 Value *Idx =
212 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Devang Patela83cc332007-10-24 18:05:48 +0000213 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000214 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000215
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000216 // Emit remaining default initializers
217 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Anderson0032b272009-08-13 21:57:51 +0000218 Value *Idx =
219 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000220 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000221 V = Builder.CreateInsertElement(V, NewV, Idx);
222 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000223
Devang Patela83cc332007-10-24 18:05:48 +0000224 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000225 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000226
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000227 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000228 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000229 }
Eli Friedmanc62aad82009-04-20 03:54:15 +0000230 Value *VisitCastExpr(const CastExpr *E) {
231 // Make sure to evaluate VLA bounds now so that we have them for later.
232 if (E->getType()->isVariablyModifiedType())
233 CGF.EmitVLASize(E->getType());
234
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000235 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000236 }
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000237 Value *EmitCastExpr(const CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000238
239 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000240 if (E->getCallReturnType()->isReferenceType())
241 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000242
Chris Lattner9b655512007-08-31 22:49:20 +0000243 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000244 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000245
Chris Lattner33793202007-08-31 22:09:40 +0000246 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000247
Mike Stumpa99038c2009-02-28 09:07:16 +0000248 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000249
Chris Lattner7f02f722007-08-24 05:35:26 +0000250 // Unary Operators.
251 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
252 Value *VisitUnaryPostDec(const UnaryOperator *E) {
253 return VisitPrePostIncDec(E, false, false);
254 }
255 Value *VisitUnaryPostInc(const UnaryOperator *E) {
256 return VisitPrePostIncDec(E, true, false);
257 }
258 Value *VisitUnaryPreDec(const UnaryOperator *E) {
259 return VisitPrePostIncDec(E, false, true);
260 }
261 Value *VisitUnaryPreInc(const UnaryOperator *E) {
262 return VisitPrePostIncDec(E, true, true);
263 }
264 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
265 return EmitLValue(E->getSubExpr()).getAddress();
266 }
267 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
268 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000269 // This differs from gcc, though, most likely due to a bug in gcc.
270 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000271 return Visit(E->getSubExpr());
272 }
273 Value *VisitUnaryMinus (const UnaryOperator *E);
274 Value *VisitUnaryNot (const UnaryOperator *E);
275 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000276 Value *VisitUnaryReal (const UnaryOperator *E);
277 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000278 Value *VisitUnaryExtension(const UnaryOperator *E) {
279 return Visit(E->getSubExpr());
280 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000281 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000282
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000283 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000284 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
285 return Visit(DAE->getExpr());
286 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000287 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
288 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000289 }
290
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000291 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000292 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000293 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000294 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
295 return CGF.EmitCXXNewExpr(E);
296 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000297 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
298 CGF.EmitCXXDeleteExpr(E);
299 return 0;
300 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000301
Douglas Gregora71d8192009-09-04 17:36:40 +0000302 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
303 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000304 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000305 // operator (), and the result of such a call has type void. The only
306 // effect is the evaluation of the postfix-expression before the dot or
307 // arrow.
308 CGF.EmitScalarExpr(E->getBase());
309 return 0;
310 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000311
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000312 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
313 return llvm::Constant::getNullValue(ConvertType(E->getType()));
314 }
315
Chris Lattner7f02f722007-08-24 05:35:26 +0000316 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000317 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stump035cf892009-04-02 18:15:54 +0000318 if (CGF.getContext().getLangOptions().OverflowChecking
319 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000320 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000321 if (Ops.LHS->getType()->isFPOrFPVector())
322 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000323 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
324 }
Mike Stump2add4732009-04-01 20:28:16 +0000325 /// Create a binary op that checks for overflow.
326 /// Currently only supports +, - and *.
327 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 Value *EmitDiv(const BinOpInfo &Ops);
329 Value *EmitRem(const BinOpInfo &Ops);
330 Value *EmitAdd(const BinOpInfo &Ops);
331 Value *EmitSub(const BinOpInfo &Ops);
332 Value *EmitShl(const BinOpInfo &Ops);
333 Value *EmitShr(const BinOpInfo &Ops);
334 Value *EmitAnd(const BinOpInfo &Ops) {
335 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
336 }
337 Value *EmitXor(const BinOpInfo &Ops) {
338 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
339 }
340 Value *EmitOr (const BinOpInfo &Ops) {
341 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
342 }
343
Chris Lattner1f1ded92007-08-24 21:00:35 +0000344 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000345 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000346 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
347
348 // Binary operators and binary compound assignment operators.
349#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000350 Value *VisitBin ## OP(const BinaryOperator *E) { \
351 return Emit ## OP(EmitBinOps(E)); \
352 } \
353 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
354 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000355 }
356 HANDLEBINOP(Mul);
357 HANDLEBINOP(Div);
358 HANDLEBINOP(Rem);
359 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000360 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000361 HANDLEBINOP(Shl);
362 HANDLEBINOP(Shr);
363 HANDLEBINOP(And);
364 HANDLEBINOP(Xor);
365 HANDLEBINOP(Or);
366#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000367
Chris Lattner7f02f722007-08-24 05:35:26 +0000368 // Comparisons.
369 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
370 unsigned SICmpOpc, unsigned FCmpOpc);
371#define VISITCOMP(CODE, UI, SI, FP) \
372 Value *VisitBin##CODE(const BinaryOperator *E) { \
373 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
374 llvm::FCmpInst::FP); }
375 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
376 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
377 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
378 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
379 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
380 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
381#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000382
Chris Lattner7f02f722007-08-24 05:35:26 +0000383 Value *VisitBinAssign (const BinaryOperator *E);
384
385 Value *VisitBinLAnd (const BinaryOperator *E);
386 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000387 Value *VisitBinComma (const BinaryOperator *E);
388
389 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000390 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000391 Value *VisitConditionalOperator(const ConditionalOperator *CO);
392 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000393 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000394 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
395 return CGF.EmitObjCStringLiteral(E);
396 }
397};
398} // end anonymous namespace.
399
400//===----------------------------------------------------------------------===//
401// Utilities
402//===----------------------------------------------------------------------===//
403
Chris Lattner9abc84e2007-08-26 16:42:57 +0000404/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000405/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000406Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
407 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000408
Chris Lattner9abc84e2007-08-26 16:42:57 +0000409 if (SrcType->isRealFloatingType()) {
410 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000411 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000412 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
413 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000414
Anders Carlsson237957c2009-08-09 18:26:27 +0000415 if (SrcType->isMemberPointerType()) {
416 // FIXME: This is ABI specific.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000417
Anders Carlsson237957c2009-08-09 18:26:27 +0000418 // Compare against -1.
419 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
420 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
421 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000422
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000423 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000424 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000425
Chris Lattner9abc84e2007-08-26 16:42:57 +0000426 // Because of the type rules of C, we often end up computing a logical value,
427 // then zero extending it to int, then wanting it as a logical value again.
428 // Optimize this common case.
429 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000430 if (ZI->getOperand(0)->getType() ==
431 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000432 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000433 // If there aren't any more uses, zap the instruction to save space.
434 // Note that there can be more uses, for example if this
435 // is the result of an assignment.
436 if (ZI->use_empty())
437 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000438 return Result;
439 }
440 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000441
Chris Lattner9abc84e2007-08-26 16:42:57 +0000442 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000443 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000444 return Builder.CreateICmpNE(Src, Zero, "tobool");
445}
446
Chris Lattner3707b252007-08-26 06:48:56 +0000447/// EmitScalarConversion - Emit a conversion from the specified type to the
448/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000449Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
450 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000451 SrcType = CGF.getContext().getCanonicalType(SrcType);
452 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000453 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000454
Chris Lattnercf289082007-08-26 07:21:11 +0000455 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000456
Owen Anderson0032b272009-08-13 21:57:51 +0000457 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner3707b252007-08-26 06:48:56 +0000458
459 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000460 if (DstType->isBooleanType())
461 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000462
Chris Lattner3707b252007-08-26 06:48:56 +0000463 const llvm::Type *DstTy = ConvertType(DstType);
464
465 // Ignore conversions like int -> uint.
466 if (Src->getType() == DstTy)
467 return Src;
468
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000469 // Handle pointer conversions next: pointers can only be converted to/from
470 // other pointers and integers. Check for pointer types in terms of LLVM, as
471 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000472 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000473 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000474 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000475 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000476
Chris Lattner3707b252007-08-26 06:48:56 +0000477 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000478 // First, convert to the correct width so that we control the kind of
479 // extension.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000480 const llvm::Type *MiddleTy =
Owen Anderson0032b272009-08-13 21:57:51 +0000481 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Eli Friedman25615422009-03-04 04:02:35 +0000482 bool InputSigned = SrcType->isSignedIntegerType();
483 llvm::Value* IntResult =
484 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
485 // Then, cast to pointer.
486 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000487 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000488
Daniel Dunbar270cc662008-08-25 09:51:32 +0000489 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000490 // Must be an ptr to int cast.
491 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000492 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000493 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000494
Nate Begeman213541a2008-04-18 23:10:10 +0000495 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000496 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000497 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000498 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000499 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
500
501 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000502 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Owen Anderson0032b272009-08-13 21:57:51 +0000503 llvm::Value *Idx =
504 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000505 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
506
507 // Splat the element across to all elements
508 llvm::SmallVector<llvm::Constant*, 16> Args;
509 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
510 for (unsigned i = 0; i < NumElements; i++)
Owen Anderson0032b272009-08-13 21:57:51 +0000511 Args.push_back(llvm::ConstantInt::get(
512 llvm::Type::getInt32Ty(VMContext), 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000513
Owen Anderson4a289322009-07-28 21:22:35 +0000514 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000515 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
516 return Yay;
517 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000518
Chris Lattner3b1ae002008-02-02 04:51:41 +0000519 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000520 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000521 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000522 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000523
Chris Lattner3707b252007-08-26 06:48:56 +0000524 // Finally, we have the arithmetic types: real int/float.
525 if (isa<llvm::IntegerType>(Src->getType())) {
526 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000527 if (isa<llvm::IntegerType>(DstTy))
528 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
529 else if (InputSigned)
530 return Builder.CreateSIToFP(Src, DstTy, "conv");
531 else
532 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000533 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000534
Chris Lattner3707b252007-08-26 06:48:56 +0000535 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
536 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000537 if (DstType->isSignedIntegerType())
538 return Builder.CreateFPToSI(Src, DstTy, "conv");
539 else
540 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000541 }
542
543 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000544 if (DstTy->getTypeID() < Src->getType()->getTypeID())
545 return Builder.CreateFPTrunc(Src, DstTy, "conv");
546 else
547 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000548}
549
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000550/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
551/// type to the specified destination type, where the destination type is an
552/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000553Value *ScalarExprEmitter::
554EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
555 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000556 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000557 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000558
Chris Lattnered70f0a2007-08-26 16:52:28 +0000559 // Handle conversions to bool first, they are special: comparisons against 0.
560 if (DstTy->isBooleanType()) {
561 // Complex != 0 -> (Real != 0) | (Imag != 0)
562 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
563 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
564 return Builder.CreateOr(Src.first, Src.second, "tobool");
565 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000566
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000567 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
568 // the imaginary part of the complex value is discarded and the value of the
569 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000570 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000571 return EmitScalarConversion(Src.first, SrcTy, DstTy);
572}
573
574
Chris Lattner7f02f722007-08-24 05:35:26 +0000575//===----------------------------------------------------------------------===//
576// Visitor Methods
577//===----------------------------------------------------------------------===//
578
579Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000580 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000581 if (E->getType()->isVoidType())
582 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000583 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000584}
585
Eli Friedmand38617c2008-05-14 19:38:39 +0000586Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
587 llvm::SmallVector<llvm::Constant*, 32> indices;
588 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
589 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
590 }
591 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
592 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson4a289322009-07-28 21:22:35 +0000593 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000594 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
595}
596
Chris Lattner7f02f722007-08-24 05:35:26 +0000597Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000598 TestAndClearIgnoreResultAssign();
599
Chris Lattner7f02f722007-08-24 05:35:26 +0000600 // Emit subscript expressions in rvalue context's. For most cases, this just
601 // loads the lvalue formed by the subscript expr. However, we have to be
602 // careful, because the base of a vector subscript is occasionally an rvalue,
603 // so we can't get it as an lvalue.
604 if (!E->getBase()->getType()->isVectorType())
605 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000606
Chris Lattner7f02f722007-08-24 05:35:26 +0000607 // Handle the vector case. The base must be a vector, the index must be an
608 // integer value.
609 Value *Base = Visit(E->getBase());
610 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000611 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Owen Anderson0032b272009-08-13 21:57:51 +0000612 Idx = Builder.CreateIntCast(Idx,
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000613 llvm::Type::getInt32Ty(CGF.getLLVMContext()),
Owen Anderson0032b272009-08-13 21:57:51 +0000614 IdxSigned,
Eli Friedman515ff5a2009-03-28 03:27:06 +0000615 "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000616 return Builder.CreateExtractElement(Base, Idx, "vecext");
617}
618
Chris Lattner7f02f722007-08-24 05:35:26 +0000619// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
620// have to handle a more broad range of conversions than explicit casts, as they
621// handle things like function to ptr-to-function decay etc.
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000622Value *ScalarExprEmitter::EmitCastExpr(const CastExpr *CE) {
623 const Expr *E = CE->getSubExpr();
624 QualType DestTy = CE->getType();
625 CastExpr::CastKind Kind = CE->getCastKind();
626
Mike Stump7f79f9b2009-05-29 15:46:01 +0000627 if (!DestTy->isVoidType())
628 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000629
Anders Carlssone9776242009-08-24 18:26:39 +0000630 switch (Kind) {
631 default:
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000632 // FIXME: Assert here.
633 // assert(0 && "Unhandled cast kind!");
634 break;
635 case CastExpr::CK_Unknown:
636 // FIXME: We should really assert here - Unknown casts should never get
637 // as far as to codegen.
Anders Carlssone9776242009-08-24 18:26:39 +0000638 break;
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000639 case CastExpr::CK_BitCast: {
640 Value *Src = Visit(const_cast<Expr*>(E));
641 return Builder.CreateBitCast(Src, ConvertType(DestTy));
642 }
Anders Carlsson504bf552009-08-24 18:37:17 +0000643 case CastExpr::CK_ArrayToPointerDecay: {
644 assert(E->getType()->isArrayType() &&
645 "Array to pointer decay must have array source type!");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000646
Anders Carlsson504bf552009-08-24 18:37:17 +0000647 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
648
649 // Note that VLA pointers are always decayed, so we don't need to do
650 // anything here.
651 if (!E->getType()->isVariableArrayType()) {
652 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
653 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
654 ->getElementType()) &&
655 "Expected pointer to array");
656 V = Builder.CreateStructGEP(V, 0, "arraydecay");
657 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000658
Anders Carlsson504bf552009-08-24 18:37:17 +0000659 // The resultant pointer type can be implicitly casted to other pointer
660 // types as well (e.g. void*) and can be implicitly converted to integer.
661 const llvm::Type *DestLTy = ConvertType(DestTy);
662 if (V->getType() != DestLTy) {
663 if (isa<llvm::PointerType>(DestLTy))
664 V = Builder.CreateBitCast(V, DestLTy, "ptrconv");
665 else {
666 assert(isa<llvm::IntegerType>(DestLTy) && "Unknown array decay");
667 V = Builder.CreatePtrToInt(V, DestLTy, "ptrconv");
668 }
669 }
670 return V;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000671 }
Anders Carlssone9776242009-08-24 18:26:39 +0000672 case CastExpr::CK_NullToMemberPointer:
673 return CGF.CGM.EmitNullConstant(DestTy);
Anders Carlsson191dfe92009-09-12 04:57:16 +0000674
675 case CastExpr::CK_DerivedToBase: {
676 const RecordType *DerivedClassTy =
677 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
678 CXXRecordDecl *DerivedClassDecl =
679 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
680
681 const RecordType *BaseClassTy =
682 DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
683 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
684
685 Value *Src = Visit(const_cast<Expr*>(E));
Anders Carlsson32baf622009-09-12 06:04:24 +0000686
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000687 bool NullCheckValue = true;
Anders Carlsson32baf622009-09-12 06:04:24 +0000688
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000689 if (isa<CXXThisExpr>(E)) {
690 // We always assume that 'this' is never null.
Anders Carlsson32baf622009-09-12 06:04:24 +0000691 NullCheckValue = false;
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000692 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
693 // And that lvalue casts are never null.
694 if (ICE->isLvalueCast())
695 NullCheckValue = false;
696 }
Anders Carlsson191dfe92009-09-12 04:57:16 +0000697 return CGF.GetAddressCXXOfBaseClass(Src, DerivedClassDecl, BaseClassDecl,
Anders Carlsson32baf622009-09-12 06:04:24 +0000698 NullCheckValue);
Anders Carlsson191dfe92009-09-12 04:57:16 +0000699 }
700
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000701 case CastExpr::CK_IntegralToPointer: {
702 Value *Src = Visit(const_cast<Expr*>(E));
703 return Builder.CreateIntToPtr(Src, ConvertType(DestTy));
704 }
705
706 case CastExpr::CK_PointerToIntegral: {
707 Value *Src = Visit(const_cast<Expr*>(E));
708 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
709 }
710
Anders Carlssone9776242009-08-24 18:26:39 +0000711 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000712
Chris Lattner58a2e942007-08-26 07:26:12 +0000713 // Handle cases where the source is an non-complex type.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000714
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000715 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000716 Value *Src = Visit(const_cast<Expr*>(E));
717
Chris Lattner3707b252007-08-26 06:48:56 +0000718 // Use EmitScalarConversion to perform the conversion.
719 return EmitScalarConversion(Src, E->getType(), DestTy);
720 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000721
Chris Lattner9b2dc282008-04-04 16:54:41 +0000722 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000723 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000724 bool IgnoreImag = true;
725 bool IgnoreImagAssign = true;
726 bool IgnoreReal = IgnoreResultAssign;
727 bool IgnoreRealAssign = IgnoreResultAssign;
728 if (DestTy->isBooleanType())
729 IgnoreImagAssign = IgnoreImag = false;
730 else if (DestTy->isVoidType()) {
731 IgnoreReal = IgnoreImag = false;
732 IgnoreRealAssign = IgnoreImagAssign = true;
733 }
734 CodeGenFunction::ComplexPairTy V
735 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
736 IgnoreImagAssign);
737 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000738 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000739
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000740 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
741 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000742 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000743 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000744}
745
Chris Lattner33793202007-08-31 22:09:40 +0000746Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000747 return CGF.EmitCompoundStmt(*E->getSubStmt(),
748 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000749}
750
Mike Stumpa99038c2009-02-28 09:07:16 +0000751Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +0000752 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
753 if (E->getType().isObjCGCWeak())
754 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
755 return Builder.CreateLoad(V, false, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +0000756}
Chris Lattner33793202007-08-31 22:09:40 +0000757
Chris Lattner7f02f722007-08-24 05:35:26 +0000758//===----------------------------------------------------------------------===//
759// Unary Operators
760//===----------------------------------------------------------------------===//
761
762Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000763 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000764 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000765 QualType ValTy = E->getSubExpr()->getType();
766 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Owen Anderson0032b272009-08-13 21:57:51 +0000767
768 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000769
Chris Lattner7f02f722007-08-24 05:35:26 +0000770 int AmountVal = isInc ? 1 : -1;
Eli Friedmandaa24a22009-03-28 02:45:41 +0000771
772 if (ValTy->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000773 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000774 // The amount of the addition/subtraction needs to account for the VLA size
775 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
776 }
777
Chris Lattner7f02f722007-08-24 05:35:26 +0000778 Value *NextVal;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000779 if (const llvm::PointerType *PT =
Chris Lattner8cc9d082009-03-18 04:25:13 +0000780 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000781 llvm::Constant *Inc =
Owen Anderson0032b272009-08-13 21:57:51 +0000782 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000783 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000784 QualType PTEE = ValTy->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000785 if (const ObjCInterfaceType *OIT =
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000786 dyn_cast<ObjCInterfaceType>(PTEE)) {
787 // Handle interface types, which are not represented with a concrete type.
788 int size = CGF.getContext().getTypeSize(OIT) / 8;
789 if (!isInc)
790 size = -size;
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000791 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000792 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000793 InVal = Builder.CreateBitCast(InVal, i8Ty);
794 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
795 llvm::Value *lhs = LV.getAddress();
Owen Anderson96e0fc72009-07-29 22:16:19 +0000796 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
John McCall0953e762009-09-24 19:53:00 +0000797 LV = LValue::MakeAddr(lhs, CGF.MakeQualifiers(ValTy));
Mike Stumpb3589f42009-07-30 22:28:39 +0000798 } else
Dan Gohman664f8932009-08-12 00:33:55 +0000799 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
Chris Lattner8cc9d082009-03-18 04:25:13 +0000800 } else {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000801 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000802 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
803 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
804 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
805 }
Owen Anderson0032b272009-08-13 21:57:51 +0000806 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +0000807 // Bool++ is an interesting case, due to promotion rules, we get:
808 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
809 // Bool = ((int)Bool+1) != 0
810 // An interesting aspect of this is that increment is always true.
811 // Decrement does not have this property.
Owen Anderson3b144ba2009-07-31 17:39:36 +0000812 NextVal = llvm::ConstantInt::getTrue(VMContext);
Chris Lattner87415d22009-06-17 06:36:24 +0000813 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000814 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Dan Gohmanbf933a02009-08-12 01:16:29 +0000815
816 // Signed integer overflow is undefined behavior.
817 if (ValTy->isSignedIntegerType())
818 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
819 else
820 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000821 } else {
822 // Add the inc/dec to the real part.
Benjamin Kramerffbb15e2009-10-05 13:47:21 +0000823 if (InVal->getType()->isFloatTy())
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000824 NextVal =
825 llvm::ConstantFP::get(VMContext,
Owen Andersonbc0a2222009-07-27 21:00:51 +0000826 llvm::APFloat(static_cast<float>(AmountVal)));
Benjamin Kramerffbb15e2009-10-05 13:47:21 +0000827 else if (InVal->getType()->isDoubleTy())
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000828 NextVal =
Owen Andersonbc0a2222009-07-27 21:00:51 +0000829 llvm::ConstantFP::get(VMContext,
830 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000831 else {
832 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000833 bool ignored;
834 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
835 &ignored);
Owen Andersonbc0a2222009-07-27 21:00:51 +0000836 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000837 }
Chris Lattner87415d22009-06-17 06:36:24 +0000838 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000839 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000840
Chris Lattner7f02f722007-08-24 05:35:26 +0000841 // Store the updated result through the lvalue.
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000842 if (LV.isBitfield())
843 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
844 &NextVal);
845 else
846 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner7f02f722007-08-24 05:35:26 +0000847
848 // If this is a postinc, return the value read from memory, otherwise use the
849 // updated value.
850 return isPre ? NextVal : InVal;
851}
852
853
854Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000855 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000856 Value *Op = Visit(E->getSubExpr());
Chris Lattner87415d22009-06-17 06:36:24 +0000857 if (Op->getType()->isFPOrFPVector())
858 return Builder.CreateFNeg(Op, "neg");
Chris Lattner7f02f722007-08-24 05:35:26 +0000859 return Builder.CreateNeg(Op, "neg");
860}
861
862Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000863 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000864 Value *Op = Visit(E->getSubExpr());
865 return Builder.CreateNot(Op, "neg");
866}
867
868Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
869 // Compare operand to zero.
870 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000871
Chris Lattner7f02f722007-08-24 05:35:26 +0000872 // Invert value.
873 // TODO: Could dynamically modify easy computations here. For example, if
874 // the operand is an icmp ne, turn into icmp eq.
875 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000876
Anders Carlsson9f84d882009-05-19 18:44:53 +0000877 // ZExt result to the expr type.
878 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +0000879}
880
Sebastian Redl05189992008-11-11 17:56:53 +0000881/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
882/// argument of the sizeof expression as an integer.
883Value *
884ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +0000885 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000886 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000887 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000888 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
889 if (E->isArgumentType()) {
890 // sizeof(type) - make sure to emit the VLA size.
891 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +0000892 } else {
893 // C99 6.5.3.4p2: If the argument is an expression of type
894 // VLA, it is evaluated.
895 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000896 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000897
Anders Carlsson96f21472009-02-05 19:43:10 +0000898 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000899 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000900 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000901
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000902 // If this isn't sizeof(vla), the result must be constant; use the constant
903 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000904 Expr::EvalResult Result;
905 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000906 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +0000907}
908
Chris Lattner46f93d02007-08-24 21:20:17 +0000909Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
910 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000911 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000912 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +0000913 return Visit(Op);
914}
915Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
916 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000917 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000918 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000919
Mike Stump7f79f9b2009-05-29 15:46:01 +0000920 // __imag on a scalar returns zero. Emit the subexpr to ensure side
921 // effects are evaluated, but not the actual value.
922 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
923 CGF.EmitLValue(Op);
924 else
925 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000926 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000927}
928
Mike Stump1eb44332009-09-09 15:08:12 +0000929Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) {
Eli Friedman35183ac2009-02-27 06:44:11 +0000930 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +0000931 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +0000932 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000933}
Chris Lattner46f93d02007-08-24 21:20:17 +0000934
Chris Lattner7f02f722007-08-24 05:35:26 +0000935//===----------------------------------------------------------------------===//
936// Binary Operators
937//===----------------------------------------------------------------------===//
938
939BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000940 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000941 BinOpInfo Result;
942 Result.LHS = Visit(E->getLHS());
943 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000944 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000945 Result.E = E;
946 return Result;
947}
948
Chris Lattner3ccf7742007-08-26 21:41:21 +0000949Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000950 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000951 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000952 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
953
954 BinOpInfo OpInfo;
955
Eli Friedmanab3a8522009-03-28 01:22:36 +0000956 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000957 // This needs to go through the complex expression emitter, but it's a tad
958 // complicated to do that... I'm leaving it out for now. (Note that we do
959 // actually need the imaginary part of the RHS for multiplication and
960 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +0000961 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Anderson03e20502009-07-30 23:11:26 +0000962 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Eli Friedmanab3a8522009-03-28 01:22:36 +0000963 }
964
Mike Stumpcc0442f2009-05-22 19:07:20 +0000965 // Emit the RHS first. __block variables need to have the rhs evaluated
966 // first, plus this should improve codegen a little.
967 OpInfo.RHS = Visit(E->getRHS());
968 OpInfo.Ty = E->getComputationResultType();
969 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +0000970 // Load/convert the LHS.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000971 LValue LHSLV = EmitLValue(E->getLHS());
972 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000973 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
974 E->getComputationLHSType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000975
Chris Lattner1f1ded92007-08-24 21:00:35 +0000976 // Expand the binary operator.
977 Value *Result = (this->*Func)(OpInfo);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000978
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000979 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +0000980 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
981
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000982 // Store the result value into the LHS lvalue. Bit-fields are handled
983 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
984 // 'An assignment expression has the value of the left operand after the
985 // assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000986 if (LHSLV.isBitfield()) {
987 if (!LHSLV.isVolatileQualified()) {
988 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
989 &Result);
990 return Result;
991 } else
992 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
993 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +0000994 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stump7f79f9b2009-05-29 15:46:01 +0000995 if (Ignore)
996 return 0;
997 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000998}
999
1000
Chris Lattner7f02f722007-08-24 05:35:26 +00001001Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +00001002 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +00001003 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +00001004 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001005 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1006 else
1007 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1008}
1009
1010Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1011 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +00001012 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001013 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1014 else
1015 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1016}
1017
Mike Stump2add4732009-04-01 20:28:16 +00001018Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1019 unsigned IID;
1020 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001021
Mike Stump035cf892009-04-02 18:15:54 +00001022 switch (Ops.E->getOpcode()) {
1023 case BinaryOperator::Add:
1024 case BinaryOperator::AddAssign:
1025 OpID = 1;
1026 IID = llvm::Intrinsic::sadd_with_overflow;
1027 break;
1028 case BinaryOperator::Sub:
1029 case BinaryOperator::SubAssign:
1030 OpID = 2;
1031 IID = llvm::Intrinsic::ssub_with_overflow;
1032 break;
1033 case BinaryOperator::Mul:
1034 case BinaryOperator::MulAssign:
1035 OpID = 3;
1036 IID = llvm::Intrinsic::smul_with_overflow;
1037 break;
1038 default:
1039 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001040 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001041 }
Mike Stump035cf892009-04-02 18:15:54 +00001042 OpID <<= 1;
1043 OpID |= 1;
1044
Mike Stump2add4732009-04-01 20:28:16 +00001045 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1046
1047 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1048
1049 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1050 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1051 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1052
1053 // Branch in case of overflow.
1054 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1055 llvm::BasicBlock *overflowBB =
1056 CGF.createBasicBlock("overflow", CGF.CurFn);
1057 llvm::BasicBlock *continueBB =
1058 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1059
1060 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1061
1062 // Handle overflow
1063
1064 Builder.SetInsertPoint(overflowBB);
1065
1066 // Handler is:
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001067 // long long *__overflow_handler)(long long a, long long b, char op,
Mike Stump2add4732009-04-01 20:28:16 +00001068 // char width)
1069 std::vector<const llvm::Type*> handerArgTypes;
Owen Anderson0032b272009-08-13 21:57:51 +00001070 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1071 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1072 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1073 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1074 llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1075 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
Mike Stump2add4732009-04-01 20:28:16 +00001076 llvm::Value *handlerFunction =
1077 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson96e0fc72009-07-29 22:16:19 +00001078 llvm::PointerType::getUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +00001079 handlerFunction = Builder.CreateLoad(handlerFunction);
1080
1081 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
Owen Anderson0032b272009-08-13 21:57:51 +00001082 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1083 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1084 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001085 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
Mike Stump2add4732009-04-01 20:28:16 +00001086 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1087
1088 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1089
1090 Builder.CreateBr(continueBB);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001091
Mike Stump2add4732009-04-01 20:28:16 +00001092 // Set up the continuation
1093 Builder.SetInsertPoint(continueBB);
1094 // Get the correct result
1095 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1096 phi->reserveOperandSpace(2);
1097 phi->addIncoming(result, initialBB);
1098 phi->addIncoming(handlerResult, overflowBB);
1099
1100 return phi;
1101}
Chris Lattner7f02f722007-08-24 05:35:26 +00001102
1103Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001104 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner87415d22009-06-17 06:36:24 +00001105 if (CGF.getContext().getLangOptions().OverflowChecking &&
1106 Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001107 return EmitOverflowCheckedBinOp(Ops);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001108
Chris Lattner87415d22009-06-17 06:36:24 +00001109 if (Ops.LHS->getType()->isFPOrFPVector())
1110 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001111
1112 // Signed integer overflow is undefined behavior.
1113 if (Ops.Ty->isSignedIntegerType())
1114 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1115
Chris Lattner7f02f722007-08-24 05:35:26 +00001116 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001117 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001118
Steve Naroff14108da2009-07-10 23:34:53 +00001119 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001120 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001121 // The amount of the addition needs to account for the VLA size
1122 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1123 }
Chris Lattner8f925282008-01-03 06:36:51 +00001124 Value *Ptr, *Idx;
1125 Expr *IdxExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001126 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001127 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00001128 Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001129 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001130 Ptr = Ops.LHS;
1131 Idx = Ops.RHS;
1132 IdxExp = Ops.E->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001133 } else { // int + pointer
Ted Kremenek6217b802009-07-29 21:53:49 +00001134 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
John McCall183700f2009-09-21 23:43:11 +00001135 OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001136 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001137 Ptr = Ops.RHS;
1138 Idx = Ops.LHS;
1139 IdxExp = Ops.E->getLHS();
1140 }
1141
1142 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001143 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001144 // Zero or sign extend the pointer value based on whether the index is
1145 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001146 const llvm::Type *IdxType =
1147 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +00001148 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001149 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1150 else
1151 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1152 }
Steve Naroff14108da2009-07-10 23:34:53 +00001153 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001154 // Handle interface types, which are not represented with a concrete type.
Daniel Dunbar2a866252009-04-25 05:08:32 +00001155 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001156 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001157 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001158 CGF.getContext().getTypeSize(OIT) / 8);
1159 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001160 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001161 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1162 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1163 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001164 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001165
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001166 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1167 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1168 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001169 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001170 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001171 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001172 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001173 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001174 }
1175
Dan Gohman664f8932009-08-12 00:33:55 +00001176 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001177}
1178
1179Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001180 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stump035cf892009-04-02 18:15:54 +00001181 if (CGF.getContext().getLangOptions().OverflowChecking
1182 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001183 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001184
1185 if (Ops.LHS->getType()->isFPOrFPVector())
1186 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner7f02f722007-08-24 05:35:26 +00001187 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001188 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001189
Steve Naroff14108da2009-07-10 23:34:53 +00001190 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001191 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001192 // The amount of the addition needs to account for the VLA size for
1193 // ptr-int
1194 // The amount of the division needs to account for the VLA size for
1195 // ptr-ptr.
1196 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1197 }
1198
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001199 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001200 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001201 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1202 // pointer - int
1203 Value *Idx = Ops.RHS;
1204 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001205 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001206 // Zero or sign extend the pointer value based on whether the index is
1207 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001208 const llvm::Type *IdxType =
1209 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001210 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1211 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1212 else
1213 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1214 }
1215 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001216
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001217 // Handle interface types, which are not represented with a concrete type.
1218 if (const ObjCInterfaceType *OIT =
Daniel Dunbar2a866252009-04-25 05:08:32 +00001219 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001220 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001221 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001222 CGF.getContext().getTypeSize(OIT) / 8);
1223 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001224 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001225 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1226 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1227 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001228 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001229
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001230 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001231 // extensions. The GNU void* casts amount to no-ops since our void* type is
1232 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001233 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001234 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001235 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1236 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1237 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001238 }
1239
Dan Gohman664f8932009-08-12 00:33:55 +00001240 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001241 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001242 // pointer - pointer
1243 Value *LHS = Ops.LHS;
1244 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001245
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001246 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001247
Chris Lattnere5ed1512009-02-11 07:21:43 +00001248 // Handle GCC extension for pointer arithmetic on void* and function pointer
1249 // types.
1250 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001251 ElementSize = 1;
1252 } else {
1253 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1254 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001255
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001256 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1257 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1258 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1259 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001260
Chris Lattnere5ed1512009-02-11 07:21:43 +00001261 // Optimize out the shift for element size of 1.
1262 if (ElementSize == 1)
1263 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001264
1265 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001266 // pointer difference in C is only defined in the case where both operands
1267 // are pointing to elements of an array.
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001268 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Dan Gohmandf110942009-08-11 22:40:09 +00001269 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001270 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001271}
1272
1273Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1274 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1275 // RHS to the same size as the LHS.
1276 Value *RHS = Ops.RHS;
1277 if (Ops.LHS->getType() != RHS->getType())
1278 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001279
Chris Lattner7f02f722007-08-24 05:35:26 +00001280 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1281}
1282
1283Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1284 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1285 // RHS to the same size as the LHS.
1286 Value *RHS = Ops.RHS;
1287 if (Ops.LHS->getType() != RHS->getType())
1288 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001289
Chris Lattner1f1ded92007-08-24 21:00:35 +00001290 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001291 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1292 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1293}
1294
1295Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1296 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001297 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001298 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001299 QualType LHSTy = E->getLHS()->getType();
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001300 if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001301 Value *LHS = Visit(E->getLHS());
1302 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001303
Eli Friedman1360d4a2009-07-22 06:07:16 +00001304 if (LHS->getType()->isFPOrFPVector()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001305 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001306 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001307 } else if (LHSTy->isSignedIntegerType()) {
1308 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001309 LHS, RHS, "cmp");
1310 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001311 // Unsigned integers and pointers.
1312 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001313 LHS, RHS, "cmp");
1314 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001315
1316 // If this is a vector comparison, sign extend the result to the appropriate
1317 // vector integer type and return it (don't convert to bool).
1318 if (LHSTy->isVectorType())
1319 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001320
Chris Lattner7f02f722007-08-24 05:35:26 +00001321 } else {
1322 // Complex Comparison: can only be an equality comparison.
1323 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1324 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001325
John McCall183700f2009-09-21 23:43:11 +00001326 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001327
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001328 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001329 if (CETy->isRealFloatingType()) {
1330 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1331 LHS.first, RHS.first, "cmp.r");
1332 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1333 LHS.second, RHS.second, "cmp.i");
1334 } else {
1335 // Complex comparisons can only be equality comparisons. As such, signed
1336 // and unsigned opcodes are the same.
1337 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1338 LHS.first, RHS.first, "cmp.r");
1339 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1340 LHS.second, RHS.second, "cmp.i");
1341 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001342
Chris Lattner7f02f722007-08-24 05:35:26 +00001343 if (E->getOpcode() == BinaryOperator::EQ) {
1344 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1345 } else {
1346 assert(E->getOpcode() == BinaryOperator::NE &&
1347 "Complex comparison other than == or != ?");
1348 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1349 }
1350 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001351
1352 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001353}
1354
1355Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001356 bool Ignore = TestAndClearIgnoreResultAssign();
1357
1358 // __block variables need to have the rhs evaluated first, plus this should
1359 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001360 Value *RHS = Visit(E->getRHS());
Mike Stump99459b62009-05-21 21:05:15 +00001361 LValue LHS = EmitLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001362
Daniel Dunbared3849b2008-11-19 09:36:46 +00001363 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001364 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1365 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001366 // the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001367 if (LHS.isBitfield()) {
1368 if (!LHS.isVolatileQualified()) {
1369 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1370 &RHS);
1371 return RHS;
1372 } else
1373 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1374 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001375 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stump7f79f9b2009-05-29 15:46:01 +00001376 if (Ignore)
1377 return 0;
1378 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001379}
1380
1381Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001382 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1383 // If we have 1 && X, just emit X without inserting the control flow.
1384 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1385 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001386 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1387 // ZExt result to int.
1388 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1389 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001390
Chris Lattner20eb09d2008-11-12 08:26:50 +00001391 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1392 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonc9c88b42009-07-31 20:28:54 +00001393 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001394 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001395
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001396 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1397 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001398
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001399 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1400 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1401
1402 // Any edges into the ContBlock are now from an (indeterminate number of)
1403 // edges from this first condition. All of these values will be false. Start
1404 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001405 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1406 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001407 PN->reserveOperandSpace(2); // Normal case, two inputs.
1408 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1409 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001410 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001411
Anders Carlsson33da07d2009-06-04 02:53:13 +00001412 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001413 CGF.EmitBlock(RHSBlock);
1414 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson33da07d2009-06-04 02:53:13 +00001415 CGF.PopConditionalTempDestruction();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001416
Chris Lattner7f02f722007-08-24 05:35:26 +00001417 // Reaquire the RHS block, as there may be subblocks inserted.
1418 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001419
1420 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1421 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001422 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001423 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001424
Chris Lattner7f02f722007-08-24 05:35:26 +00001425 // ZExt result to int.
1426 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1427}
1428
1429Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001430 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1431 // If we have 0 || X, just emit X without inserting the control flow.
1432 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1433 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001434 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1435 // ZExt result to int.
1436 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1437 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001438
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001439 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001440 if (!CGF.ContainsLabel(E->getRHS()))
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001441 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001442 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001443
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001444 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1445 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001446
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001447 // Branch on the LHS first. If it is true, go to the success (cont) block.
1448 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1449
1450 // Any edges into the ContBlock are now from an (indeterminate number of)
1451 // edges from this first condition. All of these values will be true. Start
1452 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001453 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1454 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001455 PN->reserveOperandSpace(2); // Normal case, two inputs.
1456 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1457 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001458 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001459
Anders Carlsson33da07d2009-06-04 02:53:13 +00001460 CGF.PushConditionalTempDestruction();
1461
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001462 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001463 CGF.EmitBlock(RHSBlock);
1464 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001465
Anders Carlsson33da07d2009-06-04 02:53:13 +00001466 CGF.PopConditionalTempDestruction();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001467
Chris Lattner7f02f722007-08-24 05:35:26 +00001468 // Reaquire the RHS block, as there may be subblocks inserted.
1469 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001470
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001471 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1472 // into the phi node for the edge with the value of RHSCond.
1473 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001474 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001475
Chris Lattner7f02f722007-08-24 05:35:26 +00001476 // ZExt result to int.
1477 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1478}
1479
1480Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1481 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001482 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001483 return Visit(E->getRHS());
1484}
1485
1486//===----------------------------------------------------------------------===//
1487// Other Operators
1488//===----------------------------------------------------------------------===//
1489
Chris Lattner9802a512008-11-12 08:55:54 +00001490/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1491/// expression is cheap enough and side-effect-free enough to evaluate
1492/// unconditionally instead of conditionally. This is used to convert control
1493/// flow into selects in some cases.
1494static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1495 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1496 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001497
Chris Lattner9802a512008-11-12 08:55:54 +00001498 // TODO: Allow anything we can constant fold to an integer or fp constant.
1499 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1500 isa<FloatingLiteral>(E))
1501 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001502
Chris Lattner9802a512008-11-12 08:55:54 +00001503 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1504 // X and Y are local variables.
1505 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1506 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1507 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1508 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001509
Chris Lattner9802a512008-11-12 08:55:54 +00001510 return false;
1511}
1512
1513
Chris Lattner7f02f722007-08-24 05:35:26 +00001514Value *ScalarExprEmitter::
1515VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001516 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00001517 // If the condition constant folds and can be elided, try to avoid emitting
1518 // the condition and the dead arm.
1519 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001520 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001521 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001522 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001523
Chris Lattner31a09842008-11-12 08:04:58 +00001524 // If the dead side doesn't have labels we need, and if the Live side isn't
1525 // the gnu missing ?: extension (which we could handle, but don't bother
1526 // to), just emit the Live part.
1527 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1528 Live) // Live part isn't missing.
1529 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001530 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001531
1532
Chris Lattner9802a512008-11-12 08:55:54 +00001533 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1534 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001535 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001536 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1537 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1538 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1539 llvm::Value *LHS = Visit(E->getLHS());
1540 llvm::Value *RHS = Visit(E->getRHS());
1541 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1542 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001543
1544
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001545 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1546 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001547 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001548 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001549
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001550 // If we don't have the GNU missing condition extension, emit a branch on bool
1551 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00001552 if (E->getLHS()) {
1553 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1554 // the branch on bool.
1555 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1556 } else {
1557 // Otherwise, for the ?: extension, evaluate the conditional and then
1558 // convert it to bool the hard way. We do this explicitly because we need
1559 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001560 CondVal = CGF.EmitScalarExpr(E->getCond());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001561
Chris Lattner12d152f2009-02-13 23:35:32 +00001562 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1563 // if there are no extra uses (an optimization). Inhibit this by making an
1564 // extra dead use, because we're going to add a use of CondVal later. We
1565 // don't use the builder for this, because we don't want it to get optimized
1566 // away. This leaves dead code, but the ?: extension isn't common.
1567 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1568 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001569
Chris Lattner035cf422008-11-12 08:08:13 +00001570 Value *CondBoolVal =
1571 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1572 CGF.getContext().BoolTy);
1573 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001574 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001575
1576 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001577 CGF.EmitBlock(LHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001578
Chris Lattner7f02f722007-08-24 05:35:26 +00001579 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001580 Value *LHS;
1581 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001582 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001583 else // Perform promotions, to handle cases like "short ?: int"
1584 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001585
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001586 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001587 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001588 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001589
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001590 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001591 CGF.EmitBlock(RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001592
Eli Friedman856226c2008-05-16 20:38:39 +00001593 Value *RHS = Visit(E->getRHS());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001594 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001595 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001596 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001597
Chris Lattner7f02f722007-08-24 05:35:26 +00001598 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001599
Nuno Lopes108f55d2008-06-04 19:15:45 +00001600 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001601 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1602 return 0;
1603 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001604
Chris Lattner7f02f722007-08-24 05:35:26 +00001605 // Create a PHI node for the real part.
1606 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1607 PN->reserveOperandSpace(2);
1608 PN->addIncoming(LHS, LHSBlock);
1609 PN->addIncoming(RHS, RHSBlock);
1610 return PN;
1611}
1612
1613Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001614 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001615}
1616
Chris Lattner2202bce2007-11-30 17:56:23 +00001617Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001618 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001619 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1620
1621 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001622 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001623 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1624
Mike Stump7f79f9b2009-05-29 15:46:01 +00001625 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001626 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001627}
1628
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001629Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001630 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001631}
1632
Chris Lattner7f02f722007-08-24 05:35:26 +00001633//===----------------------------------------------------------------------===//
1634// Entry Point into this File
1635//===----------------------------------------------------------------------===//
1636
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001637/// EmitScalarExpr - Emit the computation of the specified expression of scalar
1638/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001639Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001640 assert(E && !hasAggregateLLVMType(E->getType()) &&
1641 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001642
Mike Stump7f79f9b2009-05-29 15:46:01 +00001643 return ScalarExprEmitter(*this, IgnoreResultAssign)
1644 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00001645}
Chris Lattner3707b252007-08-26 06:48:56 +00001646
1647/// EmitScalarConversion - Emit a conversion from the specified type to the
1648/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001649Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1650 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001651 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1652 "Invalid scalar expression to emit");
1653 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1654}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001655
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001656/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
1657/// type to the specified destination type, where the destination type is an
1658/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001659Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1660 QualType SrcTy,
1661 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001662 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001663 "Invalid complex -> scalar conversion");
1664 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1665 DstTy);
1666}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001667
1668Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1669 assert(V1->getType() == V2->getType() &&
1670 "Vector operands must be of the same type");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001671 unsigned NumElements =
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001672 cast<llvm::VectorType>(V1->getType())->getNumElements();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001673
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001674 va_list va;
1675 va_start(va, V2);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001676
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001677 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001678 for (unsigned i = 0; i < NumElements; i++) {
1679 int n = va_arg(va, int);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001680 assert(n >= 0 && n < (int)NumElements * 2 &&
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001681 "Vector shuffle index out of bounds!");
Owen Anderson0032b272009-08-13 21:57:51 +00001682 Args.push_back(llvm::ConstantInt::get(
1683 llvm::Type::getInt32Ty(VMContext), n));
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001684 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001685
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001686 const char *Name = va_arg(va, const char *);
1687 va_end(va);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001688
Owen Anderson4a289322009-07-28 21:22:35 +00001689 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001690
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001691 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1692}
1693
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001694llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001695 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001696 llvm::Value *Vec
Owen Anderson03e20502009-07-30 23:11:26 +00001697 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001698
Chris Lattner345f7202008-07-26 20:15:14 +00001699 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001700 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Anderson0032b272009-08-13 21:57:51 +00001701 llvm::Value *Idx = llvm::ConstantInt::get(
1702 llvm::Type::getInt32Ty(VMContext), i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001703 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001704 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001705
1706 return Vec;
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001707}