blob: 549402892f8cda8d10d0a435ffe4bd9d6474430c [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 Lattnercc50a512007-08-26 16:46:58 +000040 QualType BoolTy = getContext().BoolTy;
41 if (!E->getType()->isComplexType())
42 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner4b009652007-07-25 00:24:17 +000043
Chris Lattnercc50a512007-08-26 16:46:58 +000044 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattner4b009652007-07-25 00:24:17 +000045}
46
47//===----------------------------------------------------------------------===//
48// LValue Expression Emission
49//===----------------------------------------------------------------------===//
50
51/// EmitLValue - Emit code to compute a designator that specifies the location
52/// of the expression.
53///
54/// This can return one of two things: a simple address or a bitfield
55/// reference. In either case, the LLVM Value* in the LValue structure is
56/// guaranteed to be an LLVM pointer type.
57///
58/// If this returns a bitfield reference, nothing about the pointee type of
59/// the LLVM value is known: For example, it may not be a pointer to an
60/// integer.
61///
62/// If this returns a normal address, and if the lvalue's C type is fixed
63/// size, this method guarantees that the returned pointer type will point to
64/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
65/// variable length type, this is not possible.
66///
67LValue CodeGenFunction::EmitLValue(const Expr *E) {
68 switch (E->getStmtClass()) {
Chris Lattnera52c8892007-08-26 05:06:40 +000069 default: {
Chris Lattner4b009652007-07-25 00:24:17 +000070 fprintf(stderr, "Unimplemented lvalue expr!\n");
71 E->dump();
Chris Lattnera52c8892007-08-26 05:06:40 +000072 llvm::Type *Ty = llvm::PointerType::get(ConvertType(E->getType()));
73 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
74 }
Chris Lattner4b009652007-07-25 00:24:17 +000075
76 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
77 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
78 case Expr::PreDefinedExprClass:
79 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
80 case Expr::StringLiteralClass:
81 return EmitStringLiteralLValue(cast<StringLiteral>(E));
82
83 case Expr::UnaryOperatorClass:
84 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
85 case Expr::ArraySubscriptExprClass:
86 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +000087 case Expr::OCUVectorElementExprClass:
88 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +000089 }
90}
91
92/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
93/// this method emits the address of the lvalue, then loads the result as an
94/// rvalue, returning the rvalue.
95RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +000096 if (LV.isSimple()) {
97 llvm::Value *Ptr = LV.getAddress();
98 const llvm::Type *EltTy =
99 cast<llvm::PointerType>(Ptr->getType())->getElementType();
100
101 // Simple scalar l-value.
102 if (EltTy->isFirstClassType())
103 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
104
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000105 assert(ExprType->isFunctionType() && "Unknown scalar value");
106 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000107 }
108
109 if (LV.isVectorElt()) {
110 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
111 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
112 "vecext"));
113 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000114
115 // If this is a reference to a subset of the elements of a vector, either
116 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000117 if (LV.isOCUVectorElt())
118 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000119
120 assert(0 && "Bitfield ref not impl!");
121}
122
Chris Lattner944f7962007-08-03 16:18:34 +0000123// If this is a reference to a subset of the elements of a vector, either
124// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000125RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000126 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000127 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
128
Chris Lattnera0d03a72007-08-03 17:31:20 +0000129 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000130
131 // If the result of the expression is a non-vector type, we must be
132 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000133 const VectorType *ExprVT = ExprType->getAsVectorType();
134 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000135 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000136 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
137 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
138 }
139
140 // If the source and destination have the same number of elements, use a
141 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000142 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000143 unsigned NumSourceElts =
144 cast<llvm::VectorType>(Vec->getType())->getNumElements();
145
146 if (NumResultElts == NumSourceElts) {
147 llvm::SmallVector<llvm::Constant*, 4> Mask;
148 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000149 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000150 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
151 }
152
153 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
154 Vec = Builder.CreateShuffleVector(Vec,
155 llvm::UndefValue::get(Vec->getType()),
156 MaskV, "tmp");
157 return RValue::get(Vec);
158 }
159
160 // Start out with an undef of the result type.
161 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
162
163 // Extract/Insert each element of the result.
164 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000165 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000166 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
167 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
168
169 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
170 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
171 }
172
173 return RValue::get(Result);
174}
175
176
Chris Lattner4b009652007-07-25 00:24:17 +0000177RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
178 return EmitLoadOfLValue(EmitLValue(E), E->getType());
179}
180
181
182/// EmitStoreThroughLValue - Store the specified rvalue into the specified
183/// lvalue, where both are guaranteed to the have the same type, and that type
184/// is 'Ty'.
185void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
186 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000187 if (!Dst.isSimple()) {
188 if (Dst.isVectorElt()) {
189 // Read/modify/write the vector, inserting the new element.
190 // FIXME: Volatility.
191 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
192 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
193 Dst.getVectorIdx(), "vecins");
194 Builder.CreateStore(Vec, Dst.getVectorAddr());
195 return;
196 }
Chris Lattner4b009652007-07-25 00:24:17 +0000197
Chris Lattner5bfdd232007-08-03 16:28:33 +0000198 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000199 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000200 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
201
202 assert(0 && "FIXME: Don't support store to bitfield yet");
203 }
Chris Lattner4b009652007-07-25 00:24:17 +0000204
205 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000206 assert(Src.isScalar() && "Can't emit an agg store with this method");
207 // FIXME: Handle volatility etc.
208 const llvm::Type *SrcTy = Src.getVal()->getType();
209 const llvm::Type *AddrTy =
210 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner4b009652007-07-25 00:24:17 +0000211
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000212 if (AddrTy != SrcTy)
213 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
214 "storetmp");
215 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000216}
217
Chris Lattner5bfdd232007-08-03 16:28:33 +0000218void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
219 QualType Ty) {
220 // This access turns into a read/modify/write of the vector. Load the input
221 // value now.
222 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
223 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000224 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000225
226 llvm::Value *SrcVal = Src.getVal();
227
Chris Lattner940966d2007-08-03 16:37:04 +0000228 if (const VectorType *VTy = Ty->getAsVectorType()) {
229 unsigned NumSrcElts = VTy->getNumElements();
230
231 // Extract/Insert each element.
232 for (unsigned i = 0; i != NumSrcElts; ++i) {
233 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
234 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
235
Chris Lattnera0d03a72007-08-03 17:31:20 +0000236 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000237 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
238 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
239 }
240 } else {
241 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000242 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000243 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
244 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000245 }
246
Chris Lattner5bfdd232007-08-03 16:28:33 +0000247 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
248}
249
Chris Lattner4b009652007-07-25 00:24:17 +0000250
251LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
252 const Decl *D = E->getDecl();
253 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
254 llvm::Value *V = LocalDeclMap[D];
255 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
256 return LValue::MakeAddr(V);
257 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
258 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
259 }
260 assert(0 && "Unimp declref");
261}
262
263LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
264 // __extension__ doesn't affect lvalue-ness.
265 if (E->getOpcode() == UnaryOperator::Extension)
266 return EmitLValue(E->getSubExpr());
267
268 assert(E->getOpcode() == UnaryOperator::Deref &&
269 "'*' is the only unary operator that produces an lvalue");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000270 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
Chris Lattner4b009652007-07-25 00:24:17 +0000271}
272
273LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
274 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
275 const char *StrData = E->getStrData();
276 unsigned Len = E->getByteLength();
277
278 // FIXME: Can cache/reuse these within the module.
279 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
280
281 // Create a global variable for this.
282 C = new llvm::GlobalVariable(C->getType(), true,
283 llvm::GlobalValue::InternalLinkage,
284 C, ".str", CurFn->getParent());
285 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
286 llvm::Constant *Zeros[] = { Zero, Zero };
287 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
288 return LValue::MakeAddr(C);
289}
290
291LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
292 std::string FunctionName(CurFuncDecl->getName());
293 std::string GlobalVarName;
294
295 switch (E->getIdentType()) {
296 default:
297 assert(0 && "unknown pre-defined ident type");
298 case PreDefinedExpr::Func:
299 GlobalVarName = "__func__.";
300 break;
301 case PreDefinedExpr::Function:
302 GlobalVarName = "__FUNCTION__.";
303 break;
304 case PreDefinedExpr::PrettyFunction:
305 // FIXME:: Demangle C++ method names
306 GlobalVarName = "__PRETTY_FUNCTION__.";
307 break;
308 }
309
310 GlobalVarName += CurFuncDecl->getName();
311
312 // FIXME: Can cache/reuse these within the module.
313 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
314
315 // Create a global variable for this.
316 C = new llvm::GlobalVariable(C->getType(), true,
317 llvm::GlobalValue::InternalLinkage,
318 C, GlobalVarName, CurFn->getParent());
319 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
320 llvm::Constant *Zeros[] = { Zero, Zero };
321 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
322 return LValue::MakeAddr(C);
323}
324
325LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000326 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000327 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattner4b009652007-07-25 00:24:17 +0000328
329 // If the base is a vector type, then we are forming a vector element lvalue
330 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000331 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000332 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000333 LValue LHS = EmitLValue(E->getLHS());
334 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000335 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000336 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000337 }
338
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000339 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000340 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +0000341
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000342 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000343 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000344 bool IdxSigned = IdxTy->isSignedIntegerType();
345 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
346 if (IdxBitwidth != LLVMPointerWidth)
347 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
348 IdxSigned, "idxprom");
349
350 // We know that the pointer points to a type of the correct size, unless the
351 // size is a VLA.
352 if (!E->getType()->isConstantSizeType(getContext()))
353 assert(0 && "VLA idx not implemented");
354 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
355}
356
Chris Lattner65520192007-08-02 23:37:31 +0000357LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000358EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000359 // Emit the base vector as an l-value.
360 LValue Base = EmitLValue(E->getBase());
361 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
362
Chris Lattnera0d03a72007-08-03 17:31:20 +0000363 return LValue::MakeOCUVectorElt(Base.getAddress(),
364 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000365}
366
Chris Lattner4b009652007-07-25 00:24:17 +0000367//===--------------------------------------------------------------------===//
368// Expression Emission
369//===--------------------------------------------------------------------===//
370
Chris Lattner348c8a22007-08-23 23:43:33 +0000371/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
372/// returning an rvalue corresponding to it. If NeedResult is false, the
373/// result of the expression doesn't need to be generated into memory.
374RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
375 if (!hasAggregateLLVMType(E->getType()))
Chris Lattner9fba49a2007-08-24 05:35:26 +0000376 return RValue::get(EmitScalarExpr(E));
Chris Lattner348c8a22007-08-23 23:43:33 +0000377
378 llvm::Value *DestMem = 0;
379 if (NeedResult)
380 DestMem = CreateTempAlloca(ConvertType(E->getType()));
381
382 if (!E->getType()->isComplexType()) {
383 EmitAggExpr(E, DestMem, false);
384 } else if (NeedResult)
Chris Lattner8e1f6e02007-08-26 16:22:13 +0000385 EmitComplexExprIntoAddr(E, DestMem, false);
Chris Lattner348c8a22007-08-23 23:43:33 +0000386 else
387 EmitComplexExpr(E);
388
389 return RValue::getAggregate(DestMem);
390}
391
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000392
Chris Lattner4b009652007-07-25 00:24:17 +0000393RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000394 if (const ImplicitCastExpr *IcExpr =
395 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
396 if (const DeclRefExpr *DRExpr =
397 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
398 if (const FunctionDecl *FDecl =
399 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
400 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
401 return EmitBuiltinExpr(builtinID, E);
402
Chris Lattner9fba49a2007-08-24 05:35:26 +0000403 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Chris Lattner4b009652007-07-25 00:24:17 +0000404
405 // The callee type will always be a pointer to function type, get the function
406 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000407 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000408 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
409
410 // Get information about the argument types.
411 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
412
413 // Calling unprototyped functions provides no argument info.
414 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
415 ArgTyIt = FTP->arg_type_begin();
416 ArgTyEnd = FTP->arg_type_end();
417 }
418
419 llvm::SmallVector<llvm::Value*, 16> Args;
420
Chris Lattner59802042007-08-10 17:02:28 +0000421 // Handle struct-return functions by passing a pointer to the location that
422 // we would like to return into.
423 if (hasAggregateLLVMType(E->getType())) {
424 // Create a temporary alloca to hold the result of the call. :(
425 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
426 // FIXME: set the stret attribute on the argument.
427 }
428
Chris Lattner4b009652007-07-25 00:24:17 +0000429 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000430 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000431
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000432 if (!hasAggregateLLVMType(ArgTy)) {
433 // Scalar argument is passed by-value.
434 Args.push_back(EmitScalarExpr(E->getArg(i)));
435
436 if (ArgTyIt == ArgTyEnd) {
437 // Otherwise, if passing through "..." or to a function with no prototype,
438 // perform the "default argument promotions" (C99 6.5.2.2p6), which
439 // includes the usual unary conversions, but also promotes float to
440 // double.
441 // FIXME: remove this when the impcast is in place.
442 if (Args.back()->getType() == llvm::Type::FloatTy)
443 Args.back() = Builder.CreateFPExt(Args.back(), llvm::Type::DoubleTy,
444 "tmp");
445 // FIXME: Remove ArgIt when this is gone.
Chris Lattner4b009652007-07-25 00:24:17 +0000446 }
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000447 } else if (ArgTy->isComplexType()) {
448 // Make a temporary alloca to pass the argument.
449 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
450 EmitComplexExprIntoAddr(E->getArg(i), DestMem, false);
451 Args.push_back(DestMem);
452 } else {
453 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
454 EmitAggExpr(E->getArg(i), DestMem, false);
455 Args.push_back(DestMem);
Chris Lattner4b009652007-07-25 00:24:17 +0000456 }
457
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000458 if (ArgTyIt != ArgTyEnd)
459 ++ArgTyIt;
Chris Lattner4b009652007-07-25 00:24:17 +0000460 }
461
Chris Lattnera9572252007-08-01 06:24:52 +0000462 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000463 if (V->getType() != llvm::Type::VoidTy)
464 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000465 else if (hasAggregateLLVMType(E->getType()))
466 // Struct return.
467 return RValue::getAggregate(Args[0]);
468
Chris Lattner4b009652007-07-25 00:24:17 +0000469 return RValue::get(V);
470}