blob: c80b6a7a8b3914448c3e680c131191b345389aab [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chris Lattnerb6984c42007-06-20 04:44:43 +000015#include "CodeGenModule.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000016#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner4347e3692007-06-06 04:54:52 +000019#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
Chris Lattner651f0e92007-07-16 05:43:05 +000021#include "llvm/Support/MathExtras.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000022using namespace clang;
23using namespace CodeGen;
24
Chris Lattnerd7f58862007-06-02 05:24:33 +000025//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000026// Miscellaneous Helper Methods
27//===--------------------------------------------------------------------===//
28
Chris Lattnere9a64532007-06-22 21:44:33 +000029/// 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}
Chris Lattner8394d792007-06-05 20:53:16 +000035
36/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000038llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner268fcce2007-08-26 16:46:58 +000039 QualType BoolTy = getContext().BoolTy;
40 if (!E->getType()->isComplexType())
41 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000042
Chris Lattner268fcce2007-08-26 16:46:58 +000043 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000044}
45
Chris Lattner4647a212007-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 Lattnera45c5af2007-06-02 19:47:04 +000062//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +000063// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +000064//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +000065
Chris Lattner8394d792007-06-05 20:53:16 +000066/// 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///
Chris Lattnerd7f58862007-06-02 05:24:33 +000082LValue CodeGenFunction::EmitLValue(const Expr *E) {
83 switch (E->getStmtClass()) {
Chris Lattnerc7f06ca2007-08-26 05:06:40 +000084 default: {
Chris Lattnerc00c35a2008-03-30 23:25:33 +000085 printf("Statement class: %d\n", E->getStmtClass());
Chris Lattnerf0780fa2007-12-02 01:49:16 +000086 WarnUnsupported(E, "l-value expression");
Christopher Lamb77560fb2007-12-17 01:11:20 +000087 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Chris Lattnerc7f06ca2007-08-26 05:06:40 +000088 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
89 }
Chris Lattnerd7f58862007-06-02 05:24:33 +000090
Christopher Lambd91c3d42007-12-29 05:02:41 +000091 case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +000092 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +000093 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson625bfc82007-07-21 05:21:51 +000094 case Expr::PreDefinedExprClass:
95 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +000096 case Expr::StringLiteralClass:
97 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner4bd55962008-03-30 23:03:07 +000098
99 case Expr::ObjCIvarRefExprClass:
100 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000101
102 case Expr::UnaryOperatorClass:
103 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000104 case Expr::ArraySubscriptExprClass:
105 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000106 case Expr::OCUVectorElementExprClass:
107 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Devang Patel30efa2e2007-10-23 20:28:39 +0000108 case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000109 }
110}
111
Chris Lattner8394d792007-06-05 20:53:16 +0000112/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
113/// this method emits the address of the lvalue, then loads the result as an
114/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000115RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000116 if (LV.isSimple()) {
117 llvm::Value *Ptr = LV.getAddress();
118 const llvm::Type *EltTy =
119 cast<llvm::PointerType>(Ptr->getType())->getElementType();
120
121 // Simple scalar l-value.
Chris Lattner05ba4cb2008-01-30 07:01:17 +0000122 if (EltTy->isFirstClassType()) {
123 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
124
125 // Bool can have different representation in memory than in registers.
126 if (ExprType->isBooleanType()) {
127 if (V->getType() != llvm::Type::Int1Ty)
128 V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
129 }
130
131 return RValue::get(V);
132 }
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000133
Chris Lattner6278e6a2007-08-11 00:04:45 +0000134 assert(ExprType->isFunctionType() && "Unknown scalar value");
135 return RValue::get(Ptr);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000136 }
Chris Lattner09153c02007-06-22 18:48:09 +0000137
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000138 if (LV.isVectorElt()) {
139 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
140 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
141 "vecext"));
142 }
Chris Lattner73ab9b32007-08-03 00:16:29 +0000143
144 // If this is a reference to a subset of the elements of a vector, either
145 // shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000146 if (LV.isOCUVectorElt())
147 return EmitLoadOfOCUElementLValue(LV, ExprType);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +0000148
149 if (LV.isBitfield())
150 return EmitLoadOfBitfieldLValue(LV, ExprType);
151
152 assert(0 && "Unknown LValue type!");
Chris Lattner793d10c2007-09-16 19:23:47 +0000153 //an invalid RValue, but the assert will
154 //ensure that this point is never reached
155 return RValue();
Chris Lattner8394d792007-06-05 20:53:16 +0000156}
157
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +0000158RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
159 QualType ExprType) {
160 llvm::Value *Ptr = LV.getBitfieldAddr();
161 const llvm::Type *EltTy =
162 cast<llvm::PointerType>(Ptr->getType())->getElementType();
163 unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
164 unsigned short BitfieldSize = LV.getBitfieldSize();
165 unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize;
166
167 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
168
169 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit);
170 V = Builder.CreateShl(V, ShAmt, "tmp");
171
172 ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize);
173 V = LV.isBitfieldSigned() ?
174 Builder.CreateAShr(V, ShAmt, "tmp") :
175 Builder.CreateLShr(V, ShAmt, "tmp");
176 return RValue::get(V);
177}
178
Chris Lattner40ff7012007-08-03 16:18:34 +0000179// If this is a reference to a subset of the elements of a vector, either
180// shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000181RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000182 QualType ExprType) {
Chris Lattner40ff7012007-08-03 16:18:34 +0000183 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
184
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000185 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner40ff7012007-08-03 16:18:34 +0000186
187 // If the result of the expression is a non-vector type, we must be
188 // extracting a single element. Just codegen as an extractelement.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000189 const VectorType *ExprVT = ExprType->getAsVectorType();
190 if (!ExprVT) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000191 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000192 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
193 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
194 }
195
196 // If the source and destination have the same number of elements, use a
197 // vector shuffle instead of insert/extracts.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000198 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner40ff7012007-08-03 16:18:34 +0000199 unsigned NumSourceElts =
200 cast<llvm::VectorType>(Vec->getType())->getNumElements();
201
202 if (NumResultElts == NumSourceElts) {
203 llvm::SmallVector<llvm::Constant*, 4> Mask;
204 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000205 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000206 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
207 }
208
209 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
210 Vec = Builder.CreateShuffleVector(Vec,
211 llvm::UndefValue::get(Vec->getType()),
212 MaskV, "tmp");
213 return RValue::get(Vec);
214 }
215
216 // Start out with an undef of the result type.
217 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
218
219 // Extract/Insert each element of the result.
220 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000221 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000222 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
223 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
224
225 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
226 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
227 }
228
229 return RValue::get(Result);
230}
231
232
Chris Lattner9369a562007-06-29 16:31:29 +0000233
Chris Lattner8394d792007-06-05 20:53:16 +0000234/// EmitStoreThroughLValue - Store the specified rvalue into the specified
235/// lvalue, where both are guaranteed to the have the same type, and that type
236/// is 'Ty'.
237void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
238 QualType Ty) {
Chris Lattner41d480e2007-08-03 16:28:33 +0000239 if (!Dst.isSimple()) {
240 if (Dst.isVectorElt()) {
241 // Read/modify/write the vector, inserting the new element.
242 // FIXME: Volatility.
243 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
Chris Lattner4647a212007-08-31 22:49:20 +0000244 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +0000245 Dst.getVectorIdx(), "vecins");
246 Builder.CreateStore(Vec, Dst.getVectorAddr());
247 return;
248 }
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000249
Chris Lattner41d480e2007-08-03 16:28:33 +0000250 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000251 if (Dst.isOCUVectorElt())
Chris Lattner41d480e2007-08-03 16:28:33 +0000252 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +0000253
254 if (Dst.isBitfield())
255 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
256
Lauro Ramos Venanciodb449042008-01-22 22:38:35 +0000257 assert(0 && "Unknown LValue type");
Chris Lattner41d480e2007-08-03 16:28:33 +0000258 }
Chris Lattner8394d792007-06-05 20:53:16 +0000259
Chris Lattner09153c02007-06-22 18:48:09 +0000260 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000261 assert(Src.isScalar() && "Can't emit an agg store with this method");
262 // FIXME: Handle volatility etc.
Chris Lattner4647a212007-08-31 22:49:20 +0000263 const llvm::Type *SrcTy = Src.getScalarVal()->getType();
Christopher Lamb77560fb2007-12-17 01:11:20 +0000264 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
265 const llvm::Type *AddrTy = DstPtr->getElementType();
266 unsigned AS = DstPtr->getAddressSpace();
Chris Lattner8394d792007-06-05 20:53:16 +0000267
Chris Lattner6278e6a2007-08-11 00:04:45 +0000268 if (AddrTy != SrcTy)
Christopher Lamb77560fb2007-12-17 01:11:20 +0000269 DstAddr = Builder.CreateBitCast(DstAddr,
270 llvm::PointerType::get(SrcTy, AS),
Chris Lattner6278e6a2007-08-11 00:04:45 +0000271 "storetmp");
Chris Lattner4647a212007-08-31 22:49:20 +0000272 Builder.CreateStore(Src.getScalarVal(), DstAddr);
Chris Lattner8394d792007-06-05 20:53:16 +0000273}
274
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +0000275void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
276 QualType Ty) {
277 unsigned short StartBit = Dst.getBitfieldStartBit();
278 unsigned short BitfieldSize = Dst.getBitfieldSize();
279 llvm::Value *Ptr = Dst.getBitfieldAddr();
280 const llvm::Type *EltTy =
281 cast<llvm::PointerType>(Ptr->getType())->getElementType();
282 unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
283
284 llvm::Value *NewVal = Src.getScalarVal();
285 llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp");
286
287 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit);
288 NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp");
289
290 llvm::Constant *Mask = llvm::ConstantInt::get(
291 llvm::APInt::getBitsSet(EltTySize, StartBit,
Dan Gohman922096c2008-02-12 21:49:34 +0000292 StartBit + BitfieldSize));
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +0000293
294 // Mask out any bits that shouldn't be set in the result.
295 NewVal = Builder.CreateAnd(NewVal, Mask, "tmp");
296
297 // Next, mask out the bits this bit-field should include from the old value.
298 Mask = llvm::ConstantExpr::getNot(Mask);
299 OldVal = Builder.CreateAnd(OldVal, Mask, "tmp");
300
301 // Finally, merge the two together and store it.
302 NewVal = Builder.CreateOr(OldVal, NewVal, "tmp");
303
304 Builder.CreateStore(NewVal, Ptr);
305}
306
Devang Patelffe1e212007-10-30 20:59:40 +0000307void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
Chris Lattner41d480e2007-08-03 16:28:33 +0000308 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 Lattnerd268a7a2007-08-03 17:31:20 +0000313 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner41d480e2007-08-03 16:28:33 +0000314
Chris Lattner4647a212007-08-31 22:49:20 +0000315 llvm::Value *SrcVal = Src.getScalarVal();
Chris Lattner41d480e2007-08-03 16:28:33 +0000316
Chris Lattner3a44aa72007-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 Lattnerd268a7a2007-08-03 17:31:20 +0000325 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner3a44aa72007-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 Lattnerd268a7a2007-08-03 17:31:20 +0000331 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner41d480e2007-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 Lattner41d480e2007-08-03 16:28:33 +0000334 }
335
Chris Lattner41d480e2007-08-03 16:28:33 +0000336 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
337}
338
Chris Lattnerd7f58862007-06-02 05:24:33 +0000339
340LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000341 const ValueDecl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000342 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000343 const VarDecl *VD = cast<VarDecl>(D);
344 if (VD->getStorageClass() == VarDecl::Extern)
345 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
346 else {
347 llvm::Value *V = LocalDeclMap[D];
348 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
349 return LValue::MakeAddr(V);
350 }
Chris Lattner5bcdf242007-12-02 07:09:19 +0000351 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352 return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false));
353 } else if (const FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
Chris Lattner37bd2ec2007-12-18 08:16:44 +0000354 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(FVD, false));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000355 }
356 assert(0 && "Unimp declref");
Chris Lattner793d10c2007-09-16 19:23:47 +0000357 //an invalid LValue, but the assert will
358 //ensure that this point is never reached.
359 return LValue();
Chris Lattnerd7f58862007-06-02 05:24:33 +0000360}
Chris Lattnere47e4402007-06-01 18:02:12 +0000361
Chris Lattner8394d792007-06-05 20:53:16 +0000362LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
363 // __extension__ doesn't affect lvalue-ness.
364 if (E->getOpcode() == UnaryOperator::Extension)
365 return EmitLValue(E->getSubExpr());
366
Chris Lattner595db862007-10-30 22:53:42 +0000367 switch (E->getOpcode()) {
368 default: assert(0 && "Unknown unary operator lvalue!");
369 case UnaryOperator::Deref:
370 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
371 case UnaryOperator::Real:
372 case UnaryOperator::Imag:
373 LValue LV = EmitLValue(E->getSubExpr());
Chris Lattner3e593cd2008-03-19 05:19:41 +0000374 unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
375 return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
376 Idx, "idx"));
Chris Lattner595db862007-10-30 22:53:42 +0000377 }
Chris Lattner8394d792007-06-05 20:53:16 +0000378}
379
Chris Lattner4347e3692007-06-06 04:54:52 +0000380LValue 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 Lattnerfb300092007-11-28 05:34:05 +0000384 std::string StringLiteral(StrData, StrData+Len);
385 return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral));
Chris Lattner4347e3692007-06-06 04:54:52 +0000386}
387
Anders Carlsson625bfc82007-07-21 05:21:51 +0000388LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
Chris Lattner5506f8c2008-04-04 04:07:35 +0000389 std::string FunctionName;
390 if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
391 FunctionName = FD->getName();
392 }
393 else {
394 assert(0 && "Attempting to load predefined constant for invalid decl type");
395 }
Anders Carlsson625bfc82007-07-21 05:21:51 +0000396 std::string GlobalVarName;
397
398 switch (E->getIdentType()) {
399 default:
400 assert(0 && "unknown pre-defined ident type");
401 case PreDefinedExpr::Func:
402 GlobalVarName = "__func__.";
403 break;
404 case PreDefinedExpr::Function:
405 GlobalVarName = "__FUNCTION__.";
406 break;
407 case PreDefinedExpr::PrettyFunction:
408 // FIXME:: Demangle C++ method names
409 GlobalVarName = "__PRETTY_FUNCTION__.";
410 break;
411 }
412
Chris Lattner5506f8c2008-04-04 04:07:35 +0000413 GlobalVarName += FunctionName;
Anders Carlsson625bfc82007-07-21 05:21:51 +0000414
415 // FIXME: Can cache/reuse these within the module.
416 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
417
418 // Create a global variable for this.
419 C = new llvm::GlobalVariable(C->getType(), true,
420 llvm::GlobalValue::InternalLinkage,
421 C, GlobalVarName, CurFn->getParent());
Anders Carlsson625bfc82007-07-21 05:21:51 +0000422 return LValue::MakeAddr(C);
423}
424
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000425LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +0000426 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +0000427 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000428
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000429 // If the base is a vector type, then we are forming a vector element lvalue
430 // with this subscript.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000431 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000432 // Emit the vector as an lvalue to get its address.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000433 LValue LHS = EmitLValue(E->getLHS());
434 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000435 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000436 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000437 }
438
Ted Kremenekc81614d2007-08-20 16:18:38 +0000439 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +0000440 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000441
Ted Kremenekc81614d2007-08-20 16:18:38 +0000442 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000443 QualType IdxTy = E->getIdx()->getType();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000444 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000445 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000446 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000447 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000448 IdxSigned, "idxprom");
449
450 // We know that the pointer points to a type of the correct size, unless the
451 // size is a VLA.
Eli Friedmana682d392008-02-15 12:20:59 +0000452 if (!E->getType()->isConstantSizeType())
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000453 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000454 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000455}
456
Chris Lattner9e751ca2007-08-02 23:37:31 +0000457LValue CodeGenFunction::
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000458EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +0000459 // Emit the base vector as an l-value.
460 LValue Base = EmitLValue(E->getBase());
461 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
462
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000463 return LValue::MakeOCUVectorElt(Base.getAddress(),
464 E->getEncodedElementAccess());
Chris Lattner9e751ca2007-08-02 23:37:31 +0000465}
466
Devang Patel30efa2e2007-10-23 20:28:39 +0000467LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Patelb37b12d2007-12-11 21:33:16 +0000468 bool isUnion = false;
Devang Pateld68df202007-10-24 22:26:28 +0000469 Expr *BaseExpr = E->getBase();
Devang Pateld68df202007-10-24 22:26:28 +0000470 llvm::Value *BaseValue = NULL;
Chris Lattner4e4186b2007-12-02 18:52:07 +0000471
472 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
Devang Patelb37b12d2007-12-11 21:33:16 +0000473 if (E->isArrow()) {
Devang Patel7718d7a2007-10-26 18:15:21 +0000474 BaseValue = EmitScalarExpr(BaseExpr);
Devang Patelb37b12d2007-12-11 21:33:16 +0000475 const PointerType *PTy =
476 cast<PointerType>(BaseExpr->getType().getCanonicalType());
477 if (PTy->getPointeeType()->isUnionType())
478 isUnion = true;
479 }
Chris Lattner4e4186b2007-12-02 18:52:07 +0000480 else {
481 LValue BaseLV = EmitLValue(BaseExpr);
482 // FIXME: this isn't right for bitfields.
483 BaseValue = BaseLV.getAddress();
Devang Patelb37b12d2007-12-11 21:33:16 +0000484 if (BaseExpr->getType()->isUnionType())
485 isUnion = true;
Chris Lattner4e4186b2007-12-02 18:52:07 +0000486 }
Devang Patel30efa2e2007-10-23 20:28:39 +0000487
488 FieldDecl *Field = E->getMemberDecl();
Eli Friedmana62f3e12008-02-09 08:50:58 +0000489 return EmitLValueForField(BaseValue, Field, isUnion);
490}
Devang Patel30efa2e2007-10-23 20:28:39 +0000491
Eli Friedmana62f3e12008-02-09 08:50:58 +0000492LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
493 FieldDecl* Field,
494 bool isUnion)
495{
496 llvm::Value *V;
497 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
Lauro Ramos Venancio9eff02d2008-02-07 19:29:53 +0000498
Chris Lattner3e593cd2008-03-19 05:19:41 +0000499 if (!Field->isBitField()) {
500 V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
501 } else {
502 const llvm::Type *FieldTy = ConvertType(Field->getType());
503 const llvm::PointerType *BaseTy =
Lauro Ramos Venancio9eff02d2008-02-07 19:29:53 +0000504 cast<llvm::PointerType>(BaseValue->getType());
505 unsigned AS = BaseTy->getAddressSpace();
506 BaseValue = Builder.CreateBitCast(BaseValue,
507 llvm::PointerType::get(FieldTy, AS),
508 "tmp");
509 V = Builder.CreateGEP(BaseValue,
510 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
511 "tmp");
Lauro Ramos Venancio9eff02d2008-02-07 19:29:53 +0000512 }
Chris Lattner3e593cd2008-03-19 05:19:41 +0000513
Devang Pateled93c3c2007-10-26 19:42:18 +0000514 // Match union field type.
Lauro Ramos Venancio9eff02d2008-02-07 19:29:53 +0000515 if (isUnion) {
Devang Pateled93c3c2007-10-26 19:42:18 +0000516 const llvm::Type * FieldTy = ConvertType(Field->getType());
Devang Patelffe1e212007-10-30 20:59:40 +0000517 const llvm::PointerType * BaseTy =
518 cast<llvm::PointerType>(BaseValue->getType());
Devang Pateled93c3c2007-10-26 19:42:18 +0000519 if (FieldTy != BaseTy->getElementType()) {
Christopher Lambfd9af542007-12-29 04:06:57 +0000520 unsigned AS = BaseTy->getAddressSpace();
Christopher Lamb77560fb2007-12-17 01:11:20 +0000521 V = Builder.CreateBitCast(V,
Christopher Lambfd9af542007-12-29 04:06:57 +0000522 llvm::PointerType::get(FieldTy, AS),
Christopher Lamb77560fb2007-12-17 01:11:20 +0000523 "tmp");
Devang Pateled93c3c2007-10-26 19:42:18 +0000524 }
525 }
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +0000526
Chris Lattner3e593cd2008-03-19 05:19:41 +0000527 if (!Field->isBitField())
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +0000528 return LValue::MakeAddr(V);
Chris Lattner3e593cd2008-03-19 05:19:41 +0000529
530 CodeGenTypes::BitFieldInfo bitFieldInfo =
531 CGM.getTypes().getBitFieldInfo(Field);
532 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
533 Field->getType()->isSignedIntegerType());
Devang Patel30efa2e2007-10-23 20:28:39 +0000534}
535
Chris Lattnere47e4402007-06-01 18:02:12 +0000536//===--------------------------------------------------------------------===//
537// Expression Emission
538//===--------------------------------------------------------------------===//
539
Chris Lattner76ba8492007-08-20 22:37:10 +0000540
Chris Lattner2b228c92007-06-15 21:34:29 +0000541RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson1d8e5212007-08-20 18:05:56 +0000542 if (const ImplicitCastExpr *IcExpr =
543 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
544 if (const DeclRefExpr *DRExpr =
545 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
546 if (const FunctionDecl *FDecl =
547 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
548 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
549 return EmitBuiltinExpr(builtinID, E);
550
Chris Lattner2da04b32007-08-24 05:35:26 +0000551 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Eli Friedman9d92ce82008-01-30 01:32:06 +0000552 return EmitCallExpr(Callee, E->getCallee()->getType(),
553 E->arg_begin(), E->getNumArgs());
Nate Begeman1e36a852008-01-17 17:46:27 +0000554}
555
Eli Friedman9d92ce82008-01-30 01:32:06 +0000556RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args,
557 unsigned NumArgs) {
Nate Begeman1e36a852008-01-17 17:46:27 +0000558 llvm::Value *Callee = EmitScalarExpr(FnExpr);
Eli Friedman9d92ce82008-01-30 01:32:06 +0000559 return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs);
Chris Lattner9e47ead2007-08-31 04:44:06 +0000560}
561
Christopher Lambd91c3d42007-12-29 05:02:41 +0000562LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
563 // Can only get l-value for call expression returning aggregate type
564 RValue RV = EmitCallExpr(E);
565 return LValue::MakeAddr(RV.getAggregateAddr());
566}
567
Chris Lattner4bd55962008-03-30 23:03:07 +0000568LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
569 // Objective-C objects are traditionally C structures with their layout
570 // defined at compile-time. In some implementations, their layout is not
571 // defined until run time in order to allow instance variables to be added to
572 // a class without recompiling all of the subclasses. If this is the case
573 // then the CGObjCRuntime subclass must return true to LateBoundIvars and
574 // implement the lookup itself.
Chris Lattnerc00c35a2008-03-30 23:25:33 +0000575 if (CGM.getObjCRuntime()->LateBoundIVars()) {
Chris Lattner4bd55962008-03-30 23:03:07 +0000576 assert(0 && "FIXME: Implement support for late-bound instance variables");
577 return LValue(); // Not reached.
578 }
Chris Lattnerc00c35a2008-03-30 23:25:33 +0000579
580 // Get a structure type for the object
581 QualType ExprTy = E->getBase()->getType();
582 const llvm::Type *ObjectType = ConvertType(ExprTy);
583 // TODO: Add a special case for isa (index 0)
584 // Work out which index the ivar is
585 const ObjCIvarDecl *Decl = E->getDecl();
586 unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl);
Chris Lattner4bd55962008-03-30 23:03:07 +0000587
Chris Lattnerc00c35a2008-03-30 23:25:33 +0000588 // Get object pointer and coerce object pointer to correct type.
589 llvm::Value *Object = EmitLValue(E->getBase()).getAddress();
Chris Lattner5506f8c2008-04-04 04:07:35 +0000590 Object = Builder.CreateLoad(Object, E->getDecl()->getName());
Chris Lattnerc00c35a2008-03-30 23:25:33 +0000591 if (Object->getType() != ObjectType)
592 Object = Builder.CreateBitCast(Object, ObjectType);
Chris Lattner5506f8c2008-04-04 04:07:35 +0000593
Chris Lattnerc00c35a2008-03-30 23:25:33 +0000594
595 // Return a pointer to the right element.
596 return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index,
597 Decl->getName()));
Chris Lattner4bd55962008-03-30 23:03:07 +0000598}
599
Nate Begeman1e36a852008-01-17 17:46:27 +0000600RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType,
Eli Friedman9d92ce82008-01-30 01:32:06 +0000601 Expr *const *ArgExprs, unsigned NumArgs) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000602 // The callee type will always be a pointer to function type, get the function
603 // type.
Nate Begeman1e36a852008-01-17 17:46:27 +0000604 FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType();
605 QualType ResultType = cast<FunctionType>(FnType)->getResultType();
Eli Friedman9d92ce82008-01-30 01:32:06 +0000606
Chris Lattner23b7eb62007-06-15 23:05:46 +0000607 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000608
Chris Lattner90d91202007-08-10 17:02:28 +0000609 // Handle struct-return functions by passing a pointer to the location that
610 // we would like to return into.
Nate Begeman1e36a852008-01-17 17:46:27 +0000611 if (hasAggregateLLVMType(ResultType)) {
Chris Lattner90d91202007-08-10 17:02:28 +0000612 // Create a temporary alloca to hold the result of the call. :(
Nate Begeman1e36a852008-01-17 17:46:27 +0000613 Args.push_back(CreateTempAlloca(ConvertType(ResultType)));
Chris Lattner90d91202007-08-10 17:02:28 +0000614 // FIXME: set the stret attribute on the argument.
615 }
616
Nate Begeman1e36a852008-01-17 17:46:27 +0000617 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
618 QualType ArgTy = ArgExprs[i]->getType();
Eli Friedmana62f3e12008-02-09 08:50:58 +0000619
Chris Lattnera811da52007-08-26 22:55:13 +0000620 if (!hasAggregateLLVMType(ArgTy)) {
621 // Scalar argument is passed by-value.
Nate Begeman1e36a852008-01-17 17:46:27 +0000622 Args.push_back(EmitScalarExpr(ArgExprs[i]));
Chris Lattnera811da52007-08-26 22:55:13 +0000623 } else if (ArgTy->isComplexType()) {
624 // Make a temporary alloca to pass the argument.
625 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
Nate Begeman1e36a852008-01-17 17:46:27 +0000626 EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false);
Chris Lattnera811da52007-08-26 22:55:13 +0000627 Args.push_back(DestMem);
628 } else {
629 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
Nate Begeman1e36a852008-01-17 17:46:27 +0000630 EmitAggExpr(ArgExprs[i], DestMem, false);
Chris Lattnera811da52007-08-26 22:55:13 +0000631 Args.push_back(DestMem);
Chris Lattnerc14236b2007-07-10 22:18:37 +0000632 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000633 }
634
Nate Begemanaca747a2008-03-09 03:09:36 +0000635 llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size());
636 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
637 CI->setCallingConv(F->getCallingConv());
638 if (CI->getType() != llvm::Type::VoidTy)
639 CI->setName("call");
Nate Begeman1e36a852008-01-17 17:46:27 +0000640 else if (ResultType->isComplexType())
Chris Lattner4647a212007-08-31 22:49:20 +0000641 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Nate Begeman1e36a852008-01-17 17:46:27 +0000642 else if (hasAggregateLLVMType(ResultType))
Chris Lattner90d91202007-08-10 17:02:28 +0000643 // Struct return.
644 return RValue::getAggregate(Args[0]);
Chris Lattnerb6a7b582007-11-30 17:56:23 +0000645 else {
646 // void return.
Nate Begeman1e36a852008-01-17 17:46:27 +0000647 assert(ResultType->isVoidType() && "Should only have a void expr here");
Nate Begemanaca747a2008-03-09 03:09:36 +0000648 CI = 0;
Chris Lattnerb6a7b582007-11-30 17:56:23 +0000649 }
Chris Lattner90d91202007-08-10 17:02:28 +0000650
Nate Begemanaca747a2008-03-09 03:09:36 +0000651 return RValue::get(CI);
Chris Lattner2b228c92007-06-15 21:34:29 +0000652}