blob: 508b2833cd31a1afb1d2aaa2cdcb8e255be0f51a [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 Lattner8ad56702007-08-24 00:01:20 +000040 return ConvertScalarValueToBool(EmitAnyExpr(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 Lattner8ad56702007-08-24 00:01:20 +0000163 } else if (isa<ComplexType>(Ty)) {
164 assert(0 && "implement complex -> bool");
165
Chris Lattnerc6395932007-06-22 20:56:16 +0000166 } else {
Chris Lattner8ad56702007-08-24 00:01:20 +0000167 assert((isa<PointerType>(Ty) ||
168 (isa<TagType>(Ty) &&
169 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum)) &&
170 "Unknown Type");
171 // Code below handles this case fine.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000172 }
173
174 // Usual case for integers, pointers, and enums: compare against zero.
175 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000176
177 // Because of the type rules of C, we often end up computing a logical value,
178 // then zero extending it to int, then wanting it as a logical value again.
179 // Optimize this common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000180 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
Chris Lattnera45c5af2007-06-02 19:47:04 +0000181 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
182 Result = ZI->getOperand(0);
183 ZI->eraseFromParent();
184 return Result;
185 }
186 }
187
Chris Lattner23b7eb62007-06-15 23:05:46 +0000188 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000189 return Builder.CreateICmpNE(Result, Zero, "tobool");
190}
191
Chris Lattnera45c5af2007-06-02 19:47:04 +0000192//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000193// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000194//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000195
Chris Lattner8394d792007-06-05 20:53:16 +0000196/// EmitLValue - Emit code to compute a designator that specifies the location
197/// of the expression.
198///
199/// This can return one of two things: a simple address or a bitfield
200/// reference. In either case, the LLVM Value* in the LValue structure is
201/// guaranteed to be an LLVM pointer type.
202///
203/// If this returns a bitfield reference, nothing about the pointee type of
204/// the LLVM value is known: For example, it may not be a pointer to an
205/// integer.
206///
207/// If this returns a normal address, and if the lvalue's C type is fixed
208/// size, this method guarantees that the returned pointer type will point to
209/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
210/// variable length type, this is not possible.
211///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000212LValue CodeGenFunction::EmitLValue(const Expr *E) {
213 switch (E->getStmtClass()) {
214 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000215 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000216 E->dump();
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000217 return LValue::MakeAddr(llvm::UndefValue::get(
Chris Lattnerd7f58862007-06-02 05:24:33 +0000218 llvm::PointerType::get(llvm::Type::Int32Ty)));
219
220 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000221 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson625bfc82007-07-21 05:21:51 +0000222 case Expr::PreDefinedExprClass:
223 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000224 case Expr::StringLiteralClass:
225 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000226
227 case Expr::UnaryOperatorClass:
228 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000229 case Expr::ArraySubscriptExprClass:
230 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000231 case Expr::OCUVectorElementExprClass:
232 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000233 }
234}
235
Chris Lattner8394d792007-06-05 20:53:16 +0000236/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
237/// this method emits the address of the lvalue, then loads the result as an
238/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000239RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000240 if (LV.isSimple()) {
241 llvm::Value *Ptr = LV.getAddress();
242 const llvm::Type *EltTy =
243 cast<llvm::PointerType>(Ptr->getType())->getElementType();
244
245 // Simple scalar l-value.
246 if (EltTy->isFirstClassType())
247 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
248
Chris Lattner6278e6a2007-08-11 00:04:45 +0000249 assert(ExprType->isFunctionType() && "Unknown scalar value");
250 return RValue::get(Ptr);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000251 }
Chris Lattner09153c02007-06-22 18:48:09 +0000252
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000253 if (LV.isVectorElt()) {
254 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
255 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
256 "vecext"));
257 }
Chris Lattner73ab9b32007-08-03 00:16:29 +0000258
259 // If this is a reference to a subset of the elements of a vector, either
260 // shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000261 if (LV.isOCUVectorElt())
262 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner09153c02007-06-22 18:48:09 +0000263
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000264 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000265}
266
Chris Lattner40ff7012007-08-03 16:18:34 +0000267// If this is a reference to a subset of the elements of a vector, either
268// shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000269RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000270 QualType ExprType) {
Chris Lattner40ff7012007-08-03 16:18:34 +0000271 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
272
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000273 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner40ff7012007-08-03 16:18:34 +0000274
275 // If the result of the expression is a non-vector type, we must be
276 // extracting a single element. Just codegen as an extractelement.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000277 const VectorType *ExprVT = ExprType->getAsVectorType();
278 if (!ExprVT) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000279 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000280 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
281 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
282 }
283
284 // If the source and destination have the same number of elements, use a
285 // vector shuffle instead of insert/extracts.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000286 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner40ff7012007-08-03 16:18:34 +0000287 unsigned NumSourceElts =
288 cast<llvm::VectorType>(Vec->getType())->getNumElements();
289
290 if (NumResultElts == NumSourceElts) {
291 llvm::SmallVector<llvm::Constant*, 4> Mask;
292 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000293 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000294 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
295 }
296
297 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
298 Vec = Builder.CreateShuffleVector(Vec,
299 llvm::UndefValue::get(Vec->getType()),
300 MaskV, "tmp");
301 return RValue::get(Vec);
302 }
303
304 // Start out with an undef of the result type.
305 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
306
307 // Extract/Insert each element of the result.
308 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000309 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000310 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
311 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
312
313 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
314 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
315 }
316
317 return RValue::get(Result);
318}
319
320
Chris Lattner9369a562007-06-29 16:31:29 +0000321RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
322 return EmitLoadOfLValue(EmitLValue(E), E->getType());
323}
324
325
Chris Lattner8394d792007-06-05 20:53:16 +0000326/// EmitStoreThroughLValue - Store the specified rvalue into the specified
327/// lvalue, where both are guaranteed to the have the same type, and that type
328/// is 'Ty'.
329void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
330 QualType Ty) {
Chris Lattner41d480e2007-08-03 16:28:33 +0000331 if (!Dst.isSimple()) {
332 if (Dst.isVectorElt()) {
333 // Read/modify/write the vector, inserting the new element.
334 // FIXME: Volatility.
335 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
336 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
337 Dst.getVectorIdx(), "vecins");
338 Builder.CreateStore(Vec, Dst.getVectorAddr());
339 return;
340 }
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000341
Chris Lattner41d480e2007-08-03 16:28:33 +0000342 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000343 if (Dst.isOCUVectorElt())
Chris Lattner41d480e2007-08-03 16:28:33 +0000344 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
345
346 assert(0 && "FIXME: Don't support store to bitfield yet");
347 }
Chris Lattner8394d792007-06-05 20:53:16 +0000348
Chris Lattner09153c02007-06-22 18:48:09 +0000349 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000350 assert(Src.isScalar() && "Can't emit an agg store with this method");
351 // FIXME: Handle volatility etc.
352 const llvm::Type *SrcTy = Src.getVal()->getType();
353 const llvm::Type *AddrTy =
354 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner8394d792007-06-05 20:53:16 +0000355
Chris Lattner6278e6a2007-08-11 00:04:45 +0000356 if (AddrTy != SrcTy)
357 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
358 "storetmp");
359 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner8394d792007-06-05 20:53:16 +0000360}
361
Chris Lattner41d480e2007-08-03 16:28:33 +0000362void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
363 QualType Ty) {
364 // This access turns into a read/modify/write of the vector. Load the input
365 // value now.
366 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
367 // FIXME: Volatility.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000368 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner41d480e2007-08-03 16:28:33 +0000369
370 llvm::Value *SrcVal = Src.getVal();
371
Chris Lattner3a44aa72007-08-03 16:37:04 +0000372 if (const VectorType *VTy = Ty->getAsVectorType()) {
373 unsigned NumSrcElts = VTy->getNumElements();
374
375 // Extract/Insert each element.
376 for (unsigned i = 0; i != NumSrcElts; ++i) {
377 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
378 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
379
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000380 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner3a44aa72007-08-03 16:37:04 +0000381 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
382 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
383 }
384 } else {
385 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000386 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner41d480e2007-08-03 16:28:33 +0000387 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
388 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner41d480e2007-08-03 16:28:33 +0000389 }
390
Chris Lattner41d480e2007-08-03 16:28:33 +0000391 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
392}
393
Chris Lattnerd7f58862007-06-02 05:24:33 +0000394
395LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
396 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000397 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000398 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000399 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000400 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000401 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000402 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000403 }
404 assert(0 && "Unimp declref");
405}
Chris Lattnere47e4402007-06-01 18:02:12 +0000406
Chris Lattner8394d792007-06-05 20:53:16 +0000407LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
408 // __extension__ doesn't affect lvalue-ness.
409 if (E->getOpcode() == UnaryOperator::Extension)
410 return EmitLValue(E->getSubExpr());
411
412 assert(E->getOpcode() == UnaryOperator::Deref &&
413 "'*' is the only unary operator that produces an lvalue");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000414 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
Chris Lattner8394d792007-06-05 20:53:16 +0000415}
416
Chris Lattner4347e3692007-06-06 04:54:52 +0000417LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
418 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
419 const char *StrData = E->getStrData();
420 unsigned Len = E->getByteLength();
421
422 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000423 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000424
425 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000426 C = new llvm::GlobalVariable(C->getType(), true,
427 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000428 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000429 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
430 llvm::Constant *Zeros[] = { Zero, Zero };
431 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000432 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000433}
434
Anders Carlsson625bfc82007-07-21 05:21:51 +0000435LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
436 std::string FunctionName(CurFuncDecl->getName());
437 std::string GlobalVarName;
438
439 switch (E->getIdentType()) {
440 default:
441 assert(0 && "unknown pre-defined ident type");
442 case PreDefinedExpr::Func:
443 GlobalVarName = "__func__.";
444 break;
445 case PreDefinedExpr::Function:
446 GlobalVarName = "__FUNCTION__.";
447 break;
448 case PreDefinedExpr::PrettyFunction:
449 // FIXME:: Demangle C++ method names
450 GlobalVarName = "__PRETTY_FUNCTION__.";
451 break;
452 }
453
454 GlobalVarName += CurFuncDecl->getName();
455
456 // FIXME: Can cache/reuse these within the module.
457 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
458
459 // Create a global variable for this.
460 C = new llvm::GlobalVariable(C->getType(), true,
461 llvm::GlobalValue::InternalLinkage,
462 C, GlobalVarName, CurFn->getParent());
463 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
464 llvm::Constant *Zeros[] = { Zero, Zero };
465 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
466 return LValue::MakeAddr(C);
467}
468
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000469LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +0000470 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000471 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000472
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000473 // If the base is a vector type, then we are forming a vector element lvalue
474 // with this subscript.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000475 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000476 // Emit the vector as an lvalue to get its address.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000477 LValue LHS = EmitLValue(E->getLHS());
478 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000479 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000480 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000481 }
482
Ted Kremenekc81614d2007-08-20 16:18:38 +0000483 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000484 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000485
Ted Kremenekc81614d2007-08-20 16:18:38 +0000486 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000487 QualType IdxTy = E->getIdx()->getType();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000488 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000489 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000490 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000491 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000492 IdxSigned, "idxprom");
493
494 // We know that the pointer points to a type of the correct size, unless the
495 // size is a VLA.
Chris Lattner0e9d6222007-07-15 23:26:56 +0000496 if (!E->getType()->isConstantSizeType(getContext()))
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000497 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000498 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000499}
500
Chris Lattner9e751ca2007-08-02 23:37:31 +0000501LValue CodeGenFunction::
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000502EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +0000503 // Emit the base vector as an l-value.
504 LValue Base = EmitLValue(E->getBase());
505 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
506
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000507 return LValue::MakeOCUVectorElt(Base.getAddress(),
508 E->getEncodedElementAccess());
Chris Lattner9e751ca2007-08-02 23:37:31 +0000509}
510
Chris Lattnere47e4402007-06-01 18:02:12 +0000511//===--------------------------------------------------------------------===//
512// Expression Emission
513//===--------------------------------------------------------------------===//
514
Chris Lattner08b15df2007-08-23 23:43:33 +0000515/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
516/// returning an rvalue corresponding to it. If NeedResult is false, the
517/// result of the expression doesn't need to be generated into memory.
518RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
519 if (!hasAggregateLLVMType(E->getType()))
520 return EmitExpr(E);
521
522 llvm::Value *DestMem = 0;
523 if (NeedResult)
524 DestMem = CreateTempAlloca(ConvertType(E->getType()));
525
526 if (!E->getType()->isComplexType()) {
527 EmitAggExpr(E, DestMem, false);
528 } else if (NeedResult)
529 EmitComplexExprIntoAddr(E, DestMem);
530 else
531 EmitComplexExpr(E);
532
533 return RValue::getAggregate(DestMem);
534}
535
Chris Lattner8394d792007-06-05 20:53:16 +0000536RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattner6278e6a2007-08-11 00:04:45 +0000537 assert(E && !hasAggregateLLVMType(E->getType()) &&
538 "Invalid scalar expression to emit");
Chris Lattnere47e4402007-06-01 18:02:12 +0000539
540 switch (E->getStmtClass()) {
541 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000542 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000543 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000544 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000545
546 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000547 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000548 // DeclRef's of EnumConstantDecl's are simple rvalues.
549 if (const EnumConstantDecl *EC =
550 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000551 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattner8394d792007-06-05 20:53:16 +0000552 return EmitLoadOfLValue(E);
Chris Lattnera779b3d2007-07-10 21:58:36 +0000553 case Expr::ArraySubscriptExprClass:
554 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000555 case Expr::OCUVectorElementExprClass:
Chris Lattner73ab9b32007-08-03 00:16:29 +0000556 return EmitLoadOfLValue(E);
Anders Carlsson625bfc82007-07-21 05:21:51 +0000557 case Expr::PreDefinedExprClass:
Chris Lattner4347e3692007-06-06 04:54:52 +0000558 case Expr::StringLiteralClass:
559 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000560
561 // Leaf expressions.
562 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000563 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattner2ada32e2007-07-09 23:03:16 +0000564 case Expr::FloatingLiteralClass:
565 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000566 case Expr::CharacterLiteralClass:
567 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner40480052007-08-03 17:51:03 +0000568 case Expr::TypesCompatibleExprClass:
569 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000570
Chris Lattnerd7f58862007-06-02 05:24:33 +0000571 // Operators.
572 case Expr::ParenExprClass:
573 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000574 case Expr::UnaryOperatorClass:
575 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000576 case Expr::SizeOfAlignOfTypeExprClass:
577 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
578 E->getType(),
579 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattner388cf762007-07-13 20:25:53 +0000580 case Expr::ImplicitCastExprClass:
Chris Lattner76ba8492007-08-20 22:37:10 +0000581 return EmitImplicitCastExpr(cast<ImplicitCastExpr>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000582 case Expr::CastExprClass:
Chris Lattner388cf762007-07-13 20:25:53 +0000583 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner2b228c92007-06-15 21:34:29 +0000584 case Expr::CallExprClass:
585 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000586 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000587 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000588
589 case Expr::ConditionalOperatorClass:
590 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner81a96882007-08-04 00:20:15 +0000591 case Expr::ChooseExprClass:
592 return EmitChooseExpr(cast<ChooseExpr>(E));
Anders Carlsson76f4a902007-08-21 17:43:55 +0000593 case Expr::ObjCStringLiteralClass:
594 return EmitObjCStringLiteral(cast<ObjCStringLiteral>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000595 }
Chris Lattnere47e4402007-06-01 18:02:12 +0000596}
597
Chris Lattner8394d792007-06-05 20:53:16 +0000598RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000599 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000600}
Chris Lattner2ada32e2007-07-09 23:03:16 +0000601RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
602 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
603 E->getValue()));
604}
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000605RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
606 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
607 E->getValue()));
608}
Chris Lattnera779b3d2007-07-10 21:58:36 +0000609
Chris Lattner40480052007-08-03 17:51:03 +0000610RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
611 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
612 E->typesAreCompatible()));
613}
614
Chris Lattner81a96882007-08-04 00:20:15 +0000615/// EmitChooseExpr - Implement __builtin_choose_expr.
616RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
617 llvm::APSInt CondVal(32);
618 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
619 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
620
621 // Emit the LHS or RHS as appropriate.
622 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
623}
624
Chris Lattner40480052007-08-03 17:51:03 +0000625
Chris Lattnera779b3d2007-07-10 21:58:36 +0000626RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
627 // Emit subscript expressions in rvalue context's. For most cases, this just
628 // loads the lvalue formed by the subscript expr. However, we have to be
629 // careful, because the base of a vector subscript is occasionally an rvalue,
630 // so we can't get it as an lvalue.
631 if (!E->getBase()->getType()->isVectorType())
632 return EmitLoadOfLValue(E);
633
634 // Handle the vector case. The base must be a vector, the index must be an
635 // integer value.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000636 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
637 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattnera779b3d2007-07-10 21:58:36 +0000638
639 // FIXME: Convert Idx to i32 type.
640
641 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
642}
643
Chris Lattner388cf762007-07-13 20:25:53 +0000644// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
645// have to handle a more broad range of conversions than explicit casts, as they
646// handle things like function to ptr-to-function decay etc.
647RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner8ad56702007-08-24 00:01:20 +0000648 RValue Src = EmitAnyExpr(Op);
Chris Lattner8394d792007-06-05 20:53:16 +0000649
650 // If the destination is void, just evaluate the source.
Chris Lattner388cf762007-07-13 20:25:53 +0000651 if (DestTy->isVoidType())
Chris Lattner8394d792007-06-05 20:53:16 +0000652 return RValue::getAggregate(0);
653
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000654 return EmitConversion(Src, Op->getType(), DestTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000655}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000656
Chris Lattner76ba8492007-08-20 22:37:10 +0000657/// EmitImplicitCastExpr - Implicit casts are the same as normal casts, but also
658/// handle things like function to pointer-to-function decay, and array to
659/// pointer decay.
660RValue CodeGenFunction::EmitImplicitCastExpr(const ImplicitCastExpr *E) {
661 const Expr *Op = E->getSubExpr();
662 QualType OpTy = Op->getType().getCanonicalType();
663
664 // If this is due to array->pointer conversion, emit the array expression as
665 // an l-value.
666 if (isa<ArrayType>(OpTy)) {
667 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
668 // will not true when we add support for VLAs.
669 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
670
671 assert(isa<llvm::PointerType>(V->getType()) &&
672 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
673 ->getElementType()) &&
674 "Doesn't support VLAs yet!");
675 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
676 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
677 }
678
679 return EmitCastExpr(Op, E->getType());
680}
681
Chris Lattner2b228c92007-06-15 21:34:29 +0000682RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson1d8e5212007-08-20 18:05:56 +0000683 if (const ImplicitCastExpr *IcExpr =
684 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
685 if (const DeclRefExpr *DRExpr =
686 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
687 if (const FunctionDecl *FDecl =
688 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
689 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
690 return EmitBuiltinExpr(builtinID, E);
691
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000692 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattnerc14236b2007-07-10 22:18:37 +0000693
694 // The callee type will always be a pointer to function type, get the function
695 // type.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000696 QualType CalleeTy = E->getCallee()->getType();
Chris Lattnerc14236b2007-07-10 22:18:37 +0000697 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
698
699 // Get information about the argument types.
700 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
701
702 // Calling unprototyped functions provides no argument info.
703 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
704 ArgTyIt = FTP->arg_type_begin();
705 ArgTyEnd = FTP->arg_type_end();
706 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000707
Chris Lattner23b7eb62007-06-15 23:05:46 +0000708 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000709
Chris Lattner90d91202007-08-10 17:02:28 +0000710 // Handle struct-return functions by passing a pointer to the location that
711 // we would like to return into.
712 if (hasAggregateLLVMType(E->getType())) {
713 // Create a temporary alloca to hold the result of the call. :(
714 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
715 // FIXME: set the stret attribute on the argument.
716 }
717
Chris Lattner2b228c92007-06-15 21:34:29 +0000718 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000719 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner08b15df2007-08-23 23:43:33 +0000720 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattnerc14236b2007-07-10 22:18:37 +0000721
722 // If this argument has prototype information, convert it.
723 if (ArgTyIt != ArgTyEnd) {
724 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
725 } else {
726 // Otherwise, if passing through "..." or to a function with no prototype,
727 // perform the "default argument promotions" (C99 6.5.2.2p6), which
728 // includes the usual unary conversions, but also promotes float to
729 // double.
730 if (const BuiltinType *BT =
731 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
732 if (BT->getKind() == BuiltinType::Float)
733 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
734 llvm::Type::DoubleTy,"tmp"));
735 }
736 }
737
Chris Lattner2b228c92007-06-15 21:34:29 +0000738 if (ArgVal.isScalar())
739 Args.push_back(ArgVal.getVal());
740 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000741 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000742 }
743
Chris Lattner7b9f04e2007-08-01 06:24:52 +0000744 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000745 if (V->getType() != llvm::Type::VoidTy)
746 V->setName("call");
Chris Lattner90d91202007-08-10 17:02:28 +0000747 else if (hasAggregateLLVMType(E->getType()))
748 // Struct return.
749 return RValue::getAggregate(Args[0]);
750
Chris Lattner2b228c92007-06-15 21:34:29 +0000751 return RValue::get(V);
752}
753
754
Chris Lattner8394d792007-06-05 20:53:16 +0000755//===----------------------------------------------------------------------===//
756// Unary Operator Emission
757//===----------------------------------------------------------------------===//
758
Chris Lattner8394d792007-06-05 20:53:16 +0000759RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000760 switch (E->getOpcode()) {
761 default:
762 printf("Unimplemented unary expr!\n");
763 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000764 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerdcca4872007-07-11 23:43:46 +0000765 case UnaryOperator::PostInc:
766 case UnaryOperator::PostDec:
767 case UnaryOperator::PreInc :
768 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
769 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
770 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
771 case UnaryOperator::Plus : return EmitUnaryPlus(E);
772 case UnaryOperator::Minus : return EmitUnaryMinus(E);
773 case UnaryOperator::Not : return EmitUnaryNot(E);
774 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000775 case UnaryOperator::SizeOf :
776 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
777 case UnaryOperator::AlignOf :
778 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Chris Lattner8394d792007-06-05 20:53:16 +0000779 // FIXME: real/imag
780 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000781 }
782}
783
Chris Lattnerdcca4872007-07-11 23:43:46 +0000784RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
785 LValue LV = EmitLValue(E->getSubExpr());
786 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
787
788 // We know the operand is real or pointer type, so it must be an LLVM scalar.
789 assert(InVal.isScalar() && "Unknown thing to increment");
790 llvm::Value *InV = InVal.getVal();
791
792 int AmountVal = 1;
793 if (E->getOpcode() == UnaryOperator::PreDec ||
794 E->getOpcode() == UnaryOperator::PostDec)
795 AmountVal = -1;
796
797 llvm::Value *NextVal;
798 if (isa<llvm::IntegerType>(InV->getType())) {
799 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
800 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
801 } else if (InV->getType()->isFloatingPoint()) {
802 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
803 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
804 } else {
805 // FIXME: This is not right for pointers to VLA types.
806 assert(isa<llvm::PointerType>(InV->getType()));
807 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
808 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
809 }
810
811 RValue NextValToStore = RValue::get(NextVal);
812
813 // Store the updated result through the lvalue.
814 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
815
816 // If this is a postinc, return the value read from memory, otherwise use the
817 // updated value.
818 if (E->getOpcode() == UnaryOperator::PreDec ||
819 E->getOpcode() == UnaryOperator::PreInc)
820 return NextValToStore;
821 else
822 return InVal;
823}
824
Chris Lattner8394d792007-06-05 20:53:16 +0000825/// C99 6.5.3.2
826RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
827 // The address of the operand is just its lvalue. It cannot be a bitfield.
828 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
829}
830
831RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000832 assert(E->getType().getCanonicalType() ==
833 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
834 // Unary plus just returns its value.
835 return EmitExpr(E->getSubExpr());
Chris Lattner8394d792007-06-05 20:53:16 +0000836}
837
838RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000839 assert(E->getType().getCanonicalType() ==
840 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
841
Chris Lattner8394d792007-06-05 20:53:16 +0000842 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000843 RValue V = EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000844
Chris Lattner8394d792007-06-05 20:53:16 +0000845 if (V.isScalar())
846 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
847
848 assert(0 && "FIXME: This doesn't handle complex operands yet");
849}
850
851RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
852 // Unary not performs promotions, then complements its integer operand.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000853 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner8394d792007-06-05 20:53:16 +0000854
855 if (V.isScalar())
856 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
857
858 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
859}
860
861
862/// C99 6.5.3.3
863RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
864 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000865 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000866
867 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000868 // TODO: Could dynamically modify easy computations here. For example, if
869 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000870 BoolVal = Builder.CreateNot(BoolVal, "lnot");
871
872 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000873 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000874}
875
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000876/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
877/// an integer (RetType).
878RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
879 QualType RetType, bool isSizeOf) {
880 /// FIXME: This doesn't handle VLAs yet!
881 std::pair<uint64_t, unsigned> Info =
882 getContext().getTypeInfo(TypeToSize, SourceLocation());
883
884 uint64_t Val = isSizeOf ? Info.first : Info.second;
885 Val /= 8; // Return size in bytes, not bits.
886
887 assert(RetType->isIntegerType() && "Result type must be an integer!");
888
889 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
890 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
891}
892
Chris Lattnere47e4402007-06-01 18:02:12 +0000893
Chris Lattnerdb91b162007-06-02 00:16:28 +0000894//===--------------------------------------------------------------------===//
895// Binary Operator Emission
896//===--------------------------------------------------------------------===//
897
Chris Lattnerdb91b162007-06-02 00:16:28 +0000898
Chris Lattnercd215f02007-06-29 16:52:55 +0000899/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
900/// are strange in that the result of the operation is not the same type as the
901/// intermediate computation. This function emits the LHS and RHS operands of
902/// the compound assignment, promoting them to their common computation type.
903///
904/// Since the LHS is an lvalue, and the result is stored back through it, we
905/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
906/// RHS values are both in the computation type for the operator.
907void CodeGenFunction::
908EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
909 LValue &LHSLV, RValue &LHS, RValue &RHS) {
910 LHSLV = EmitLValue(E->getLHS());
911
912 // Load the LHS and RHS operands.
913 QualType LHSTy = E->getLHS()->getType();
914 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000915 RHS = EmitExpr(E->getRHS());
916 QualType RHSTy = E->getRHS()->getType();
Chris Lattner47c247e2007-06-29 17:26:27 +0000917
Chris Lattnercd215f02007-06-29 16:52:55 +0000918 // Convert the LHS and RHS to the common evaluation type.
919 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
920 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
921}
922
923/// EmitCompoundAssignmentResult - Given a result value in the computation type,
924/// truncate it down to the actual result type, store it through the LHS lvalue,
925/// and return it.
926RValue CodeGenFunction::
927EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
928 LValue LHSLV, RValue ResV) {
929
930 // Truncate back to the destination type.
931 if (E->getComputationType() != E->getType())
932 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
933
934 // Store the result value into the LHS.
935 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
936
937 // Return the result.
938 return ResV;
939}
940
Chris Lattnerdb91b162007-06-02 00:16:28 +0000941
Chris Lattner8394d792007-06-05 20:53:16 +0000942RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000943 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000944 switch (E->getOpcode()) {
945 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000946 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000947 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000948 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerb25a9432007-06-29 17:03:06 +0000949 case BinaryOperator::Mul:
Chris Lattner87f48362007-08-08 17:49:18 +0000950 LHS = EmitExpr(E->getLHS());
951 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000952 return EmitMul(LHS, RHS, E->getType());
953 case BinaryOperator::Div:
Chris Lattner87f48362007-08-08 17:49:18 +0000954 LHS = EmitExpr(E->getLHS());
955 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000956 return EmitDiv(LHS, RHS, E->getType());
957 case BinaryOperator::Rem:
Chris Lattner87f48362007-08-08 17:49:18 +0000958 LHS = EmitExpr(E->getLHS());
959 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000960 return EmitRem(LHS, RHS, E->getType());
Chris Lattner87f48362007-08-08 17:49:18 +0000961 case BinaryOperator::Add:
962 LHS = EmitExpr(E->getLHS());
963 RHS = EmitExpr(E->getRHS());
964 if (!E->getType()->isPointerType())
965 return EmitAdd(LHS, RHS, E->getType());
966
967 return EmitPointerAdd(LHS, E->getLHS()->getType(),
968 RHS, E->getRHS()->getType(), E->getType());
969 case BinaryOperator::Sub:
970 LHS = EmitExpr(E->getLHS());
971 RHS = EmitExpr(E->getRHS());
972
973 if (!E->getLHS()->getType()->isPointerType())
974 return EmitSub(LHS, RHS, E->getType());
975
976 return EmitPointerSub(LHS, E->getLHS()->getType(),
977 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner47c247e2007-06-29 17:26:27 +0000978 case BinaryOperator::Shl:
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000979 LHS = EmitExpr(E->getLHS());
980 RHS = EmitExpr(E->getRHS());
Chris Lattner47c247e2007-06-29 17:26:27 +0000981 return EmitShl(LHS, RHS, E->getType());
982 case BinaryOperator::Shr:
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000983 LHS = EmitExpr(E->getLHS());
984 RHS = EmitExpr(E->getRHS());
Chris Lattner47c247e2007-06-29 17:26:27 +0000985 return EmitShr(LHS, RHS, E->getType());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000986 case BinaryOperator::And:
Chris Lattner87f48362007-08-08 17:49:18 +0000987 LHS = EmitExpr(E->getLHS());
988 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000989 return EmitAnd(LHS, RHS, E->getType());
990 case BinaryOperator::Xor:
Chris Lattner87f48362007-08-08 17:49:18 +0000991 LHS = EmitExpr(E->getLHS());
992 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000993 return EmitXor(LHS, RHS, E->getType());
994 case BinaryOperator::Or :
Chris Lattner87f48362007-08-08 17:49:18 +0000995 LHS = EmitExpr(E->getLHS());
996 RHS = EmitExpr(E->getRHS());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000997 return EmitOr(LHS, RHS, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000998 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
999 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +00001000 case BinaryOperator::LT:
1001 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1002 llvm::ICmpInst::ICMP_SLT,
1003 llvm::FCmpInst::FCMP_OLT);
1004 case BinaryOperator::GT:
1005 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1006 llvm::ICmpInst::ICMP_SGT,
1007 llvm::FCmpInst::FCMP_OGT);
1008 case BinaryOperator::LE:
1009 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1010 llvm::ICmpInst::ICMP_SLE,
1011 llvm::FCmpInst::FCMP_OLE);
1012 case BinaryOperator::GE:
1013 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1014 llvm::ICmpInst::ICMP_SGE,
1015 llvm::FCmpInst::FCMP_OGE);
1016 case BinaryOperator::EQ:
1017 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1018 llvm::ICmpInst::ICMP_EQ,
1019 llvm::FCmpInst::FCMP_OEQ);
1020 case BinaryOperator::NE:
1021 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1022 llvm::ICmpInst::ICMP_NE,
1023 llvm::FCmpInst::FCMP_UNE);
Chris Lattnercd215f02007-06-29 16:52:55 +00001024 case BinaryOperator::Assign:
1025 return EmitBinaryAssign(E);
1026
Chris Lattnerb25a9432007-06-29 17:03:06 +00001027 case BinaryOperator::MulAssign: {
1028 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1029 LValue LHSLV;
1030 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1031 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1032 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1033 }
1034 case BinaryOperator::DivAssign: {
1035 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1036 LValue LHSLV;
1037 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1038 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1039 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1040 }
1041 case BinaryOperator::RemAssign: {
1042 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1043 LValue LHSLV;
1044 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1045 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1046 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1047 }
Chris Lattnercd215f02007-06-29 16:52:55 +00001048 case BinaryOperator::AddAssign: {
1049 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1050 LValue LHSLV;
1051 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1052 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1053 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1054 }
1055 case BinaryOperator::SubAssign: {
1056 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1057 LValue LHSLV;
1058 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1059 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1060 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1061 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001062 case BinaryOperator::ShlAssign: {
1063 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1064 LValue LHSLV;
1065 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1066 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1067 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1068 }
1069 case BinaryOperator::ShrAssign: {
1070 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1071 LValue LHSLV;
1072 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1073 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1074 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1075 }
Chris Lattnerb25a9432007-06-29 17:03:06 +00001076 case BinaryOperator::AndAssign: {
1077 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1078 LValue LHSLV;
1079 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1080 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1081 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1082 }
1083 case BinaryOperator::OrAssign: {
1084 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1085 LValue LHSLV;
1086 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1087 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1088 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1089 }
1090 case BinaryOperator::XorAssign: {
1091 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1092 LValue LHSLV;
1093 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1094 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1095 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1096 }
Chris Lattner8394d792007-06-05 20:53:16 +00001097 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +00001098 }
1099}
1100
Chris Lattnerb25a9432007-06-29 17:03:06 +00001101RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner835635d2007-08-21 04:59:27 +00001102 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
Chris Lattner8394d792007-06-05 20:53:16 +00001103}
1104
Chris Lattnerb25a9432007-06-29 17:03:06 +00001105RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner6ce75df2007-08-21 16:34:16 +00001106 if (LHS.getVal()->getType()->isFloatingPoint())
1107 return RValue::get(Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div"));
1108 else if (ResTy->isUnsignedIntegerType())
1109 return RValue::get(Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div"));
1110 else
1111 return RValue::get(Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div"));
Chris Lattner8394d792007-06-05 20:53:16 +00001112}
1113
Chris Lattnerb25a9432007-06-29 17:03:06 +00001114RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner6ce75df2007-08-21 16:34:16 +00001115 // Rem in C can't be a floating point type: C99 6.5.5p2.
1116 if (ResTy->isUnsignedIntegerType())
1117 return RValue::get(Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem"));
1118 else
1119 return RValue::get(Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem"));
Chris Lattner8394d792007-06-05 20:53:16 +00001120}
1121
Chris Lattnercd215f02007-06-29 16:52:55 +00001122RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner835635d2007-08-21 04:59:27 +00001123 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattner8394d792007-06-05 20:53:16 +00001124}
1125
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001126RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1127 RValue RHS, QualType RHSTy,
1128 QualType ResTy) {
1129 llvm::Value *LHSValue = LHS.getVal();
1130 llvm::Value *RHSValue = RHS.getVal();
1131 if (LHSTy->isPointerType()) {
1132 // pointer + int
1133 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1134 } else {
1135 // int + pointer
1136 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1137 }
1138}
1139
Chris Lattnercd215f02007-06-29 16:52:55 +00001140RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner6ce75df2007-08-21 16:34:16 +00001141 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
Chris Lattner8394d792007-06-05 20:53:16 +00001142}
1143
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001144RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1145 RValue RHS, QualType RHSTy,
1146 QualType ResTy) {
1147 llvm::Value *LHSValue = LHS.getVal();
1148 llvm::Value *RHSValue = RHS.getVal();
1149 if (const PointerType *RHSPtrType =
1150 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1151 // pointer - pointer
1152 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1153 QualType LHSElementType = LHSPtrType->getPointeeType();
1154 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1155 "can't subtract pointers with differing element types");
Chris Lattner651f0e92007-07-16 05:43:05 +00001156 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattner4481b422007-07-14 01:29:45 +00001157 SourceLocation()) / 8;
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001158 const llvm::Type *ResultType = ConvertType(ResTy);
1159 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1160 "sub.ptr.lhs.cast");
1161 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1162 "sub.ptr.rhs.cast");
1163 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1164 "sub.ptr.sub");
Chris Lattner651f0e92007-07-16 05:43:05 +00001165
1166 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1167 // remainder. As such, we handle common power-of-two cases here to generate
1168 // better code.
1169 if (llvm::isPowerOf2_64(ElementSize)) {
1170 llvm::Value *ShAmt =
1171 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1172 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1173 } else {
1174 // Otherwise, do a full sdiv.
1175 llvm::Value *BytesPerElement =
1176 llvm::ConstantInt::get(ResultType, ElementSize);
1177 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1178 "sub.ptr.div"));
1179 }
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001180 } else {
1181 // pointer - int
1182 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1183 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1184 }
1185}
1186
Chris Lattner47c247e2007-06-29 17:26:27 +00001187RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1188 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1189
Chris Lattner8394d792007-06-05 20:53:16 +00001190 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1191 // RHS to the same size as the LHS.
1192 if (LHS->getType() != RHS->getType())
1193 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1194
1195 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1196}
1197
Chris Lattner47c247e2007-06-29 17:26:27 +00001198RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1199 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
Chris Lattner8394d792007-06-05 20:53:16 +00001200
1201 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1202 // RHS to the same size as the LHS.
1203 if (LHS->getType() != RHS->getType())
1204 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1205
Chris Lattner47c247e2007-06-29 17:26:27 +00001206 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001207 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1208 else
1209 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1210}
1211
Chris Lattner1fde0b32007-06-20 18:30:55 +00001212RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1213 unsigned UICmpOpc, unsigned SICmpOpc,
1214 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +00001215 llvm::Value *Result;
Chris Lattner96d72562007-08-21 16:57:55 +00001216 QualType LHSTy = E->getLHS()->getType();
1217 if (!LHSTy->isComplexType()) {
1218 RValue LHS = EmitExpr(E->getLHS());
1219 RValue RHS = EmitExpr(E->getRHS());
1220
1221 if (LHSTy->isRealFloatingType()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001222 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1223 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner96d72562007-08-21 16:57:55 +00001224 } else if (LHSTy->isUnsignedIntegerType()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001225 // FIXME: This check isn't right for "unsigned short < int" where ushort
1226 // promotes to int and does a signed compare.
1227 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1228 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001229 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001230 // Signed integers and pointers.
1231 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1232 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001233 }
1234 } else {
Chris Lattner96d72562007-08-21 16:57:55 +00001235 // Complex Comparison: can only be an equality comparison.
1236 ComplexPairTy LHS = EmitComplexExpr(E->getLHS());
1237 ComplexPairTy RHS = EmitComplexExpr(E->getRHS());
Gabor Greifd4606aa2007-07-13 23:33:18 +00001238
Chris Lattner96d72562007-08-21 16:57:55 +00001239 QualType CETy =
1240 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
1241
1242 llvm::Value *ResultR, *ResultI;
1243 if (CETy->isRealFloatingType()) {
1244 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1245 LHS.first, RHS.first, "cmp.r");
1246 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1247 LHS.second, RHS.second, "cmp.i");
Gabor Greifd4606aa2007-07-13 23:33:18 +00001248 } else {
Chris Lattnerbf1bd0d2007-08-21 17:03:38 +00001249 // Complex comparisons can only be equality comparisons. As such, signed
1250 // and unsigned opcodes are the same.
1251 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner96d72562007-08-21 16:57:55 +00001252 LHS.first, RHS.first, "cmp.r");
Chris Lattnerbf1bd0d2007-08-21 17:03:38 +00001253 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner96d72562007-08-21 16:57:55 +00001254 LHS.second, RHS.second, "cmp.i");
Gabor Greifd4606aa2007-07-13 23:33:18 +00001255 }
Chris Lattner96d72562007-08-21 16:57:55 +00001256
1257 if (E->getOpcode() == BinaryOperator::EQ) {
1258 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1259 } else {
1260 assert(E->getOpcode() == BinaryOperator::NE &&
1261 "Complex comparison other than == or != ?");
1262 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1263 }
Chris Lattner273c63d2007-06-20 18:02:30 +00001264 }
Gabor Greifd4606aa2007-07-13 23:33:18 +00001265
Chris Lattner273c63d2007-06-20 18:02:30 +00001266 // ZExt result to int.
1267 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1268}
1269
Chris Lattnerb25a9432007-06-29 17:03:06 +00001270RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner64be48f2007-08-21 17:12:50 +00001271 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
Chris Lattner8394d792007-06-05 20:53:16 +00001272}
1273
Chris Lattnerb25a9432007-06-29 17:03:06 +00001274RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner64be48f2007-08-21 17:12:50 +00001275 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
Chris Lattner8394d792007-06-05 20:53:16 +00001276}
1277
Chris Lattnerb25a9432007-06-29 17:03:06 +00001278RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner64be48f2007-08-21 17:12:50 +00001279 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
Chris Lattner8394d792007-06-05 20:53:16 +00001280}
1281
1282RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001283 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001284
Chris Lattner23b7eb62007-06-15 23:05:46 +00001285 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1286 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001287
Chris Lattner23b7eb62007-06-15 23:05:46 +00001288 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001289 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1290
1291 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001292 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001293
1294 // Reaquire the RHS block, as there may be subblocks inserted.
1295 RHSBlock = Builder.GetInsertBlock();
1296 EmitBlock(ContBlock);
1297
1298 // Create a PHI node. If we just evaluted the LHS condition, the result is
1299 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001300 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +00001301 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001302 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001303 PN->addIncoming(RHSCond, RHSBlock);
1304
1305 // ZExt result to int.
1306 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1307}
1308
1309RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001310 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001311
Chris Lattner23b7eb62007-06-15 23:05:46 +00001312 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1313 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001314
Chris Lattner23b7eb62007-06-15 23:05:46 +00001315 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001316 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1317
1318 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001319 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001320
1321 // Reaquire the RHS block, as there may be subblocks inserted.
1322 RHSBlock = Builder.GetInsertBlock();
1323 EmitBlock(ContBlock);
1324
1325 // Create a PHI node. If we just evaluted the LHS condition, the result is
1326 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001327 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +00001328 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001329 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001330 PN->addIncoming(RHSCond, RHSBlock);
1331
1332 // ZExt result to int.
1333 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1334}
1335
1336RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001337 assert(E->getLHS()->getType().getCanonicalType() ==
1338 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner8394d792007-06-05 20:53:16 +00001339 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001340 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001341
1342 // Store the value into the LHS.
1343 EmitStoreThroughLValue(RHS, LHS, E->getType());
Chris Lattner6278e6a2007-08-11 00:04:45 +00001344
1345 // Return the RHS.
Chris Lattner8394d792007-06-05 20:53:16 +00001346 return RHS;
1347}
1348
Chris Lattner9369a562007-06-29 16:31:29 +00001349
Chris Lattner8394d792007-06-05 20:53:16 +00001350RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
Chris Lattner3cf417b2007-08-21 17:15:50 +00001351 EmitStmt(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001352 return EmitExpr(E->getRHS());
1353}
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001354
1355RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1356 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1357 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1358 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1359
1360 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1361 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1362
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001363 EmitBlock(LHSBlock);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001364 // Handle the GNU extension for missing LHS.
1365 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001366 Builder.CreateBr(ContBlock);
1367 LHSBlock = Builder.GetInsertBlock();
1368
1369 EmitBlock(RHSBlock);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +00001370
1371 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001372 Builder.CreateBr(ContBlock);
1373 RHSBlock = Builder.GetInsertBlock();
1374
1375 const llvm::Type *LHSType = LHSValue->getType();
1376 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1377
1378 EmitBlock(ContBlock);
1379 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1380 PN->reserveOperandSpace(2);
1381 PN->addIncoming(LHSValue, LHSBlock);
1382 PN->addIncoming(RHSValue, RHSBlock);
1383
1384 return RValue::get(PN);
1385}