blob: 3a4e406c76dc841da632c62809590a9001d76c6f [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
Anders Carlsson49865302007-08-20 18:05:56 +000017#include "clang/Lex/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/Support/MathExtras.h"
23using namespace clang;
24using namespace CodeGen;
25
26//===--------------------------------------------------------------------===//
27// Miscellaneous Helper Methods
28//===--------------------------------------------------------------------===//
29
30/// 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}
36
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
39llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner5ac222c2007-08-24 00:01:20 +000040 return ConvertScalarValueToBool(EmitAnyExpr(E), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +000041}
42
Chris Lattner4b009652007-07-25 00:24:17 +000043//===--------------------------------------------------------------------===//
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,
50 QualType DstTy) {
51 ValTy = ValTy.getCanonicalType();
52 DstTy = DstTy.getCanonicalType();
53 if (ValTy == DstTy) return Val;
54
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));
59
Chris Lattner4e05d1e2007-08-26 06:48:56 +000060 if (Val.isScalar() && !hasAggregateLLVMType(DstTy))
61 return RValue::get(EmitScalarConversion(Val.getVal(), ValTy, DstTy));
Chris Lattner4b009652007-07-25 00:24:17 +000062
Chris Lattner4b009652007-07-25 00:24:17 +000063
64 assert(0 && "FIXME: We don't support complex conversions yet!");
65}
66
67
68/// ConvertScalarValueToBool - Convert the specified expression value to a
69/// boolean (i1) truth value. This is equivalent to "Val == 0".
70llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
71 Ty = Ty.getCanonicalType();
72 llvm::Value *Result;
73 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
74 switch (BT->getKind()) {
75 default: assert(0 && "Unknown scalar value");
76 case BuiltinType::Bool:
77 Result = Val.getVal();
78 // Bool is already evaluated right.
79 assert(Result->getType() == llvm::Type::Int1Ty &&
80 "Unexpected bool value type!");
81 return Result;
82 case BuiltinType::Char_S:
83 case BuiltinType::Char_U:
84 case BuiltinType::SChar:
85 case BuiltinType::UChar:
86 case BuiltinType::Short:
87 case BuiltinType::UShort:
88 case BuiltinType::Int:
89 case BuiltinType::UInt:
90 case BuiltinType::Long:
91 case BuiltinType::ULong:
92 case BuiltinType::LongLong:
93 case BuiltinType::ULongLong:
94 // Code below handles simple integers.
95 break;
96 case BuiltinType::Float:
97 case BuiltinType::Double:
98 case BuiltinType::LongDouble: {
99 // Compare against 0.0 for fp scalars.
100 Result = Val.getVal();
101 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
102 // FIXME: llvm-gcc produces a une comparison: validate this is right.
103 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
104 return Result;
105 }
106 }
Chris Lattner5ac222c2007-08-24 00:01:20 +0000107 } else if (isa<ComplexType>(Ty)) {
108 assert(0 && "implement complex -> bool");
109
Chris Lattner4b009652007-07-25 00:24:17 +0000110 } else {
Chris Lattner5ac222c2007-08-24 00:01:20 +0000111 assert((isa<PointerType>(Ty) ||
112 (isa<TagType>(Ty) &&
113 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum)) &&
114 "Unknown Type");
115 // Code below handles this case fine.
Chris Lattner4b009652007-07-25 00:24:17 +0000116 }
117
118 // Usual case for integers, pointers, and enums: compare against zero.
119 Result = Val.getVal();
120
121 // Because of the type rules of C, we often end up computing a logical value,
122 // then zero extending it to int, then wanting it as a logical value again.
123 // Optimize this common case.
124 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
125 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
126 Result = ZI->getOperand(0);
127 ZI->eraseFromParent();
128 return Result;
129 }
130 }
131
132 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
133 return Builder.CreateICmpNE(Result, Zero, "tobool");
134}
135
136//===----------------------------------------------------------------------===//
137// LValue Expression Emission
138//===----------------------------------------------------------------------===//
139
140/// EmitLValue - Emit code to compute a designator that specifies the location
141/// of the expression.
142///
143/// This can return one of two things: a simple address or a bitfield
144/// reference. In either case, the LLVM Value* in the LValue structure is
145/// guaranteed to be an LLVM pointer type.
146///
147/// If this returns a bitfield reference, nothing about the pointee type of
148/// the LLVM value is known: For example, it may not be a pointer to an
149/// integer.
150///
151/// If this returns a normal address, and if the lvalue's C type is fixed
152/// size, this method guarantees that the returned pointer type will point to
153/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
154/// variable length type, this is not possible.
155///
156LValue CodeGenFunction::EmitLValue(const Expr *E) {
157 switch (E->getStmtClass()) {
Chris Lattnera52c8892007-08-26 05:06:40 +0000158 default: {
Chris Lattner4b009652007-07-25 00:24:17 +0000159 fprintf(stderr, "Unimplemented lvalue expr!\n");
160 E->dump();
Chris Lattnera52c8892007-08-26 05:06:40 +0000161 llvm::Type *Ty = llvm::PointerType::get(ConvertType(E->getType()));
162 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
163 }
Chris Lattner4b009652007-07-25 00:24:17 +0000164
165 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
166 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
167 case Expr::PreDefinedExprClass:
168 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
169 case Expr::StringLiteralClass:
170 return EmitStringLiteralLValue(cast<StringLiteral>(E));
171
172 case Expr::UnaryOperatorClass:
173 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
174 case Expr::ArraySubscriptExprClass:
175 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000176 case Expr::OCUVectorElementExprClass:
177 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179}
180
181/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
182/// this method emits the address of the lvalue, then loads the result as an
183/// rvalue, returning the rvalue.
184RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000185 if (LV.isSimple()) {
186 llvm::Value *Ptr = LV.getAddress();
187 const llvm::Type *EltTy =
188 cast<llvm::PointerType>(Ptr->getType())->getElementType();
189
190 // Simple scalar l-value.
191 if (EltTy->isFirstClassType())
192 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
193
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000194 assert(ExprType->isFunctionType() && "Unknown scalar value");
195 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000196 }
197
198 if (LV.isVectorElt()) {
199 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
200 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
201 "vecext"));
202 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000203
204 // If this is a reference to a subset of the elements of a vector, either
205 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000206 if (LV.isOCUVectorElt())
207 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000208
209 assert(0 && "Bitfield ref not impl!");
210}
211
Chris Lattner944f7962007-08-03 16:18:34 +0000212// If this is a reference to a subset of the elements of a vector, either
213// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000214RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000215 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000216 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
217
Chris Lattnera0d03a72007-08-03 17:31:20 +0000218 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000219
220 // If the result of the expression is a non-vector type, we must be
221 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000222 const VectorType *ExprVT = ExprType->getAsVectorType();
223 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000224 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000225 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
226 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
227 }
228
229 // If the source and destination have the same number of elements, use a
230 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000231 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000232 unsigned NumSourceElts =
233 cast<llvm::VectorType>(Vec->getType())->getNumElements();
234
235 if (NumResultElts == NumSourceElts) {
236 llvm::SmallVector<llvm::Constant*, 4> Mask;
237 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000238 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000239 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
240 }
241
242 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
243 Vec = Builder.CreateShuffleVector(Vec,
244 llvm::UndefValue::get(Vec->getType()),
245 MaskV, "tmp");
246 return RValue::get(Vec);
247 }
248
249 // Start out with an undef of the result type.
250 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
251
252 // Extract/Insert each element of the result.
253 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000254 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000255 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
256 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
257
258 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
259 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
260 }
261
262 return RValue::get(Result);
263}
264
265
Chris Lattner4b009652007-07-25 00:24:17 +0000266RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
267 return EmitLoadOfLValue(EmitLValue(E), E->getType());
268}
269
270
271/// EmitStoreThroughLValue - Store the specified rvalue into the specified
272/// lvalue, where both are guaranteed to the have the same type, and that type
273/// is 'Ty'.
274void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
275 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000276 if (!Dst.isSimple()) {
277 if (Dst.isVectorElt()) {
278 // Read/modify/write the vector, inserting the new element.
279 // FIXME: Volatility.
280 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
281 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
282 Dst.getVectorIdx(), "vecins");
283 Builder.CreateStore(Vec, Dst.getVectorAddr());
284 return;
285 }
Chris Lattner4b009652007-07-25 00:24:17 +0000286
Chris Lattner5bfdd232007-08-03 16:28:33 +0000287 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000288 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000289 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
290
291 assert(0 && "FIXME: Don't support store to bitfield yet");
292 }
Chris Lattner4b009652007-07-25 00:24:17 +0000293
294 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000295 assert(Src.isScalar() && "Can't emit an agg store with this method");
296 // FIXME: Handle volatility etc.
297 const llvm::Type *SrcTy = Src.getVal()->getType();
298 const llvm::Type *AddrTy =
299 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner4b009652007-07-25 00:24:17 +0000300
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000301 if (AddrTy != SrcTy)
302 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
303 "storetmp");
304 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000305}
306
Chris Lattner5bfdd232007-08-03 16:28:33 +0000307void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
308 QualType Ty) {
309 // This access turns into a read/modify/write of the vector. Load the input
310 // value now.
311 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
312 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000313 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000314
315 llvm::Value *SrcVal = Src.getVal();
316
Chris Lattner940966d2007-08-03 16:37:04 +0000317 if (const VectorType *VTy = Ty->getAsVectorType()) {
318 unsigned NumSrcElts = VTy->getNumElements();
319
320 // Extract/Insert each element.
321 for (unsigned i = 0; i != NumSrcElts; ++i) {
322 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
323 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
324
Chris Lattnera0d03a72007-08-03 17:31:20 +0000325 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000326 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
327 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
328 }
329 } else {
330 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000331 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000332 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
333 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000334 }
335
Chris Lattner5bfdd232007-08-03 16:28:33 +0000336 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
337}
338
Chris Lattner4b009652007-07-25 00:24:17 +0000339
340LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
341 const Decl *D = E->getDecl();
342 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
343 llvm::Value *V = LocalDeclMap[D];
344 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
345 return LValue::MakeAddr(V);
346 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
347 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
348 }
349 assert(0 && "Unimp declref");
350}
351
352LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
353 // __extension__ doesn't affect lvalue-ness.
354 if (E->getOpcode() == UnaryOperator::Extension)
355 return EmitLValue(E->getSubExpr());
356
357 assert(E->getOpcode() == UnaryOperator::Deref &&
358 "'*' is the only unary operator that produces an lvalue");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000359 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
Chris Lattner4b009652007-07-25 00:24:17 +0000360}
361
362LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
363 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
364 const char *StrData = E->getStrData();
365 unsigned Len = E->getByteLength();
366
367 // FIXME: Can cache/reuse these within the module.
368 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
369
370 // Create a global variable for this.
371 C = new llvm::GlobalVariable(C->getType(), true,
372 llvm::GlobalValue::InternalLinkage,
373 C, ".str", CurFn->getParent());
374 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
375 llvm::Constant *Zeros[] = { Zero, Zero };
376 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
377 return LValue::MakeAddr(C);
378}
379
380LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
381 std::string FunctionName(CurFuncDecl->getName());
382 std::string GlobalVarName;
383
384 switch (E->getIdentType()) {
385 default:
386 assert(0 && "unknown pre-defined ident type");
387 case PreDefinedExpr::Func:
388 GlobalVarName = "__func__.";
389 break;
390 case PreDefinedExpr::Function:
391 GlobalVarName = "__FUNCTION__.";
392 break;
393 case PreDefinedExpr::PrettyFunction:
394 // FIXME:: Demangle C++ method names
395 GlobalVarName = "__PRETTY_FUNCTION__.";
396 break;
397 }
398
399 GlobalVarName += CurFuncDecl->getName();
400
401 // FIXME: Can cache/reuse these within the module.
402 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
403
404 // Create a global variable for this.
405 C = new llvm::GlobalVariable(C->getType(), true,
406 llvm::GlobalValue::InternalLinkage,
407 C, GlobalVarName, CurFn->getParent());
408 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
409 llvm::Constant *Zeros[] = { Zero, Zero };
410 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
411 return LValue::MakeAddr(C);
412}
413
414LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000415 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000416 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattner4b009652007-07-25 00:24:17 +0000417
418 // If the base is a vector type, then we are forming a vector element lvalue
419 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000420 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000421 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000422 LValue LHS = EmitLValue(E->getLHS());
423 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000424 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000425 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000426 }
427
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000428 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000429 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +0000430
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000431 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000432 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000433 bool IdxSigned = IdxTy->isSignedIntegerType();
434 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
435 if (IdxBitwidth != LLVMPointerWidth)
436 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
437 IdxSigned, "idxprom");
438
439 // We know that the pointer points to a type of the correct size, unless the
440 // size is a VLA.
441 if (!E->getType()->isConstantSizeType(getContext()))
442 assert(0 && "VLA idx not implemented");
443 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
444}
445
Chris Lattner65520192007-08-02 23:37:31 +0000446LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000447EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000448 // Emit the base vector as an l-value.
449 LValue Base = EmitLValue(E->getBase());
450 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
451
Chris Lattnera0d03a72007-08-03 17:31:20 +0000452 return LValue::MakeOCUVectorElt(Base.getAddress(),
453 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000454}
455
Chris Lattner4b009652007-07-25 00:24:17 +0000456//===--------------------------------------------------------------------===//
457// Expression Emission
458//===--------------------------------------------------------------------===//
459
Chris Lattner348c8a22007-08-23 23:43:33 +0000460/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
461/// returning an rvalue corresponding to it. If NeedResult is false, the
462/// result of the expression doesn't need to be generated into memory.
463RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
464 if (!hasAggregateLLVMType(E->getType()))
Chris Lattner9fba49a2007-08-24 05:35:26 +0000465 return RValue::get(EmitScalarExpr(E));
Chris Lattner348c8a22007-08-23 23:43:33 +0000466
467 llvm::Value *DestMem = 0;
468 if (NeedResult)
469 DestMem = CreateTempAlloca(ConvertType(E->getType()));
470
471 if (!E->getType()->isComplexType()) {
472 EmitAggExpr(E, DestMem, false);
473 } else if (NeedResult)
474 EmitComplexExprIntoAddr(E, DestMem);
475 else
476 EmitComplexExpr(E);
477
478 return RValue::getAggregate(DestMem);
479}
480
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000481
Chris Lattner4b009652007-07-25 00:24:17 +0000482RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000483 if (const ImplicitCastExpr *IcExpr =
484 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
485 if (const DeclRefExpr *DRExpr =
486 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
487 if (const FunctionDecl *FDecl =
488 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
489 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
490 return EmitBuiltinExpr(builtinID, E);
491
Chris Lattner9fba49a2007-08-24 05:35:26 +0000492 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Chris Lattner4b009652007-07-25 00:24:17 +0000493
494 // The callee type will always be a pointer to function type, get the function
495 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000496 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000497 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
498
499 // Get information about the argument types.
500 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
501
502 // Calling unprototyped functions provides no argument info.
503 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
504 ArgTyIt = FTP->arg_type_begin();
505 ArgTyEnd = FTP->arg_type_end();
506 }
507
508 llvm::SmallVector<llvm::Value*, 16> Args;
509
Chris Lattner59802042007-08-10 17:02:28 +0000510 // Handle struct-return functions by passing a pointer to the location that
511 // we would like to return into.
512 if (hasAggregateLLVMType(E->getType())) {
513 // Create a temporary alloca to hold the result of the call. :(
514 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
515 // FIXME: set the stret attribute on the argument.
516 }
517
Chris Lattner4b009652007-07-25 00:24:17 +0000518 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000519 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner348c8a22007-08-23 23:43:33 +0000520 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000521
522 // If this argument has prototype information, convert it.
523 if (ArgTyIt != ArgTyEnd) {
524 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
525 } else {
526 // Otherwise, if passing through "..." or to a function with no prototype,
527 // perform the "default argument promotions" (C99 6.5.2.2p6), which
528 // includes the usual unary conversions, but also promotes float to
529 // double.
530 if (const BuiltinType *BT =
531 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
532 if (BT->getKind() == BuiltinType::Float)
533 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
534 llvm::Type::DoubleTy,"tmp"));
535 }
536 }
537
Chris Lattner4b009652007-07-25 00:24:17 +0000538 if (ArgVal.isScalar())
539 Args.push_back(ArgVal.getVal());
540 else // Pass by-address. FIXME: Set attribute bit on call.
541 Args.push_back(ArgVal.getAggregateAddr());
542 }
543
Chris Lattnera9572252007-08-01 06:24:52 +0000544 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000545 if (V->getType() != llvm::Type::VoidTy)
546 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000547 else if (hasAggregateLLVMType(E->getType()))
548 // Struct return.
549 return RValue::getAggregate(Args[0]);
550
Chris Lattner4b009652007-07-25 00:24:17 +0000551 return RValue::get(V);
552}