blob: ee7b47ee27732aec7194a58913b3acebb34727d4 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chris Lattnerb6984c42007-06-20 04:44:43 +000015#include "CodeGenModule.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000016#include "clang/AST/AST.h"
Anders Carlsson1d8e5212007-08-20 18:05:56 +000017#include "clang/Lex/IdentifierTable.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
Chris Lattner4347e3692007-06-06 04:54:52 +000020#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
Chris Lattner651f0e92007-07-16 05:43:05 +000022#include "llvm/Support/MathExtras.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000023using namespace clang;
24using namespace CodeGen;
25
Chris Lattnerd7f58862007-06-02 05:24:33 +000026//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000027// Miscellaneous Helper Methods
28//===--------------------------------------------------------------------===//
29
Chris Lattnere9a64532007-06-22 21:44:33 +000030/// CreateTempAlloca - This creates a alloca and inserts it into the entry
31/// block.
32llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
33 const char *Name) {
34 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35}
Chris Lattner8394d792007-06-05 20:53:16 +000036
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000039llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +000040 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +000041}
42
43//===--------------------------------------------------------------------===//
44// Conversions
45//===--------------------------------------------------------------------===//
46
47/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
48/// the type specified by DstTy, following the rules of C99 6.3.
49RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
Chris Lattnerf033c142007-06-22 19:05:19 +000050 QualType DstTy) {
Chris Lattner8394d792007-06-05 20:53:16 +000051 ValTy = ValTy.getCanonicalType();
52 DstTy = DstTy.getCanonicalType();
53 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000054
55 // Handle conversions to bool first, they are special: comparisons against 0.
56 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
57 if (DestBT->getKind() == BuiltinType::Bool)
58 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
Chris Lattner8394d792007-06-05 20:53:16 +000059
Chris Lattner83b484b2007-06-06 04:39:08 +000060 // Handle pointer conversions next: pointers can only be converted to/from
61 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000062 if (isa<PointerType>(DstTy)) {
Chris Lattnerf033c142007-06-22 19:05:19 +000063 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000064
Chris Lattner02697702007-08-10 16:33:59 +000065 if (Val.getVal()->getType() == DestTy)
66 return Val;
67
Chris Lattnercf106ab2007-06-06 04:05:39 +000068 // The source value may be an integer, or a pointer.
69 assert(Val.isScalar() && "Can only convert from integer or pointer");
70 if (isa<llvm::PointerType>(Val.getVal()->getType()))
71 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
72 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Chris Lattnerfc7634f2007-07-13 03:25:53 +000073 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +000074 }
75
76 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +000077 // Must be an ptr to int cast.
Chris Lattnerf033c142007-06-22 19:05:19 +000078 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000079 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
80 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +000081 }
Chris Lattner83b484b2007-06-06 04:39:08 +000082
83 // Finally, we have the arithmetic types: real int/float and complex
84 // int/float. Handle real->real conversions first, they are the most
85 // common.
86 if (Val.isScalar() && DstTy->isRealType()) {
87 // We know that these are representable as scalars in LLVM, convert to LLVM
88 // types since they are easier to reason about.
Chris Lattner23b7eb62007-06-15 23:05:46 +000089 llvm::Value *SrcVal = Val.getVal();
Chris Lattnerf033c142007-06-22 19:05:19 +000090 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattner83b484b2007-06-06 04:39:08 +000091 if (SrcVal->getType() == DestTy) return Val;
92
Chris Lattner23b7eb62007-06-15 23:05:46 +000093 llvm::Value *Result;
Chris Lattner83b484b2007-06-06 04:39:08 +000094 if (isa<llvm::IntegerType>(SrcVal->getType())) {
95 bool InputSigned = ValTy->isSignedIntegerType();
96 if (isa<llvm::IntegerType>(DestTy))
97 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
98 else if (InputSigned)
99 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
100 else
101 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
102 } else {
103 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
104 if (isa<llvm::IntegerType>(DestTy)) {
105 if (DstTy->isSignedIntegerType())
106 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
107 else
108 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
109 } else {
110 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
111 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
112 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
113 else
114 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
115 }
116 }
117 return RValue::get(Result);
118 }
119
120 assert(0 && "FIXME: We don't support complex conversions yet!");
Chris Lattner8394d792007-06-05 20:53:16 +0000121}
122
123
124/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000125/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner23b7eb62007-06-15 23:05:46 +0000126llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
Chris Lattnerf0106d22007-06-02 19:33:17 +0000127 Ty = Ty.getCanonicalType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000128 llvm::Value *Result;
Chris Lattnerf0106d22007-06-02 19:33:17 +0000129 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
130 switch (BT->getKind()) {
131 default: assert(0 && "Unknown scalar value");
132 case BuiltinType::Bool:
133 Result = Val.getVal();
134 // Bool is already evaluated right.
135 assert(Result->getType() == llvm::Type::Int1Ty &&
136 "Unexpected bool value type!");
137 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000138 case BuiltinType::Char_S:
139 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000140 case BuiltinType::SChar:
141 case BuiltinType::UChar:
142 case BuiltinType::Short:
143 case BuiltinType::UShort:
144 case BuiltinType::Int:
145 case BuiltinType::UInt:
146 case BuiltinType::Long:
147 case BuiltinType::ULong:
148 case BuiltinType::LongLong:
149 case BuiltinType::ULongLong:
150 // Code below handles simple integers.
151 break;
152 case BuiltinType::Float:
153 case BuiltinType::Double:
154 case BuiltinType::LongDouble: {
155 // Compare against 0.0 for fp scalars.
156 Result = Val.getVal();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000157 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000158 // FIXME: llvm-gcc produces a une comparison: validate this is right.
159 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
160 return Result;
161 }
Chris Lattnerf0106d22007-06-02 19:33:17 +0000162 }
Chris Lattnerc6395932007-06-22 20:56:16 +0000163 } else if (isa<PointerType>(Ty) ||
164 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000165 // Code below handles this fine.
Chris Lattnerc6395932007-06-22 20:56:16 +0000166 } else {
167 assert(isa<ComplexType>(Ty) && "Unknwon type!");
168 assert(0 && "FIXME: comparisons against complex not implemented yet");
Chris Lattnerf0106d22007-06-02 19:33:17 +0000169 }
170
171 // Usual case for integers, pointers, and enums: compare against zero.
172 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000173
174 // Because of the type rules of C, we often end up computing a logical value,
175 // then zero extending it to int, then wanting it as a logical value again.
176 // Optimize this common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000177 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
Chris Lattnera45c5af2007-06-02 19:47:04 +0000178 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
179 Result = ZI->getOperand(0);
180 ZI->eraseFromParent();
181 return Result;
182 }
183 }
184
Chris Lattner23b7eb62007-06-15 23:05:46 +0000185 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000186 return Builder.CreateICmpNE(Result, Zero, "tobool");
187}
188
Chris Lattnera45c5af2007-06-02 19:47:04 +0000189//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000190// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000191//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000192
Chris Lattner8394d792007-06-05 20:53:16 +0000193/// EmitLValue - Emit code to compute a designator that specifies the location
194/// of the expression.
195///
196/// This can return one of two things: a simple address or a bitfield
197/// reference. In either case, the LLVM Value* in the LValue structure is
198/// guaranteed to be an LLVM pointer type.
199///
200/// If this returns a bitfield reference, nothing about the pointee type of
201/// the LLVM value is known: For example, it may not be a pointer to an
202/// integer.
203///
204/// If this returns a normal address, and if the lvalue's C type is fixed
205/// size, this method guarantees that the returned pointer type will point to
206/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
207/// variable length type, this is not possible.
208///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000209LValue CodeGenFunction::EmitLValue(const Expr *E) {
210 switch (E->getStmtClass()) {
211 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000212 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000213 E->dump();
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000214 return LValue::MakeAddr(llvm::UndefValue::get(
Chris Lattnerd7f58862007-06-02 05:24:33 +0000215 llvm::PointerType::get(llvm::Type::Int32Ty)));
216
217 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000218 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson625bfc82007-07-21 05:21:51 +0000219 case Expr::PreDefinedExprClass:
220 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000221 case Expr::StringLiteralClass:
222 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000223
224 case Expr::UnaryOperatorClass:
225 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000226 case Expr::ArraySubscriptExprClass:
227 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000228 case Expr::OCUVectorElementExprClass:
229 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000230 }
231}
232
Chris Lattner8394d792007-06-05 20:53:16 +0000233/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
234/// this method emits the address of the lvalue, then loads the result as an
235/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000236RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000237 if (LV.isSimple()) {
238 llvm::Value *Ptr = LV.getAddress();
239 const llvm::Type *EltTy =
240 cast<llvm::PointerType>(Ptr->getType())->getElementType();
241
242 // Simple scalar l-value.
243 if (EltTy->isFirstClassType())
244 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
245
Chris Lattner6278e6a2007-08-11 00:04:45 +0000246 assert(ExprType->isFunctionType() && "Unknown scalar value");
247 return RValue::get(Ptr);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000248 }
Chris Lattner09153c02007-06-22 18:48:09 +0000249
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000250 if (LV.isVectorElt()) {
251 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
252 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
253 "vecext"));
254 }
Chris Lattner73ab9b32007-08-03 00:16:29 +0000255
256 // If this is a reference to a subset of the elements of a vector, either
257 // shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000258 if (LV.isOCUVectorElt())
259 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner09153c02007-06-22 18:48:09 +0000260
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000261 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000262}
263
Chris Lattner40ff7012007-08-03 16:18:34 +0000264// If this is a reference to a subset of the elements of a vector, either
265// shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000266RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000267 QualType ExprType) {
Chris Lattner40ff7012007-08-03 16:18:34 +0000268 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
269
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000270 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner40ff7012007-08-03 16:18:34 +0000271
272 // If the result of the expression is a non-vector type, we must be
273 // extracting a single element. Just codegen as an extractelement.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000274 const VectorType *ExprVT = ExprType->getAsVectorType();
275 if (!ExprVT) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000276 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000277 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
278 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
279 }
280
281 // If the source and destination have the same number of elements, use a
282 // vector shuffle instead of insert/extracts.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000283 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner40ff7012007-08-03 16:18:34 +0000284 unsigned NumSourceElts =
285 cast<llvm::VectorType>(Vec->getType())->getNumElements();
286
287 if (NumResultElts == NumSourceElts) {
288 llvm::SmallVector<llvm::Constant*, 4> Mask;
289 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000290 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000291 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
292 }
293
294 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
295 Vec = Builder.CreateShuffleVector(Vec,
296 llvm::UndefValue::get(Vec->getType()),
297 MaskV, "tmp");
298 return RValue::get(Vec);
299 }
300
301 // Start out with an undef of the result type.
302 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
303
304 // Extract/Insert each element of the result.
305 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000306 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000307 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
308 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
309
310 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
311 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
312 }
313
314 return RValue::get(Result);
315}
316
317
Chris Lattner9369a562007-06-29 16:31:29 +0000318RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
319 return EmitLoadOfLValue(EmitLValue(E), E->getType());
320}
321
322
Chris Lattner8394d792007-06-05 20:53:16 +0000323/// EmitStoreThroughLValue - Store the specified rvalue into the specified
324/// lvalue, where both are guaranteed to the have the same type, and that type
325/// is 'Ty'.
326void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
327 QualType Ty) {
Chris Lattner41d480e2007-08-03 16:28:33 +0000328 if (!Dst.isSimple()) {
329 if (Dst.isVectorElt()) {
330 // Read/modify/write the vector, inserting the new element.
331 // FIXME: Volatility.
332 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
333 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
334 Dst.getVectorIdx(), "vecins");
335 Builder.CreateStore(Vec, Dst.getVectorAddr());
336 return;
337 }
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000338
Chris Lattner41d480e2007-08-03 16:28:33 +0000339 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000340 if (Dst.isOCUVectorElt())
Chris Lattner41d480e2007-08-03 16:28:33 +0000341 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
342
343 assert(0 && "FIXME: Don't support store to bitfield yet");
344 }
Chris Lattner8394d792007-06-05 20:53:16 +0000345
Chris Lattner09153c02007-06-22 18:48:09 +0000346 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000347 assert(Src.isScalar() && "Can't emit an agg store with this method");
348 // FIXME: Handle volatility etc.
349 const llvm::Type *SrcTy = Src.getVal()->getType();
350 const llvm::Type *AddrTy =
351 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner8394d792007-06-05 20:53:16 +0000352
Chris Lattner6278e6a2007-08-11 00:04:45 +0000353 if (AddrTy != SrcTy)
354 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
355 "storetmp");
356 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner8394d792007-06-05 20:53:16 +0000357}
358
Chris Lattner41d480e2007-08-03 16:28:33 +0000359void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
360 QualType Ty) {
361 // This access turns into a read/modify/write of the vector. Load the input
362 // value now.
363 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
364 // FIXME: Volatility.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000365 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner41d480e2007-08-03 16:28:33 +0000366
367 llvm::Value *SrcVal = Src.getVal();
368
Chris Lattner3a44aa72007-08-03 16:37:04 +0000369 if (const VectorType *VTy = Ty->getAsVectorType()) {
370 unsigned NumSrcElts = VTy->getNumElements();
371
372 // Extract/Insert each element.
373 for (unsigned i = 0; i != NumSrcElts; ++i) {
374 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
375 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
376
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000377 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner3a44aa72007-08-03 16:37:04 +0000378 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
379 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
380 }
381 } else {
382 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000383 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner41d480e2007-08-03 16:28:33 +0000384 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
385 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner41d480e2007-08-03 16:28:33 +0000386 }
387
Chris Lattner41d480e2007-08-03 16:28:33 +0000388 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
389}
390
Chris Lattnerd7f58862007-06-02 05:24:33 +0000391
392LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
393 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000394 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000395 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000396 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000397 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000398 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000399 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000400 }
401 assert(0 && "Unimp declref");
402}
Chris Lattnere47e4402007-06-01 18:02:12 +0000403
Chris Lattner8394d792007-06-05 20:53:16 +0000404LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
405 // __extension__ doesn't affect lvalue-ness.
406 if (E->getOpcode() == UnaryOperator::Extension)
407 return EmitLValue(E->getSubExpr());
408
409 assert(E->getOpcode() == UnaryOperator::Deref &&
410 "'*' is the only unary operator that produces an lvalue");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000411 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
Chris Lattner8394d792007-06-05 20:53:16 +0000412}
413
Chris Lattner4347e3692007-06-06 04:54:52 +0000414LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
415 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
416 const char *StrData = E->getStrData();
417 unsigned Len = E->getByteLength();
418
419 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000420 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000421
422 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000423 C = new llvm::GlobalVariable(C->getType(), true,
424 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000425 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000426 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
427 llvm::Constant *Zeros[] = { Zero, Zero };
428 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000429 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000430}
431
Anders Carlsson625bfc82007-07-21 05:21:51 +0000432LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
433 std::string FunctionName(CurFuncDecl->getName());
434 std::string GlobalVarName;
435
436 switch (E->getIdentType()) {
437 default:
438 assert(0 && "unknown pre-defined ident type");
439 case PreDefinedExpr::Func:
440 GlobalVarName = "__func__.";
441 break;
442 case PreDefinedExpr::Function:
443 GlobalVarName = "__FUNCTION__.";
444 break;
445 case PreDefinedExpr::PrettyFunction:
446 // FIXME:: Demangle C++ method names
447 GlobalVarName = "__PRETTY_FUNCTION__.";
448 break;
449 }
450
451 GlobalVarName += CurFuncDecl->getName();
452
453 // FIXME: Can cache/reuse these within the module.
454 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
455
456 // Create a global variable for this.
457 C = new llvm::GlobalVariable(C->getType(), true,
458 llvm::GlobalValue::InternalLinkage,
459 C, GlobalVarName, CurFn->getParent());
460 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
461 llvm::Constant *Zeros[] = { Zero, Zero };
462 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
463 return LValue::MakeAddr(C);
464}
465
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000466LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +0000467 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000468 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000469
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000470 // If the base is a vector type, then we are forming a vector element lvalue
471 // with this subscript.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000472 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000473 // Emit the vector as an lvalue to get its address.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000474 LValue LHS = EmitLValue(E->getLHS());
475 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000476 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000477 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000478 }
479
Ted Kremenekc81614d2007-08-20 16:18:38 +0000480 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000481 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000482
Ted Kremenekc81614d2007-08-20 16:18:38 +0000483 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000484 QualType IdxTy = E->getIdx()->getType();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000485 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000486 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000487 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000488 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000489 IdxSigned, "idxprom");
490
491 // We know that the pointer points to a type of the correct size, unless the
492 // size is a VLA.
Chris Lattner0e9d6222007-07-15 23:26:56 +0000493 if (!E->getType()->isConstantSizeType(getContext()))
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000494 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000495 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000496}
497
Chris Lattner9e751ca2007-08-02 23:37:31 +0000498LValue CodeGenFunction::
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000499EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +0000500 // Emit the base vector as an l-value.
501 LValue Base = EmitLValue(E->getBase());
502 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
503
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000504 return LValue::MakeOCUVectorElt(Base.getAddress(),
505 E->getEncodedElementAccess());
Chris Lattner9e751ca2007-08-02 23:37:31 +0000506}
507
Chris Lattnere47e4402007-06-01 18:02:12 +0000508//===--------------------------------------------------------------------===//
509// Expression Emission
510//===--------------------------------------------------------------------===//
511
Chris Lattner8394d792007-06-05 20:53:16 +0000512RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattner6278e6a2007-08-11 00:04:45 +0000513 assert(E && !hasAggregateLLVMType(E->getType()) &&
514 "Invalid scalar expression to emit");
Chris Lattnere47e4402007-06-01 18:02:12 +0000515
516 switch (E->getStmtClass()) {
517 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000518 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000519 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000520 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000521
522 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000523 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000524 // DeclRef's of EnumConstantDecl's are simple rvalues.
525 if (const EnumConstantDecl *EC =
526 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000527 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattner8394d792007-06-05 20:53:16 +0000528 return EmitLoadOfLValue(E);
Chris Lattnera779b3d2007-07-10 21:58:36 +0000529 case Expr::ArraySubscriptExprClass:
530 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000531 case Expr::OCUVectorElementExprClass:
Chris Lattner73ab9b32007-08-03 00:16:29 +0000532 return EmitLoadOfLValue(E);
Anders Carlsson625bfc82007-07-21 05:21:51 +0000533 case Expr::PreDefinedExprClass:
Chris Lattner4347e3692007-06-06 04:54:52 +0000534 case Expr::StringLiteralClass:
535 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000536
537 // Leaf expressions.
538 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000539 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattner2ada32e2007-07-09 23:03:16 +0000540 case Expr::FloatingLiteralClass:
541 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000542 case Expr::CharacterLiteralClass:
543 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner40480052007-08-03 17:51:03 +0000544 case Expr::TypesCompatibleExprClass:
545 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000546
Chris Lattnerd7f58862007-06-02 05:24:33 +0000547 // Operators.
548 case Expr::ParenExprClass:
549 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000550 case Expr::UnaryOperatorClass:
551 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000552 case Expr::SizeOfAlignOfTypeExprClass:
553 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
554 E->getType(),
555 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattner388cf762007-07-13 20:25:53 +0000556 case Expr::ImplicitCastExprClass:
Chris Lattner76ba8492007-08-20 22:37:10 +0000557 return EmitImplicitCastExpr(cast<ImplicitCastExpr>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000558 case Expr::CastExprClass:
Chris Lattner388cf762007-07-13 20:25:53 +0000559 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner2b228c92007-06-15 21:34:29 +0000560 case Expr::CallExprClass:
561 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000562 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000563 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000564
565 case Expr::ConditionalOperatorClass:
566 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner81a96882007-08-04 00:20:15 +0000567 case Expr::ChooseExprClass:
568 return EmitChooseExpr(cast<ChooseExpr>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000569 }
Chris Lattnere47e4402007-06-01 18:02:12 +0000570}
571
Chris Lattner8394d792007-06-05 20:53:16 +0000572RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000573 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000574}
Chris Lattner2ada32e2007-07-09 23:03:16 +0000575RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
576 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
577 E->getValue()));
578}
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000579RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
580 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
581 E->getValue()));
582}
Chris Lattnera779b3d2007-07-10 21:58:36 +0000583
Chris Lattner40480052007-08-03 17:51:03 +0000584RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
585 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
586 E->typesAreCompatible()));
587}
588
Chris Lattner81a96882007-08-04 00:20:15 +0000589/// EmitChooseExpr - Implement __builtin_choose_expr.
590RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
591 llvm::APSInt CondVal(32);
592 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
593 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
594
595 // Emit the LHS or RHS as appropriate.
596 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
597}
598
Chris Lattner40480052007-08-03 17:51:03 +0000599
Chris Lattnera779b3d2007-07-10 21:58:36 +0000600RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
601 // Emit subscript expressions in rvalue context's. For most cases, this just
602 // loads the lvalue formed by the subscript expr. However, we have to be
603 // careful, because the base of a vector subscript is occasionally an rvalue,
604 // so we can't get it as an lvalue.
605 if (!E->getBase()->getType()->isVectorType())
606 return EmitLoadOfLValue(E);
607
608 // Handle the vector case. The base must be a vector, the index must be an
609 // integer value.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000610 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
611 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattnera779b3d2007-07-10 21:58:36 +0000612
613 // FIXME: Convert Idx to i32 type.
614
615 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
616}
617
Chris Lattner388cf762007-07-13 20:25:53 +0000618// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
619// have to handle a more broad range of conversions than explicit casts, as they
620// handle things like function to ptr-to-function decay etc.
621RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000622 RValue Src = EmitExpr(Op);
Chris Lattner8394d792007-06-05 20:53:16 +0000623
624 // If the destination is void, just evaluate the source.
Chris Lattner388cf762007-07-13 20:25:53 +0000625 if (DestTy->isVoidType())
Chris Lattner8394d792007-06-05 20:53:16 +0000626 return RValue::getAggregate(0);
627
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000628 return EmitConversion(Src, Op->getType(), DestTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000629}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000630
Chris Lattner76ba8492007-08-20 22:37:10 +0000631/// EmitImplicitCastExpr - Implicit casts are the same as normal casts, but also
632/// handle things like function to pointer-to-function decay, and array to
633/// pointer decay.
634RValue CodeGenFunction::EmitImplicitCastExpr(const ImplicitCastExpr *E) {
635 const Expr *Op = E->getSubExpr();
636 QualType OpTy = Op->getType().getCanonicalType();
637
638 // If this is due to array->pointer conversion, emit the array expression as
639 // an l-value.
640 if (isa<ArrayType>(OpTy)) {
641 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
642 // will not true when we add support for VLAs.
643 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
644
645 assert(isa<llvm::PointerType>(V->getType()) &&
646 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
647 ->getElementType()) &&
648 "Doesn't support VLAs yet!");
649 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
650 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
651 }
652
653 return EmitCastExpr(Op, E->getType());
654}
655
Chris Lattner2b228c92007-06-15 21:34:29 +0000656RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson1d8e5212007-08-20 18:05:56 +0000657 if (const ImplicitCastExpr *IcExpr =
658 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
659 if (const DeclRefExpr *DRExpr =
660 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
661 if (const FunctionDecl *FDecl =
662 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
663 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
664 return EmitBuiltinExpr(builtinID, E);
665
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000666 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattnerc14236b2007-07-10 22:18:37 +0000667
668 // The callee type will always be a pointer to function type, get the function
669 // type.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000670 QualType CalleeTy = E->getCallee()->getType();
Chris Lattnerc14236b2007-07-10 22:18:37 +0000671 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
672
673 // Get information about the argument types.
674 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
675
676 // Calling unprototyped functions provides no argument info.
677 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
678 ArgTyIt = FTP->arg_type_begin();
679 ArgTyEnd = FTP->arg_type_end();
680 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000681
Chris Lattner23b7eb62007-06-15 23:05:46 +0000682 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000683
Chris Lattner90d91202007-08-10 17:02:28 +0000684 // Handle struct-return functions by passing a pointer to the location that
685 // we would like to return into.
686 if (hasAggregateLLVMType(E->getType())) {
687 // Create a temporary alloca to hold the result of the call. :(
688 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
689 // FIXME: set the stret attribute on the argument.
690 }
691
Chris Lattner2b228c92007-06-15 21:34:29 +0000692 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000693 QualType ArgTy = E->getArg(i)->getType();
694 RValue ArgVal = EmitExpr(E->getArg(i));
Chris Lattnerc14236b2007-07-10 22:18:37 +0000695
696 // If this argument has prototype information, convert it.
697 if (ArgTyIt != ArgTyEnd) {
698 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
699 } else {
700 // Otherwise, if passing through "..." or to a function with no prototype,
701 // perform the "default argument promotions" (C99 6.5.2.2p6), which
702 // includes the usual unary conversions, but also promotes float to
703 // double.
704 if (const BuiltinType *BT =
705 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
706 if (BT->getKind() == BuiltinType::Float)
707 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
708 llvm::Type::DoubleTy,"tmp"));
709 }
710 }
711
Chris Lattner2b228c92007-06-15 21:34:29 +0000712
713 if (ArgVal.isScalar())
714 Args.push_back(ArgVal.getVal());
715 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000716 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000717 }
718
Chris Lattner7b9f04e2007-08-01 06:24:52 +0000719 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000720 if (V->getType() != llvm::Type::VoidTy)
721 V->setName("call");
Chris Lattner90d91202007-08-10 17:02:28 +0000722 else if (hasAggregateLLVMType(E->getType()))
723 // Struct return.
724 return RValue::getAggregate(Args[0]);
725
Chris Lattner2b228c92007-06-15 21:34:29 +0000726 return RValue::get(V);
727}
728
729
Chris Lattner8394d792007-06-05 20:53:16 +0000730//===----------------------------------------------------------------------===//
731// Unary Operator Emission
732//===----------------------------------------------------------------------===//
733
Chris Lattner8394d792007-06-05 20:53:16 +0000734RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000735 switch (E->getOpcode()) {
736 default:
737 printf("Unimplemented unary expr!\n");
738 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000739 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerdcca4872007-07-11 23:43:46 +0000740 case UnaryOperator::PostInc:
741 case UnaryOperator::PostDec:
742 case UnaryOperator::PreInc :
743 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
744 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
745 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
746 case UnaryOperator::Plus : return EmitUnaryPlus(E);
747 case UnaryOperator::Minus : return EmitUnaryMinus(E);
748 case UnaryOperator::Not : return EmitUnaryNot(E);
749 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000750 case UnaryOperator::SizeOf :
751 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
752 case UnaryOperator::AlignOf :
753 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Chris Lattner8394d792007-06-05 20:53:16 +0000754 // FIXME: real/imag
755 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000756 }
757}
758
Chris Lattnerdcca4872007-07-11 23:43:46 +0000759RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
760 LValue LV = EmitLValue(E->getSubExpr());
761 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
762
763 // We know the operand is real or pointer type, so it must be an LLVM scalar.
764 assert(InVal.isScalar() && "Unknown thing to increment");
765 llvm::Value *InV = InVal.getVal();
766
767 int AmountVal = 1;
768 if (E->getOpcode() == UnaryOperator::PreDec ||
769 E->getOpcode() == UnaryOperator::PostDec)
770 AmountVal = -1;
771
772 llvm::Value *NextVal;
773 if (isa<llvm::IntegerType>(InV->getType())) {
774 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
775 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
776 } else if (InV->getType()->isFloatingPoint()) {
777 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
778 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
779 } else {
780 // FIXME: This is not right for pointers to VLA types.
781 assert(isa<llvm::PointerType>(InV->getType()));
782 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
783 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
784 }
785
786 RValue NextValToStore = RValue::get(NextVal);
787
788 // Store the updated result through the lvalue.
789 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
790
791 // If this is a postinc, return the value read from memory, otherwise use the
792 // updated value.
793 if (E->getOpcode() == UnaryOperator::PreDec ||
794 E->getOpcode() == UnaryOperator::PreInc)
795 return NextValToStore;
796 else
797 return InVal;
798}
799
Chris Lattner8394d792007-06-05 20:53:16 +0000800/// C99 6.5.3.2
801RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
802 // The address of the operand is just its lvalue. It cannot be a bitfield.
803 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
804}
805
806RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000807 assert(E->getType().getCanonicalType() ==
808 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
809 // Unary plus just returns its value.
810 return EmitExpr(E->getSubExpr());
Chris Lattner8394d792007-06-05 20:53:16 +0000811}
812
813RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000814 assert(E->getType().getCanonicalType() ==
815 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
816
Chris Lattner8394d792007-06-05 20:53:16 +0000817 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000818 RValue V = EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000819
Chris Lattner8394d792007-06-05 20:53:16 +0000820 if (V.isScalar())
821 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
822
823 assert(0 && "FIXME: This doesn't handle complex operands yet");
824}
825
826RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
827 // Unary not performs promotions, then complements its integer operand.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000828 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner8394d792007-06-05 20:53:16 +0000829
830 if (V.isScalar())
831 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
832
833 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
834}
835
836
837/// C99 6.5.3.3
838RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
839 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000840 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000841
842 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000843 // TODO: Could dynamically modify easy computations here. For example, if
844 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000845 BoolVal = Builder.CreateNot(BoolVal, "lnot");
846
847 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000848 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000849}
850
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000851/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
852/// an integer (RetType).
853RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
854 QualType RetType, bool isSizeOf) {
855 /// FIXME: This doesn't handle VLAs yet!
856 std::pair<uint64_t, unsigned> Info =
857 getContext().getTypeInfo(TypeToSize, SourceLocation());
858
859 uint64_t Val = isSizeOf ? Info.first : Info.second;
860 Val /= 8; // Return size in bytes, not bits.
861
862 assert(RetType->isIntegerType() && "Result type must be an integer!");
863
864 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
865 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
866}
867
Chris Lattnere47e4402007-06-01 18:02:12 +0000868
Chris Lattnerdb91b162007-06-02 00:16:28 +0000869//===--------------------------------------------------------------------===//
870// Binary Operator Emission
871//===--------------------------------------------------------------------===//
872
Chris Lattnerdb91b162007-06-02 00:16:28 +0000873
Chris Lattnercd215f02007-06-29 16:52:55 +0000874/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
875/// are strange in that the result of the operation is not the same type as the
876/// intermediate computation. This function emits the LHS and RHS operands of
877/// the compound assignment, promoting them to their common computation type.
878///
879/// Since the LHS is an lvalue, and the result is stored back through it, we
880/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
881/// RHS values are both in the computation type for the operator.
882void CodeGenFunction::
883EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
884 LValue &LHSLV, RValue &LHS, RValue &RHS) {
885 LHSLV = EmitLValue(E->getLHS());
886
887 // Load the LHS and RHS operands.
888 QualType LHSTy = E->getLHS()->getType();
889 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000890 RHS = EmitExpr(E->getRHS());
891 QualType RHSTy = E->getRHS()->getType();
Chris Lattner47c247e2007-06-29 17:26:27 +0000892
Chris Lattnercd215f02007-06-29 16:52:55 +0000893 // Convert the LHS and RHS to the common evaluation type.
894 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
895 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
896}
897
898/// EmitCompoundAssignmentResult - Given a result value in the computation type,
899/// truncate it down to the actual result type, store it through the LHS lvalue,
900/// and return it.
901RValue CodeGenFunction::
902EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
903 LValue LHSLV, RValue ResV) {
904
905 // Truncate back to the destination type.
906 if (E->getComputationType() != E->getType())
907 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
908
909 // Store the result value into the LHS.
910 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
911
912 // Return the result.
913 return ResV;
914}
915
Chris Lattnerdb91b162007-06-02 00:16:28 +0000916
Chris Lattner8394d792007-06-05 20:53:16 +0000917RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000918 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000919 switch (E->getOpcode()) {
920 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000921 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000922 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000923 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerb25a9432007-06-29 17:03:06 +0000924 case BinaryOperator::Mul:
Chris Lattner87f48362007-08-08 17:49:18 +0000925 LHS = EmitExpr(E->getLHS());
926 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000927 return EmitMul(LHS, RHS, E->getType());
928 case BinaryOperator::Div:
Chris Lattner87f48362007-08-08 17:49:18 +0000929 LHS = EmitExpr(E->getLHS());
930 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000931 return EmitDiv(LHS, RHS, E->getType());
932 case BinaryOperator::Rem:
Chris Lattner87f48362007-08-08 17:49:18 +0000933 LHS = EmitExpr(E->getLHS());
934 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000935 return EmitRem(LHS, RHS, E->getType());
Chris Lattner87f48362007-08-08 17:49:18 +0000936 case BinaryOperator::Add:
937 LHS = EmitExpr(E->getLHS());
938 RHS = EmitExpr(E->getRHS());
939 if (!E->getType()->isPointerType())
940 return EmitAdd(LHS, RHS, E->getType());
941
942 return EmitPointerAdd(LHS, E->getLHS()->getType(),
943 RHS, E->getRHS()->getType(), E->getType());
944 case BinaryOperator::Sub:
945 LHS = EmitExpr(E->getLHS());
946 RHS = EmitExpr(E->getRHS());
947
948 if (!E->getLHS()->getType()->isPointerType())
949 return EmitSub(LHS, RHS, E->getType());
950
951 return EmitPointerSub(LHS, E->getLHS()->getType(),
952 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner47c247e2007-06-29 17:26:27 +0000953 case BinaryOperator::Shl:
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000954 LHS = EmitExpr(E->getLHS());
955 RHS = EmitExpr(E->getRHS());
Chris Lattner47c247e2007-06-29 17:26:27 +0000956 return EmitShl(LHS, RHS, E->getType());
957 case BinaryOperator::Shr:
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000958 LHS = EmitExpr(E->getLHS());
959 RHS = EmitExpr(E->getRHS());
Chris Lattner47c247e2007-06-29 17:26:27 +0000960 return EmitShr(LHS, RHS, E->getType());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000961 case BinaryOperator::And:
Chris Lattner87f48362007-08-08 17:49:18 +0000962 LHS = EmitExpr(E->getLHS());
963 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000964 return EmitAnd(LHS, RHS, E->getType());
965 case BinaryOperator::Xor:
Chris Lattner87f48362007-08-08 17:49:18 +0000966 LHS = EmitExpr(E->getLHS());
967 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000968 return EmitXor(LHS, RHS, E->getType());
969 case BinaryOperator::Or :
Chris Lattner87f48362007-08-08 17:49:18 +0000970 LHS = EmitExpr(E->getLHS());
971 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000972 return EmitOr(LHS, RHS, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000973 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
974 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +0000975 case BinaryOperator::LT:
976 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
977 llvm::ICmpInst::ICMP_SLT,
978 llvm::FCmpInst::FCMP_OLT);
979 case BinaryOperator::GT:
980 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
981 llvm::ICmpInst::ICMP_SGT,
982 llvm::FCmpInst::FCMP_OGT);
983 case BinaryOperator::LE:
984 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
985 llvm::ICmpInst::ICMP_SLE,
986 llvm::FCmpInst::FCMP_OLE);
987 case BinaryOperator::GE:
988 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
989 llvm::ICmpInst::ICMP_SGE,
990 llvm::FCmpInst::FCMP_OGE);
991 case BinaryOperator::EQ:
992 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
993 llvm::ICmpInst::ICMP_EQ,
994 llvm::FCmpInst::FCMP_OEQ);
995 case BinaryOperator::NE:
996 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
997 llvm::ICmpInst::ICMP_NE,
998 llvm::FCmpInst::FCMP_UNE);
Chris Lattnercd215f02007-06-29 16:52:55 +0000999 case BinaryOperator::Assign:
1000 return EmitBinaryAssign(E);
1001
Chris Lattnerb25a9432007-06-29 17:03:06 +00001002 case BinaryOperator::MulAssign: {
1003 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1004 LValue LHSLV;
1005 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1006 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1007 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1008 }
1009 case BinaryOperator::DivAssign: {
1010 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1011 LValue LHSLV;
1012 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1013 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1014 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1015 }
1016 case BinaryOperator::RemAssign: {
1017 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1018 LValue LHSLV;
1019 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1020 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1021 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1022 }
Chris Lattnercd215f02007-06-29 16:52:55 +00001023 case BinaryOperator::AddAssign: {
1024 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1025 LValue LHSLV;
1026 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1027 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1028 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1029 }
1030 case BinaryOperator::SubAssign: {
1031 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1032 LValue LHSLV;
1033 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1034 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1035 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1036 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001037 case BinaryOperator::ShlAssign: {
1038 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1039 LValue LHSLV;
1040 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1041 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1042 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1043 }
1044 case BinaryOperator::ShrAssign: {
1045 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1046 LValue LHSLV;
1047 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1048 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1049 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1050 }
Chris Lattnerb25a9432007-06-29 17:03:06 +00001051 case BinaryOperator::AndAssign: {
1052 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1053 LValue LHSLV;
1054 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1055 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1056 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1057 }
1058 case BinaryOperator::OrAssign: {
1059 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1060 LValue LHSLV;
1061 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1062 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1063 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1064 }
1065 case BinaryOperator::XorAssign: {
1066 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1067 LValue LHSLV;
1068 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1069 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1070 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1071 }
Chris Lattner8394d792007-06-05 20:53:16 +00001072 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +00001073 }
1074}
1075
Chris Lattnerb25a9432007-06-29 17:03:06 +00001076RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner835635d2007-08-21 04:59:27 +00001077 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
Chris Lattner8394d792007-06-05 20:53:16 +00001078}
1079
Chris Lattnerb25a9432007-06-29 17:03:06 +00001080RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner6ce75df2007-08-21 16:34:16 +00001081 if (LHS.getVal()->getType()->isFloatingPoint())
1082 return RValue::get(Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div"));
1083 else if (ResTy->isUnsignedIntegerType())
1084 return RValue::get(Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div"));
1085 else
1086 return RValue::get(Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div"));
Chris Lattner8394d792007-06-05 20:53:16 +00001087}
1088
Chris Lattnerb25a9432007-06-29 17:03:06 +00001089RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner6ce75df2007-08-21 16:34:16 +00001090 // Rem in C can't be a floating point type: C99 6.5.5p2.
1091 if (ResTy->isUnsignedIntegerType())
1092 return RValue::get(Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem"));
1093 else
1094 return RValue::get(Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem"));
Chris Lattner8394d792007-06-05 20:53:16 +00001095}
1096
Chris Lattnercd215f02007-06-29 16:52:55 +00001097RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner835635d2007-08-21 04:59:27 +00001098 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattner8394d792007-06-05 20:53:16 +00001099}
1100
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001101RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1102 RValue RHS, QualType RHSTy,
1103 QualType ResTy) {
1104 llvm::Value *LHSValue = LHS.getVal();
1105 llvm::Value *RHSValue = RHS.getVal();
1106 if (LHSTy->isPointerType()) {
1107 // pointer + int
1108 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1109 } else {
1110 // int + pointer
1111 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1112 }
1113}
1114
Chris Lattnercd215f02007-06-29 16:52:55 +00001115RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner6ce75df2007-08-21 16:34:16 +00001116 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
Chris Lattner8394d792007-06-05 20:53:16 +00001117}
1118
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001119RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1120 RValue RHS, QualType RHSTy,
1121 QualType ResTy) {
1122 llvm::Value *LHSValue = LHS.getVal();
1123 llvm::Value *RHSValue = RHS.getVal();
1124 if (const PointerType *RHSPtrType =
1125 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1126 // pointer - pointer
1127 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1128 QualType LHSElementType = LHSPtrType->getPointeeType();
1129 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1130 "can't subtract pointers with differing element types");
Chris Lattner651f0e92007-07-16 05:43:05 +00001131 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattner4481b422007-07-14 01:29:45 +00001132 SourceLocation()) / 8;
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001133 const llvm::Type *ResultType = ConvertType(ResTy);
1134 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1135 "sub.ptr.lhs.cast");
1136 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1137 "sub.ptr.rhs.cast");
1138 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1139 "sub.ptr.sub");
Chris Lattner651f0e92007-07-16 05:43:05 +00001140
1141 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1142 // remainder. As such, we handle common power-of-two cases here to generate
1143 // better code.
1144 if (llvm::isPowerOf2_64(ElementSize)) {
1145 llvm::Value *ShAmt =
1146 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1147 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1148 } else {
1149 // Otherwise, do a full sdiv.
1150 llvm::Value *BytesPerElement =
1151 llvm::ConstantInt::get(ResultType, ElementSize);
1152 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1153 "sub.ptr.div"));
1154 }
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001155 } else {
1156 // pointer - int
1157 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1158 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1159 }
1160}
1161
Chris Lattner47c247e2007-06-29 17:26:27 +00001162RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1163 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1164
Chris Lattner8394d792007-06-05 20:53:16 +00001165 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1166 // RHS to the same size as the LHS.
1167 if (LHS->getType() != RHS->getType())
1168 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1169
1170 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1171}
1172
Chris Lattner47c247e2007-06-29 17:26:27 +00001173RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1174 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
Chris Lattner8394d792007-06-05 20:53:16 +00001175
1176 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1177 // RHS to the same size as the LHS.
1178 if (LHS->getType() != RHS->getType())
1179 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1180
Chris Lattner47c247e2007-06-29 17:26:27 +00001181 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001182 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1183 else
1184 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1185}
1186
Chris Lattner1fde0b32007-06-20 18:30:55 +00001187RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1188 unsigned UICmpOpc, unsigned SICmpOpc,
1189 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +00001190 llvm::Value *Result;
Chris Lattner96d72562007-08-21 16:57:55 +00001191 QualType LHSTy = E->getLHS()->getType();
1192 if (!LHSTy->isComplexType()) {
1193 RValue LHS = EmitExpr(E->getLHS());
1194 RValue RHS = EmitExpr(E->getRHS());
1195
1196 if (LHSTy->isRealFloatingType()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001197 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1198 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner96d72562007-08-21 16:57:55 +00001199 } else if (LHSTy->isUnsignedIntegerType()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001200 // FIXME: This check isn't right for "unsigned short < int" where ushort
1201 // promotes to int and does a signed compare.
1202 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1203 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001204 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001205 // Signed integers and pointers.
1206 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1207 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001208 }
1209 } else {
Chris Lattner96d72562007-08-21 16:57:55 +00001210 // Complex Comparison: can only be an equality comparison.
1211 ComplexPairTy LHS = EmitComplexExpr(E->getLHS());
1212 ComplexPairTy RHS = EmitComplexExpr(E->getRHS());
Gabor Greifd4606aa2007-07-13 23:33:18 +00001213
Chris Lattner96d72562007-08-21 16:57:55 +00001214 QualType CETy =
1215 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
1216
1217 llvm::Value *ResultR, *ResultI;
1218 if (CETy->isRealFloatingType()) {
1219 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1220 LHS.first, RHS.first, "cmp.r");
1221 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1222 LHS.second, RHS.second, "cmp.i");
Gabor Greifd4606aa2007-07-13 23:33:18 +00001223 } else {
Chris Lattnerbf1bd0d2007-08-21 17:03:38 +00001224 // Complex comparisons can only be equality comparisons. As such, signed
1225 // and unsigned opcodes are the same.
1226 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner96d72562007-08-21 16:57:55 +00001227 LHS.first, RHS.first, "cmp.r");
Chris Lattnerbf1bd0d2007-08-21 17:03:38 +00001228 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner96d72562007-08-21 16:57:55 +00001229 LHS.second, RHS.second, "cmp.i");
Gabor Greifd4606aa2007-07-13 23:33:18 +00001230 }
Chris Lattner96d72562007-08-21 16:57:55 +00001231
1232 if (E->getOpcode() == BinaryOperator::EQ) {
1233 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1234 } else {
1235 assert(E->getOpcode() == BinaryOperator::NE &&
1236 "Complex comparison other than == or != ?");
1237 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1238 }
Chris Lattner273c63d2007-06-20 18:02:30 +00001239 }
Gabor Greifd4606aa2007-07-13 23:33:18 +00001240
Chris Lattner273c63d2007-06-20 18:02:30 +00001241 // ZExt result to int.
1242 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1243}
1244
Chris Lattnerb25a9432007-06-29 17:03:06 +00001245RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner64be48f2007-08-21 17:12:50 +00001246 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
Chris Lattner8394d792007-06-05 20:53:16 +00001247}
1248
Chris Lattnerb25a9432007-06-29 17:03:06 +00001249RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner64be48f2007-08-21 17:12:50 +00001250 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
Chris Lattner8394d792007-06-05 20:53:16 +00001251}
1252
Chris Lattnerb25a9432007-06-29 17:03:06 +00001253RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner64be48f2007-08-21 17:12:50 +00001254 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
Chris Lattner8394d792007-06-05 20:53:16 +00001255}
1256
1257RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001258 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001259
Chris Lattner23b7eb62007-06-15 23:05:46 +00001260 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1261 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001262
Chris Lattner23b7eb62007-06-15 23:05:46 +00001263 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001264 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1265
1266 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001267 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001268
1269 // Reaquire the RHS block, as there may be subblocks inserted.
1270 RHSBlock = Builder.GetInsertBlock();
1271 EmitBlock(ContBlock);
1272
1273 // Create a PHI node. If we just evaluted the LHS condition, the result is
1274 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001275 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +00001276 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001277 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001278 PN->addIncoming(RHSCond, RHSBlock);
1279
1280 // ZExt result to int.
1281 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1282}
1283
1284RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001285 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001286
Chris Lattner23b7eb62007-06-15 23:05:46 +00001287 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1288 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001289
Chris Lattner23b7eb62007-06-15 23:05:46 +00001290 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001291 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1292
1293 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001294 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001295
1296 // Reaquire the RHS block, as there may be subblocks inserted.
1297 RHSBlock = Builder.GetInsertBlock();
1298 EmitBlock(ContBlock);
1299
1300 // Create a PHI node. If we just evaluted the LHS condition, the result is
1301 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001302 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +00001303 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001304 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001305 PN->addIncoming(RHSCond, RHSBlock);
1306
1307 // ZExt result to int.
1308 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1309}
1310
1311RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001312 assert(E->getLHS()->getType().getCanonicalType() ==
1313 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner8394d792007-06-05 20:53:16 +00001314 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001315 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001316
1317 // Store the value into the LHS.
1318 EmitStoreThroughLValue(RHS, LHS, E->getType());
Chris Lattner6278e6a2007-08-11 00:04:45 +00001319
1320 // Return the RHS.
Chris Lattner8394d792007-06-05 20:53:16 +00001321 return RHS;
1322}
1323
Chris Lattner9369a562007-06-29 16:31:29 +00001324
Chris Lattner8394d792007-06-05 20:53:16 +00001325RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
Chris Lattner3cf417b2007-08-21 17:15:50 +00001326 EmitStmt(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001327 return EmitExpr(E->getRHS());
1328}
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001329
1330RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1331 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1332 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1333 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1334
1335 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1336 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1337
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001338 EmitBlock(LHSBlock);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001339 // Handle the GNU extension for missing LHS.
1340 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001341 Builder.CreateBr(ContBlock);
1342 LHSBlock = Builder.GetInsertBlock();
1343
1344 EmitBlock(RHSBlock);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001345
1346 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001347 Builder.CreateBr(ContBlock);
1348 RHSBlock = Builder.GetInsertBlock();
1349
1350 const llvm::Type *LHSType = LHSValue->getType();
1351 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1352
1353 EmitBlock(ContBlock);
1354 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1355 PN->reserveOperandSpace(2);
1356 PN->addIncoming(LHSValue, LHSBlock);
1357 PN->addIncoming(RHSValue, RHSBlock);
1358
1359 return RValue::get(PN);
1360}