blob: 879f29ab60ab664efa449893d7ca0ec7656e9281 [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//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/Support/MathExtras.h"
22using namespace clang;
23using namespace CodeGen;
24
25//===--------------------------------------------------------------------===//
26// Miscellaneous Helper Methods
27//===--------------------------------------------------------------------===//
28
29/// CreateTempAlloca - This creates a alloca and inserts it into the entry
30/// block.
31llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
32 const char *Name) {
33 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
34}
35
36/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37/// expression and compare the result against zero, returning an Int1Ty value.
38llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattnercc50a512007-08-26 16:46:58 +000039 QualType BoolTy = getContext().BoolTy;
40 if (!E->getType()->isComplexType())
41 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner4b009652007-07-25 00:24:17 +000042
Chris Lattnercc50a512007-08-26 16:46:58 +000043 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattner4b009652007-07-25 00:24:17 +000044}
45
Chris Lattnere24c4cf2007-08-31 22:49:20 +000046/// EmitAnyExpr - Emit code to compute the specified expression which can have
47/// any type. The result is returned as an RValue struct. If this is an
48/// aggregate expression, the aggloc/agglocvolatile arguments indicate where
49/// the result should be returned.
50RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
51 bool isAggLocVolatile) {
52 if (!hasAggregateLLVMType(E->getType()))
53 return RValue::get(EmitScalarExpr(E));
54 else if (E->getType()->isComplexType())
55 return RValue::getComplex(EmitComplexExpr(E));
56
57 EmitAggExpr(E, AggLoc, isAggLocVolatile);
58 return RValue::getAggregate(AggLoc);
59}
60
61
Chris Lattner4b009652007-07-25 00:24:17 +000062//===----------------------------------------------------------------------===//
63// LValue Expression Emission
64//===----------------------------------------------------------------------===//
65
66/// EmitLValue - Emit code to compute a designator that specifies the location
67/// of the expression.
68///
69/// This can return one of two things: a simple address or a bitfield
70/// reference. In either case, the LLVM Value* in the LValue structure is
71/// guaranteed to be an LLVM pointer type.
72///
73/// If this returns a bitfield reference, nothing about the pointee type of
74/// the LLVM value is known: For example, it may not be a pointer to an
75/// integer.
76///
77/// If this returns a normal address, and if the lvalue's C type is fixed
78/// size, this method guarantees that the returned pointer type will point to
79/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
80/// variable length type, this is not possible.
81///
82LValue CodeGenFunction::EmitLValue(const Expr *E) {
83 switch (E->getStmtClass()) {
Chris Lattnera52c8892007-08-26 05:06:40 +000084 default: {
Chris Lattnere8f49632007-12-02 01:49:16 +000085 WarnUnsupported(E, "l-value expression");
Christopher Lamb4fe5e702007-12-17 01:11:20 +000086 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Chris Lattnera52c8892007-08-26 05:06:40 +000087 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
88 }
Chris Lattner4b009652007-07-25 00:24:17 +000089
Christopher Lambad327ba2007-12-29 05:02:41 +000090 case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +000091 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
92 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
93 case Expr::PreDefinedExprClass:
94 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
95 case Expr::StringLiteralClass:
96 return EmitStringLiteralLValue(cast<StringLiteral>(E));
97
98 case Expr::UnaryOperatorClass:
99 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
100 case Expr::ArraySubscriptExprClass:
101 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000102 case Expr::OCUVectorElementExprClass:
103 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Devang Patel41b66252007-10-23 20:28:39 +0000104 case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000105 }
106}
107
108/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
109/// this method emits the address of the lvalue, then loads the result as an
110/// rvalue, returning the rvalue.
111RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000112 if (LV.isSimple()) {
113 llvm::Value *Ptr = LV.getAddress();
114 const llvm::Type *EltTy =
115 cast<llvm::PointerType>(Ptr->getType())->getElementType();
116
117 // Simple scalar l-value.
Chris Lattner6b79f4e2008-01-30 07:01:17 +0000118 if (EltTy->isFirstClassType()) {
119 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
120
121 // Bool can have different representation in memory than in registers.
122 if (ExprType->isBooleanType()) {
123 if (V->getType() != llvm::Type::Int1Ty)
124 V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
125 }
126
127 return RValue::get(V);
128 }
Chris Lattner4b009652007-07-25 00:24:17 +0000129
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000130 assert(ExprType->isFunctionType() && "Unknown scalar value");
131 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000132 }
133
134 if (LV.isVectorElt()) {
135 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
136 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
137 "vecext"));
138 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000139
140 // If this is a reference to a subset of the elements of a vector, either
141 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000142 if (LV.isOCUVectorElt())
143 return EmitLoadOfOCUElementLValue(LV, ExprType);
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000144
145 if (LV.isBitfield())
146 return EmitLoadOfBitfieldLValue(LV, ExprType);
147
148 assert(0 && "Unknown LValue type!");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000149 //an invalid RValue, but the assert will
150 //ensure that this point is never reached
151 return RValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000152}
153
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000154RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
155 QualType ExprType) {
156 llvm::Value *Ptr = LV.getBitfieldAddr();
157 const llvm::Type *EltTy =
158 cast<llvm::PointerType>(Ptr->getType())->getElementType();
159 unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
160 unsigned short BitfieldSize = LV.getBitfieldSize();
161 unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize;
162
163 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
164
165 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit);
166 V = Builder.CreateShl(V, ShAmt, "tmp");
167
168 ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize);
169 V = LV.isBitfieldSigned() ?
170 Builder.CreateAShr(V, ShAmt, "tmp") :
171 Builder.CreateLShr(V, ShAmt, "tmp");
172 return RValue::get(V);
173}
174
Chris Lattner944f7962007-08-03 16:18:34 +0000175// If this is a reference to a subset of the elements of a vector, either
176// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000177RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000178 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000179 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
180
Chris Lattnera0d03a72007-08-03 17:31:20 +0000181 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000182
183 // If the result of the expression is a non-vector type, we must be
184 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000185 const VectorType *ExprVT = ExprType->getAsVectorType();
186 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000187 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000188 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
189 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
190 }
191
192 // If the source and destination have the same number of elements, use a
193 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000194 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000195 unsigned NumSourceElts =
196 cast<llvm::VectorType>(Vec->getType())->getNumElements();
197
198 if (NumResultElts == NumSourceElts) {
199 llvm::SmallVector<llvm::Constant*, 4> Mask;
200 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000201 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000202 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
203 }
204
205 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
206 Vec = Builder.CreateShuffleVector(Vec,
207 llvm::UndefValue::get(Vec->getType()),
208 MaskV, "tmp");
209 return RValue::get(Vec);
210 }
211
212 // Start out with an undef of the result type.
213 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
214
215 // Extract/Insert each element of the result.
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 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
219 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
220
221 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
222 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
223 }
224
225 return RValue::get(Result);
226}
227
228
Chris Lattner4b009652007-07-25 00:24:17 +0000229
230/// EmitStoreThroughLValue - Store the specified rvalue into the specified
231/// lvalue, where both are guaranteed to the have the same type, and that type
232/// is 'Ty'.
233void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
234 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000235 if (!Dst.isSimple()) {
236 if (Dst.isVectorElt()) {
237 // Read/modify/write the vector, inserting the new element.
238 // FIXME: Volatility.
239 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000240 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner5bfdd232007-08-03 16:28:33 +0000241 Dst.getVectorIdx(), "vecins");
242 Builder.CreateStore(Vec, Dst.getVectorAddr());
243 return;
244 }
Chris Lattner4b009652007-07-25 00:24:17 +0000245
Chris Lattner5bfdd232007-08-03 16:28:33 +0000246 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000247 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000248 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000249
250 if (Dst.isBitfield())
251 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
252
Lauro Ramos Venancio14d39842008-01-22 22:38:35 +0000253 assert(0 && "Unknown LValue type");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000254 }
Chris Lattner4b009652007-07-25 00:24:17 +0000255
256 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000257 assert(Src.isScalar() && "Can't emit an agg store with this method");
258 // FIXME: Handle volatility etc.
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000259 const llvm::Type *SrcTy = Src.getScalarVal()->getType();
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000260 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
261 const llvm::Type *AddrTy = DstPtr->getElementType();
262 unsigned AS = DstPtr->getAddressSpace();
Chris Lattner4b009652007-07-25 00:24:17 +0000263
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000264 if (AddrTy != SrcTy)
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000265 DstAddr = Builder.CreateBitCast(DstAddr,
266 llvm::PointerType::get(SrcTy, AS),
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000267 "storetmp");
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000268 Builder.CreateStore(Src.getScalarVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000269}
270
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000271void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
272 QualType Ty) {
273 unsigned short StartBit = Dst.getBitfieldStartBit();
274 unsigned short BitfieldSize = Dst.getBitfieldSize();
275 llvm::Value *Ptr = Dst.getBitfieldAddr();
276 const llvm::Type *EltTy =
277 cast<llvm::PointerType>(Ptr->getType())->getElementType();
278 unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
279
280 llvm::Value *NewVal = Src.getScalarVal();
281 llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp");
282
283 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit);
284 NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp");
285
286 llvm::Constant *Mask = llvm::ConstantInt::get(
287 llvm::APInt::getBitsSet(EltTySize, StartBit,
Dan Gohmana63ce8f2008-02-12 21:49:34 +0000288 StartBit + BitfieldSize));
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000289
290 // Mask out any bits that shouldn't be set in the result.
291 NewVal = Builder.CreateAnd(NewVal, Mask, "tmp");
292
293 // Next, mask out the bits this bit-field should include from the old value.
294 Mask = llvm::ConstantExpr::getNot(Mask);
295 OldVal = Builder.CreateAnd(OldVal, Mask, "tmp");
296
297 // Finally, merge the two together and store it.
298 NewVal = Builder.CreateOr(OldVal, NewVal, "tmp");
299
300 Builder.CreateStore(NewVal, Ptr);
301}
302
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000303void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
Chris Lattner5bfdd232007-08-03 16:28:33 +0000304 QualType Ty) {
305 // This access turns into a read/modify/write of the vector. Load the input
306 // value now.
307 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
308 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000309 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000310
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000311 llvm::Value *SrcVal = Src.getScalarVal();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000312
Chris Lattner940966d2007-08-03 16:37:04 +0000313 if (const VectorType *VTy = Ty->getAsVectorType()) {
314 unsigned NumSrcElts = VTy->getNumElements();
315
316 // Extract/Insert each element.
317 for (unsigned i = 0; i != NumSrcElts; ++i) {
318 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
319 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
320
Chris Lattnera0d03a72007-08-03 17:31:20 +0000321 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000322 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
323 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
324 }
325 } else {
326 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000327 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000328 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
329 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000330 }
331
Chris Lattner5bfdd232007-08-03 16:28:33 +0000332 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
333}
334
Chris Lattner4b009652007-07-25 00:24:17 +0000335
336LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Steve Naroffcb597472007-09-13 21:41:19 +0000337 const ValueDecl *D = E->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000338 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Lauro Ramos Venancio2348d972008-02-16 22:30:38 +0000339 const VarDecl *VD = cast<VarDecl>(D);
340 if (VD->getStorageClass() == VarDecl::Extern)
341 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
342 else {
343 llvm::Value *V = LocalDeclMap[D];
344 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
345 return LValue::MakeAddr(V);
346 }
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000347 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
348 return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false));
349 } else if (const FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000350 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(FVD, false));
Chris Lattner4b009652007-07-25 00:24:17 +0000351 }
352 assert(0 && "Unimp declref");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000353 //an invalid LValue, but the assert will
354 //ensure that this point is never reached.
355 return LValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000356}
357
358LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
359 // __extension__ doesn't affect lvalue-ness.
360 if (E->getOpcode() == UnaryOperator::Extension)
361 return EmitLValue(E->getSubExpr());
362
Chris Lattner5bf72022007-10-30 22:53:42 +0000363 switch (E->getOpcode()) {
364 default: assert(0 && "Unknown unary operator lvalue!");
365 case UnaryOperator::Deref:
366 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
367 case UnaryOperator::Real:
368 case UnaryOperator::Imag:
369 LValue LV = EmitLValue(E->getSubExpr());
370
371 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
372 llvm::Constant *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty,
373 E->getOpcode() == UnaryOperator::Imag);
374 llvm::Value *Ops[] = {Zero, Idx};
375 return LValue::MakeAddr(Builder.CreateGEP(LV.getAddress(), Ops, Ops+2,
376 "idx"));
377 }
Chris Lattner4b009652007-07-25 00:24:17 +0000378}
379
380LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
381 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
382 const char *StrData = E->getStrData();
383 unsigned Len = E->getByteLength();
Chris Lattnerdb6be562007-11-28 05:34:05 +0000384 std::string StringLiteral(StrData, StrData+Len);
385 return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral));
Chris Lattner4b009652007-07-25 00:24:17 +0000386}
387
388LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
389 std::string FunctionName(CurFuncDecl->getName());
390 std::string GlobalVarName;
391
392 switch (E->getIdentType()) {
393 default:
394 assert(0 && "unknown pre-defined ident type");
395 case PreDefinedExpr::Func:
396 GlobalVarName = "__func__.";
397 break;
398 case PreDefinedExpr::Function:
399 GlobalVarName = "__FUNCTION__.";
400 break;
401 case PreDefinedExpr::PrettyFunction:
402 // FIXME:: Demangle C++ method names
403 GlobalVarName = "__PRETTY_FUNCTION__.";
404 break;
405 }
406
407 GlobalVarName += CurFuncDecl->getName();
408
409 // FIXME: Can cache/reuse these within the module.
410 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
411
412 // Create a global variable for this.
413 C = new llvm::GlobalVariable(C->getType(), true,
414 llvm::GlobalValue::InternalLinkage,
415 C, GlobalVarName, CurFn->getParent());
Chris Lattner4b009652007-07-25 00:24:17 +0000416 return LValue::MakeAddr(C);
417}
418
419LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000420 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000421 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattner4b009652007-07-25 00:24:17 +0000422
423 // If the base is a vector type, then we are forming a vector element lvalue
424 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000425 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000426 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000427 LValue LHS = EmitLValue(E->getLHS());
428 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000429 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000430 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000431 }
432
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000433 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000434 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +0000435
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000436 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000437 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000438 bool IdxSigned = IdxTy->isSignedIntegerType();
439 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
440 if (IdxBitwidth != LLVMPointerWidth)
441 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
442 IdxSigned, "idxprom");
443
444 // We know that the pointer points to a type of the correct size, unless the
445 // size is a VLA.
Eli Friedman62f67fd2008-02-15 12:20:59 +0000446 if (!E->getType()->isConstantSizeType())
Chris Lattner4b009652007-07-25 00:24:17 +0000447 assert(0 && "VLA idx not implemented");
448 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
449}
450
Chris Lattner65520192007-08-02 23:37:31 +0000451LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000452EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000453 // Emit the base vector as an l-value.
454 LValue Base = EmitLValue(E->getBase());
455 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
456
Chris Lattnera0d03a72007-08-03 17:31:20 +0000457 return LValue::MakeOCUVectorElt(Base.getAddress(),
458 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000459}
460
Devang Patel41b66252007-10-23 20:28:39 +0000461LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Patele1f79db2007-12-11 21:33:16 +0000462 bool isUnion = false;
Devang Patel9dd3e2b2007-10-24 22:26:28 +0000463 Expr *BaseExpr = E->getBase();
Devang Patel9dd3e2b2007-10-24 22:26:28 +0000464 llvm::Value *BaseValue = NULL;
Chris Lattner659079e2007-12-02 18:52:07 +0000465
466 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
Devang Patele1f79db2007-12-11 21:33:16 +0000467 if (E->isArrow()) {
Devang Patel2b24fd92007-10-26 18:15:21 +0000468 BaseValue = EmitScalarExpr(BaseExpr);
Devang Patele1f79db2007-12-11 21:33:16 +0000469 const PointerType *PTy =
470 cast<PointerType>(BaseExpr->getType().getCanonicalType());
471 if (PTy->getPointeeType()->isUnionType())
472 isUnion = true;
473 }
Chris Lattner659079e2007-12-02 18:52:07 +0000474 else {
475 LValue BaseLV = EmitLValue(BaseExpr);
476 // FIXME: this isn't right for bitfields.
477 BaseValue = BaseLV.getAddress();
Devang Patele1f79db2007-12-11 21:33:16 +0000478 if (BaseExpr->getType()->isUnionType())
479 isUnion = true;
Chris Lattner659079e2007-12-02 18:52:07 +0000480 }
Devang Patel41b66252007-10-23 20:28:39 +0000481
482 FieldDecl *Field = E->getMemberDecl();
Eli Friedmand3550112008-02-09 08:50:58 +0000483 return EmitLValueForField(BaseValue, Field, isUnion);
484}
Devang Patel41b66252007-10-23 20:28:39 +0000485
Eli Friedmand3550112008-02-09 08:50:58 +0000486LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
487 FieldDecl* Field,
488 bool isUnion)
489{
490 llvm::Value *V;
491 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
Lauro Ramos Venancio63fc38f2008-02-07 19:29:53 +0000492
493 if (Field->isBitField()) {
494 const llvm::Type * FieldTy = ConvertType(Field->getType());
495 const llvm::PointerType * BaseTy =
496 cast<llvm::PointerType>(BaseValue->getType());
497 unsigned AS = BaseTy->getAddressSpace();
498 BaseValue = Builder.CreateBitCast(BaseValue,
499 llvm::PointerType::get(FieldTy, AS),
500 "tmp");
501 V = Builder.CreateGEP(BaseValue,
502 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
503 "tmp");
504 } else {
505 llvm::Value *Idxs[2] = { llvm::Constant::getNullValue(llvm::Type::Int32Ty),
506 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx) };
507 V = Builder.CreateGEP(BaseValue,Idxs, Idxs + 2, "tmp");
508 }
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000509 // Match union field type.
Lauro Ramos Venancio63fc38f2008-02-07 19:29:53 +0000510 if (isUnion) {
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000511 const llvm::Type * FieldTy = ConvertType(Field->getType());
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000512 const llvm::PointerType * BaseTy =
513 cast<llvm::PointerType>(BaseValue->getType());
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000514 if (FieldTy != BaseTy->getElementType()) {
Christopher Lambd62ab382007-12-29 04:06:57 +0000515 unsigned AS = BaseTy->getAddressSpace();
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000516 V = Builder.CreateBitCast(V,
Christopher Lambd62ab382007-12-29 04:06:57 +0000517 llvm::PointerType::get(FieldTy, AS),
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000518 "tmp");
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000519 }
520 }
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000521
522 if (Field->isBitField()) {
523 CodeGenTypes::BitFieldInfo bitFieldInfo =
524 CGM.getTypes().getBitFieldInfo(Field);
525 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
526 Field->getType()->isSignedIntegerType());
527 } else
528 return LValue::MakeAddr(V);
Devang Patel41b66252007-10-23 20:28:39 +0000529}
530
Chris Lattner4b009652007-07-25 00:24:17 +0000531//===--------------------------------------------------------------------===//
532// Expression Emission
533//===--------------------------------------------------------------------===//
534
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000535
Chris Lattner4b009652007-07-25 00:24:17 +0000536RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000537 if (const ImplicitCastExpr *IcExpr =
538 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
539 if (const DeclRefExpr *DRExpr =
540 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
541 if (const FunctionDecl *FDecl =
542 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
543 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
544 return EmitBuiltinExpr(builtinID, E);
545
Chris Lattner9fba49a2007-08-24 05:35:26 +0000546 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Eli Friedman261f4ad2008-01-30 01:32:06 +0000547 return EmitCallExpr(Callee, E->getCallee()->getType(),
548 E->arg_begin(), E->getNumArgs());
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000549}
550
Eli Friedman261f4ad2008-01-30 01:32:06 +0000551RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args,
552 unsigned NumArgs) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000553 llvm::Value *Callee = EmitScalarExpr(FnExpr);
Eli Friedman261f4ad2008-01-30 01:32:06 +0000554 return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs);
Chris Lattner02c60f52007-08-31 04:44:06 +0000555}
556
Christopher Lambad327ba2007-12-29 05:02:41 +0000557LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
558 // Can only get l-value for call expression returning aggregate type
559 RValue RV = EmitCallExpr(E);
560 return LValue::MakeAddr(RV.getAggregateAddr());
561}
562
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000563RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType,
Eli Friedman261f4ad2008-01-30 01:32:06 +0000564 Expr *const *ArgExprs, unsigned NumArgs) {
Chris Lattner4b009652007-07-25 00:24:17 +0000565 // The callee type will always be a pointer to function type, get the function
566 // type.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000567 FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType();
568 QualType ResultType = cast<FunctionType>(FnType)->getResultType();
Eli Friedman261f4ad2008-01-30 01:32:06 +0000569
Chris Lattner4b009652007-07-25 00:24:17 +0000570 llvm::SmallVector<llvm::Value*, 16> Args;
571
Chris Lattner59802042007-08-10 17:02:28 +0000572 // Handle struct-return functions by passing a pointer to the location that
573 // we would like to return into.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000574 if (hasAggregateLLVMType(ResultType)) {
Chris Lattner59802042007-08-10 17:02:28 +0000575 // Create a temporary alloca to hold the result of the call. :(
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000576 Args.push_back(CreateTempAlloca(ConvertType(ResultType)));
Chris Lattner59802042007-08-10 17:02:28 +0000577 // FIXME: set the stret attribute on the argument.
578 }
579
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000580 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
581 QualType ArgTy = ArgExprs[i]->getType();
Eli Friedmand3550112008-02-09 08:50:58 +0000582
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000583 if (!hasAggregateLLVMType(ArgTy)) {
584 // Scalar argument is passed by-value.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000585 Args.push_back(EmitScalarExpr(ArgExprs[i]));
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000586 } else if (ArgTy->isComplexType()) {
587 // Make a temporary alloca to pass the argument.
588 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000589 EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false);
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000590 Args.push_back(DestMem);
591 } else {
592 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000593 EmitAggExpr(ArgExprs[i], DestMem, false);
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000594 Args.push_back(DestMem);
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
Chris Lattner4b009652007-07-25 00:24:17 +0000596 }
597
Chris Lattnera9572252007-08-01 06:24:52 +0000598 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000599 if (V->getType() != llvm::Type::VoidTy)
600 V->setName("call");
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000601 else if (ResultType->isComplexType())
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000602 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000603 else if (hasAggregateLLVMType(ResultType))
Chris Lattner59802042007-08-10 17:02:28 +0000604 // Struct return.
605 return RValue::getAggregate(Args[0]);
Chris Lattner307da022007-11-30 17:56:23 +0000606 else {
607 // void return.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000608 assert(ResultType->isVoidType() && "Should only have a void expr here");
Chris Lattner307da022007-11-30 17:56:23 +0000609 V = 0;
610 }
Chris Lattner59802042007-08-10 17:02:28 +0000611
Chris Lattner4b009652007-07-25 00:24:17 +0000612 return RValue::get(V);
613}