blob: 71674e02632fe51327a8baf0871524930e54c435 [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
Chris Lattner4b009652007-07-25 00:24:17 +000047/// ConvertScalarValueToBool - Convert the specified expression value to a
48/// boolean (i1) truth value. This is equivalent to "Val == 0".
49llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
50 Ty = Ty.getCanonicalType();
51 llvm::Value *Result;
52 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
53 switch (BT->getKind()) {
54 default: assert(0 && "Unknown scalar value");
55 case BuiltinType::Bool:
56 Result = Val.getVal();
57 // Bool is already evaluated right.
58 assert(Result->getType() == llvm::Type::Int1Ty &&
59 "Unexpected bool value type!");
60 return Result;
61 case BuiltinType::Char_S:
62 case BuiltinType::Char_U:
63 case BuiltinType::SChar:
64 case BuiltinType::UChar:
65 case BuiltinType::Short:
66 case BuiltinType::UShort:
67 case BuiltinType::Int:
68 case BuiltinType::UInt:
69 case BuiltinType::Long:
70 case BuiltinType::ULong:
71 case BuiltinType::LongLong:
72 case BuiltinType::ULongLong:
73 // Code below handles simple integers.
74 break;
75 case BuiltinType::Float:
76 case BuiltinType::Double:
77 case BuiltinType::LongDouble: {
78 // Compare against 0.0 for fp scalars.
79 Result = Val.getVal();
80 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
81 // FIXME: llvm-gcc produces a une comparison: validate this is right.
82 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
83 return Result;
84 }
85 }
Chris Lattner5ac222c2007-08-24 00:01:20 +000086 } else if (isa<ComplexType>(Ty)) {
87 assert(0 && "implement complex -> bool");
88
Chris Lattner4b009652007-07-25 00:24:17 +000089 } else {
Chris Lattner5ac222c2007-08-24 00:01:20 +000090 assert((isa<PointerType>(Ty) ||
91 (isa<TagType>(Ty) &&
92 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum)) &&
93 "Unknown Type");
94 // Code below handles this case fine.
Chris Lattner4b009652007-07-25 00:24:17 +000095 }
96
97 // Usual case for integers, pointers, and enums: compare against zero.
98 Result = Val.getVal();
99
100 // Because of the type rules of C, we often end up computing a logical value,
101 // then zero extending it to int, then wanting it as a logical value again.
102 // Optimize this common case.
103 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
104 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
105 Result = ZI->getOperand(0);
106 ZI->eraseFromParent();
107 return Result;
108 }
109 }
110
111 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
112 return Builder.CreateICmpNE(Result, Zero, "tobool");
113}
114
115//===----------------------------------------------------------------------===//
116// LValue Expression Emission
117//===----------------------------------------------------------------------===//
118
119/// EmitLValue - Emit code to compute a designator that specifies the location
120/// of the expression.
121///
122/// This can return one of two things: a simple address or a bitfield
123/// reference. In either case, the LLVM Value* in the LValue structure is
124/// guaranteed to be an LLVM pointer type.
125///
126/// If this returns a bitfield reference, nothing about the pointee type of
127/// the LLVM value is known: For example, it may not be a pointer to an
128/// integer.
129///
130/// If this returns a normal address, and if the lvalue's C type is fixed
131/// size, this method guarantees that the returned pointer type will point to
132/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
133/// variable length type, this is not possible.
134///
135LValue CodeGenFunction::EmitLValue(const Expr *E) {
136 switch (E->getStmtClass()) {
Chris Lattnera52c8892007-08-26 05:06:40 +0000137 default: {
Chris Lattner4b009652007-07-25 00:24:17 +0000138 fprintf(stderr, "Unimplemented lvalue expr!\n");
139 E->dump();
Chris Lattnera52c8892007-08-26 05:06:40 +0000140 llvm::Type *Ty = llvm::PointerType::get(ConvertType(E->getType()));
141 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
142 }
Chris Lattner4b009652007-07-25 00:24:17 +0000143
144 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
145 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
146 case Expr::PreDefinedExprClass:
147 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
148 case Expr::StringLiteralClass:
149 return EmitStringLiteralLValue(cast<StringLiteral>(E));
150
151 case Expr::UnaryOperatorClass:
152 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
153 case Expr::ArraySubscriptExprClass:
154 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000155 case Expr::OCUVectorElementExprClass:
156 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000157 }
158}
159
160/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
161/// this method emits the address of the lvalue, then loads the result as an
162/// rvalue, returning the rvalue.
163RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000164 if (LV.isSimple()) {
165 llvm::Value *Ptr = LV.getAddress();
166 const llvm::Type *EltTy =
167 cast<llvm::PointerType>(Ptr->getType())->getElementType();
168
169 // Simple scalar l-value.
170 if (EltTy->isFirstClassType())
171 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
172
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000173 assert(ExprType->isFunctionType() && "Unknown scalar value");
174 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000175 }
176
177 if (LV.isVectorElt()) {
178 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
179 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
180 "vecext"));
181 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000182
183 // If this is a reference to a subset of the elements of a vector, either
184 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000185 if (LV.isOCUVectorElt())
186 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000187
188 assert(0 && "Bitfield ref not impl!");
189}
190
Chris Lattner944f7962007-08-03 16:18:34 +0000191// If this is a reference to a subset of the elements of a vector, either
192// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000193RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000194 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000195 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
196
Chris Lattnera0d03a72007-08-03 17:31:20 +0000197 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000198
199 // If the result of the expression is a non-vector type, we must be
200 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000201 const VectorType *ExprVT = ExprType->getAsVectorType();
202 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000203 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000204 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
205 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
206 }
207
208 // If the source and destination have the same number of elements, use a
209 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000210 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000211 unsigned NumSourceElts =
212 cast<llvm::VectorType>(Vec->getType())->getNumElements();
213
214 if (NumResultElts == NumSourceElts) {
215 llvm::SmallVector<llvm::Constant*, 4> Mask;
216 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000217 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000218 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
219 }
220
221 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
222 Vec = Builder.CreateShuffleVector(Vec,
223 llvm::UndefValue::get(Vec->getType()),
224 MaskV, "tmp");
225 return RValue::get(Vec);
226 }
227
228 // Start out with an undef of the result type.
229 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
230
231 // Extract/Insert each element of the result.
232 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000233 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000234 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
235 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
236
237 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
238 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
239 }
240
241 return RValue::get(Result);
242}
243
244
Chris Lattner4b009652007-07-25 00:24:17 +0000245RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
246 return EmitLoadOfLValue(EmitLValue(E), E->getType());
247}
248
249
250/// EmitStoreThroughLValue - Store the specified rvalue into the specified
251/// lvalue, where both are guaranteed to the have the same type, and that type
252/// is 'Ty'.
253void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
254 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000255 if (!Dst.isSimple()) {
256 if (Dst.isVectorElt()) {
257 // Read/modify/write the vector, inserting the new element.
258 // FIXME: Volatility.
259 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
260 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
261 Dst.getVectorIdx(), "vecins");
262 Builder.CreateStore(Vec, Dst.getVectorAddr());
263 return;
264 }
Chris Lattner4b009652007-07-25 00:24:17 +0000265
Chris Lattner5bfdd232007-08-03 16:28:33 +0000266 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000267 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000268 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
269
270 assert(0 && "FIXME: Don't support store to bitfield yet");
271 }
Chris Lattner4b009652007-07-25 00:24:17 +0000272
273 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000274 assert(Src.isScalar() && "Can't emit an agg store with this method");
275 // FIXME: Handle volatility etc.
276 const llvm::Type *SrcTy = Src.getVal()->getType();
277 const llvm::Type *AddrTy =
278 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner4b009652007-07-25 00:24:17 +0000279
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000280 if (AddrTy != SrcTy)
281 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
282 "storetmp");
283 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000284}
285
Chris Lattner5bfdd232007-08-03 16:28:33 +0000286void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
287 QualType Ty) {
288 // This access turns into a read/modify/write of the vector. Load the input
289 // value now.
290 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
291 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000292 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000293
294 llvm::Value *SrcVal = Src.getVal();
295
Chris Lattner940966d2007-08-03 16:37:04 +0000296 if (const VectorType *VTy = Ty->getAsVectorType()) {
297 unsigned NumSrcElts = VTy->getNumElements();
298
299 // Extract/Insert each element.
300 for (unsigned i = 0; i != NumSrcElts; ++i) {
301 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
302 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
303
Chris Lattnera0d03a72007-08-03 17:31:20 +0000304 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000305 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
306 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
307 }
308 } else {
309 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000310 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000311 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
312 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000313 }
314
Chris Lattner5bfdd232007-08-03 16:28:33 +0000315 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
316}
317
Chris Lattner4b009652007-07-25 00:24:17 +0000318
319LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
320 const Decl *D = E->getDecl();
321 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
322 llvm::Value *V = LocalDeclMap[D];
323 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
324 return LValue::MakeAddr(V);
325 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
326 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
327 }
328 assert(0 && "Unimp declref");
329}
330
331LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
332 // __extension__ doesn't affect lvalue-ness.
333 if (E->getOpcode() == UnaryOperator::Extension)
334 return EmitLValue(E->getSubExpr());
335
336 assert(E->getOpcode() == UnaryOperator::Deref &&
337 "'*' is the only unary operator that produces an lvalue");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000338 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
Chris Lattner4b009652007-07-25 00:24:17 +0000339}
340
341LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
342 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
343 const char *StrData = E->getStrData();
344 unsigned Len = E->getByteLength();
345
346 // FIXME: Can cache/reuse these within the module.
347 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
348
349 // Create a global variable for this.
350 C = new llvm::GlobalVariable(C->getType(), true,
351 llvm::GlobalValue::InternalLinkage,
352 C, ".str", CurFn->getParent());
353 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
354 llvm::Constant *Zeros[] = { Zero, Zero };
355 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
356 return LValue::MakeAddr(C);
357}
358
359LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
360 std::string FunctionName(CurFuncDecl->getName());
361 std::string GlobalVarName;
362
363 switch (E->getIdentType()) {
364 default:
365 assert(0 && "unknown pre-defined ident type");
366 case PreDefinedExpr::Func:
367 GlobalVarName = "__func__.";
368 break;
369 case PreDefinedExpr::Function:
370 GlobalVarName = "__FUNCTION__.";
371 break;
372 case PreDefinedExpr::PrettyFunction:
373 // FIXME:: Demangle C++ method names
374 GlobalVarName = "__PRETTY_FUNCTION__.";
375 break;
376 }
377
378 GlobalVarName += CurFuncDecl->getName();
379
380 // FIXME: Can cache/reuse these within the module.
381 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
382
383 // Create a global variable for this.
384 C = new llvm::GlobalVariable(C->getType(), true,
385 llvm::GlobalValue::InternalLinkage,
386 C, GlobalVarName, CurFn->getParent());
387 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
388 llvm::Constant *Zeros[] = { Zero, Zero };
389 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
390 return LValue::MakeAddr(C);
391}
392
393LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000394 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000395 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattner4b009652007-07-25 00:24:17 +0000396
397 // If the base is a vector type, then we are forming a vector element lvalue
398 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000399 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000401 LValue LHS = EmitLValue(E->getLHS());
402 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000403 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000404 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000405 }
406
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000407 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000408 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +0000409
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000410 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000411 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000412 bool IdxSigned = IdxTy->isSignedIntegerType();
413 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
414 if (IdxBitwidth != LLVMPointerWidth)
415 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
416 IdxSigned, "idxprom");
417
418 // We know that the pointer points to a type of the correct size, unless the
419 // size is a VLA.
420 if (!E->getType()->isConstantSizeType(getContext()))
421 assert(0 && "VLA idx not implemented");
422 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
423}
424
Chris Lattner65520192007-08-02 23:37:31 +0000425LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000426EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000427 // Emit the base vector as an l-value.
428 LValue Base = EmitLValue(E->getBase());
429 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
430
Chris Lattnera0d03a72007-08-03 17:31:20 +0000431 return LValue::MakeOCUVectorElt(Base.getAddress(),
432 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000433}
434
Chris Lattner4b009652007-07-25 00:24:17 +0000435//===--------------------------------------------------------------------===//
436// Expression Emission
437//===--------------------------------------------------------------------===//
438
Chris Lattner348c8a22007-08-23 23:43:33 +0000439/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
440/// returning an rvalue corresponding to it. If NeedResult is false, the
441/// result of the expression doesn't need to be generated into memory.
442RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
443 if (!hasAggregateLLVMType(E->getType()))
Chris Lattner9fba49a2007-08-24 05:35:26 +0000444 return RValue::get(EmitScalarExpr(E));
Chris Lattner348c8a22007-08-23 23:43:33 +0000445
446 llvm::Value *DestMem = 0;
447 if (NeedResult)
448 DestMem = CreateTempAlloca(ConvertType(E->getType()));
449
450 if (!E->getType()->isComplexType()) {
451 EmitAggExpr(E, DestMem, false);
452 } else if (NeedResult)
Chris Lattner8e1f6e02007-08-26 16:22:13 +0000453 EmitComplexExprIntoAddr(E, DestMem, false);
Chris Lattner348c8a22007-08-23 23:43:33 +0000454 else
455 EmitComplexExpr(E);
456
457 return RValue::getAggregate(DestMem);
458}
459
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000460
Chris Lattner4b009652007-07-25 00:24:17 +0000461RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000462 if (const ImplicitCastExpr *IcExpr =
463 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
464 if (const DeclRefExpr *DRExpr =
465 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
466 if (const FunctionDecl *FDecl =
467 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
468 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
469 return EmitBuiltinExpr(builtinID, E);
470
Chris Lattner9fba49a2007-08-24 05:35:26 +0000471 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Chris Lattner4b009652007-07-25 00:24:17 +0000472
473 // The callee type will always be a pointer to function type, get the function
474 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000475 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000476 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
477
478 // Get information about the argument types.
479 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
480
481 // Calling unprototyped functions provides no argument info.
482 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
483 ArgTyIt = FTP->arg_type_begin();
484 ArgTyEnd = FTP->arg_type_end();
485 }
486
487 llvm::SmallVector<llvm::Value*, 16> Args;
488
Chris Lattner59802042007-08-10 17:02:28 +0000489 // Handle struct-return functions by passing a pointer to the location that
490 // we would like to return into.
491 if (hasAggregateLLVMType(E->getType())) {
492 // Create a temporary alloca to hold the result of the call. :(
493 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
494 // FIXME: set the stret attribute on the argument.
495 }
496
Chris Lattner4b009652007-07-25 00:24:17 +0000497 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000498 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner348c8a22007-08-23 23:43:33 +0000499 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000500
501 // If this argument has prototype information, convert it.
Chris Lattner2bb17e42007-08-26 07:06:24 +0000502 if (ArgTyIt == ArgTyEnd) {
Chris Lattner4b009652007-07-25 00:24:17 +0000503 // Otherwise, if passing through "..." or to a function with no prototype,
504 // perform the "default argument promotions" (C99 6.5.2.2p6), which
505 // includes the usual unary conversions, but also promotes float to
506 // double.
Chris Lattner2bb17e42007-08-26 07:06:24 +0000507 // FIXME: remove this when the impcast is in place.
Chris Lattner4b009652007-07-25 00:24:17 +0000508 if (const BuiltinType *BT =
509 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
510 if (BT->getKind() == BuiltinType::Float)
511 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
512 llvm::Type::DoubleTy,"tmp"));
513 }
514 }
515
Chris Lattner4b009652007-07-25 00:24:17 +0000516 if (ArgVal.isScalar())
517 Args.push_back(ArgVal.getVal());
518 else // Pass by-address. FIXME: Set attribute bit on call.
519 Args.push_back(ArgVal.getAggregateAddr());
520 }
521
Chris Lattnera9572252007-08-01 06:24:52 +0000522 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000523 if (V->getType() != llvm::Type::VoidTy)
524 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000525 else if (hasAggregateLLVMType(E->getType()))
526 // Struct return.
527 return RValue::getAggregate(Args[0]);
528
Chris Lattner4b009652007-07-25 00:24:17 +0000529 return RValue::get(V);
530}