blob: 645777f4ea632da17d7be297a92af305effbe7cd [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 Lattner2da04b32007-08-24 05:35:26 +0000414 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
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 Lattner2da04b32007-08-24 05:35:26 +0000471 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
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 Lattner2da04b32007-08-24 05:35:26 +0000484 llvm::Value *Base = EmitScalarExpr(E->getBase());
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()))
Chris Lattner2da04b32007-08-24 05:35:26 +0000520 return RValue::get(EmitScalarExpr(E));
Chris Lattner08b15df2007-08-23 23:43:33 +0000521
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 Lattner76ba8492007-08-20 22:37:10 +0000536
Chris Lattner2b228c92007-06-15 21:34:29 +0000537RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson1d8e5212007-08-20 18:05:56 +0000538 if (const ImplicitCastExpr *IcExpr =
539 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
540 if (const DeclRefExpr *DRExpr =
541 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
542 if (const FunctionDecl *FDecl =
543 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
544 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
545 return EmitBuiltinExpr(builtinID, E);
546
Chris Lattner2da04b32007-08-24 05:35:26 +0000547 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Chris Lattnerc14236b2007-07-10 22:18:37 +0000548
549 // The callee type will always be a pointer to function type, get the function
550 // type.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000551 QualType CalleeTy = E->getCallee()->getType();
Chris Lattnerc14236b2007-07-10 22:18:37 +0000552 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
553
554 // Get information about the argument types.
555 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
556
557 // Calling unprototyped functions provides no argument info.
558 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
559 ArgTyIt = FTP->arg_type_begin();
560 ArgTyEnd = FTP->arg_type_end();
561 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000562
Chris Lattner23b7eb62007-06-15 23:05:46 +0000563 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000564
Chris Lattner90d91202007-08-10 17:02:28 +0000565 // Handle struct-return functions by passing a pointer to the location that
566 // we would like to return into.
567 if (hasAggregateLLVMType(E->getType())) {
568 // Create a temporary alloca to hold the result of the call. :(
569 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
570 // FIXME: set the stret attribute on the argument.
571 }
572
Chris Lattner2b228c92007-06-15 21:34:29 +0000573 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000574 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner08b15df2007-08-23 23:43:33 +0000575 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattnerc14236b2007-07-10 22:18:37 +0000576
577 // If this argument has prototype information, convert it.
578 if (ArgTyIt != ArgTyEnd) {
579 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
580 } else {
581 // Otherwise, if passing through "..." or to a function with no prototype,
582 // perform the "default argument promotions" (C99 6.5.2.2p6), which
583 // includes the usual unary conversions, but also promotes float to
584 // double.
585 if (const BuiltinType *BT =
586 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
587 if (BT->getKind() == BuiltinType::Float)
588 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
589 llvm::Type::DoubleTy,"tmp"));
590 }
591 }
592
Chris Lattner2b228c92007-06-15 21:34:29 +0000593 if (ArgVal.isScalar())
594 Args.push_back(ArgVal.getVal());
595 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000596 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000597 }
598
Chris Lattner7b9f04e2007-08-01 06:24:52 +0000599 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000600 if (V->getType() != llvm::Type::VoidTy)
601 V->setName("call");
Chris Lattner90d91202007-08-10 17:02:28 +0000602 else if (hasAggregateLLVMType(E->getType()))
603 // Struct return.
604 return RValue::getAggregate(Args[0]);
605
Chris Lattner2b228c92007-06-15 21:34:29 +0000606 return RValue::get(V);
607}
608
609
Chris Lattner8394d792007-06-05 20:53:16 +0000610//===----------------------------------------------------------------------===//
611// Unary Operator Emission
612//===----------------------------------------------------------------------===//
613
Chris Lattner2da04b32007-08-24 05:35:26 +0000614#if 0
Chris Lattnerdb91b162007-06-02 00:16:28 +0000615
Chris Lattnercd215f02007-06-29 16:52:55 +0000616/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
617/// are strange in that the result of the operation is not the same type as the
618/// intermediate computation. This function emits the LHS and RHS operands of
619/// the compound assignment, promoting them to their common computation type.
620///
621/// Since the LHS is an lvalue, and the result is stored back through it, we
622/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
623/// RHS values are both in the computation type for the operator.
624void CodeGenFunction::
625EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
626 LValue &LHSLV, RValue &LHS, RValue &RHS) {
627 LHSLV = EmitLValue(E->getLHS());
628
629 // Load the LHS and RHS operands.
630 QualType LHSTy = E->getLHS()->getType();
631 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000632 RHS = EmitExpr(E->getRHS());
633 QualType RHSTy = E->getRHS()->getType();
Chris Lattner47c247e2007-06-29 17:26:27 +0000634
Chris Lattnercd215f02007-06-29 16:52:55 +0000635 // Convert the LHS and RHS to the common evaluation type.
636 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
637 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
638}
639
640/// EmitCompoundAssignmentResult - Given a result value in the computation type,
641/// truncate it down to the actual result type, store it through the LHS lvalue,
642/// and return it.
643RValue CodeGenFunction::
644EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
645 LValue LHSLV, RValue ResV) {
646
647 // Truncate back to the destination type.
648 if (E->getComputationType() != E->getType())
649 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
650
651 // Store the result value into the LHS.
652 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
653
654 // Return the result.
655 return ResV;
656}
657
Chris Lattnerdb91b162007-06-02 00:16:28 +0000658
Chris Lattner8394d792007-06-05 20:53:16 +0000659RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000660 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000661 switch (E->getOpcode()) {
662 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000663 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000664 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000665 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattner87f48362007-08-08 17:49:18 +0000666 case BinaryOperator::Add:
667 LHS = EmitExpr(E->getLHS());
668 RHS = EmitExpr(E->getRHS());
669 if (!E->getType()->isPointerType())
670 return EmitAdd(LHS, RHS, E->getType());
671
672 return EmitPointerAdd(LHS, E->getLHS()->getType(),
673 RHS, E->getRHS()->getType(), E->getType());
Chris Lattnercd215f02007-06-29 16:52:55 +0000674 case BinaryOperator::Assign:
675 return EmitBinaryAssign(E);
676
Chris Lattnerb25a9432007-06-29 17:03:06 +0000677 case BinaryOperator::MulAssign: {
678 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
679 LValue LHSLV;
680 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
681 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
682 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
683 }
684 case BinaryOperator::DivAssign: {
685 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
686 LValue LHSLV;
687 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
688 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
689 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
690 }
691 case BinaryOperator::RemAssign: {
692 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
693 LValue LHSLV;
694 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
695 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
696 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
697 }
Chris Lattnercd215f02007-06-29 16:52:55 +0000698 case BinaryOperator::AddAssign: {
699 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
700 LValue LHSLV;
701 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
702 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
703 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
704 }
705 case BinaryOperator::SubAssign: {
706 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
707 LValue LHSLV;
708 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
709 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
710 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
711 }
Chris Lattnerdb91b162007-06-02 00:16:28 +0000712 }
713}
714
Chris Lattner8394d792007-06-05 20:53:16 +0000715
Chris Lattner2da04b32007-08-24 05:35:26 +0000716#endif