blob: 840ed4314f6d1f091bd5271ff585a1493acc8cbd [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"
Eli Friedmana04e70d2008-05-17 20:03:47 +000017#include "clang/Basic/TargetInfo.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"
Eli Friedmana04e70d2008-05-17 20:03:47 +000023#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25using namespace CodeGen;
26
27//===--------------------------------------------------------------------===//
28// Miscellaneous Helper Methods
29//===--------------------------------------------------------------------===//
30
31/// CreateTempAlloca - This creates a alloca and inserts it into the entry
32/// block.
33llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
34 const char *Name) {
35 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
36}
37
38/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
39/// expression and compare the result against zero, returning an Int1Ty value.
40llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattnercc50a512007-08-26 16:46:58 +000041 QualType BoolTy = getContext().BoolTy;
Chris Lattnerde0908b2008-04-04 16:54:41 +000042 if (!E->getType()->isAnyComplexType())
Chris Lattnercc50a512007-08-26 16:46:58 +000043 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner4b009652007-07-25 00:24:17 +000044
Chris Lattnercc50a512007-08-26 16:46:58 +000045 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattner4b009652007-07-25 00:24:17 +000046}
47
Chris Lattnere24c4cf2007-08-31 22:49:20 +000048/// EmitAnyExpr - Emit code to compute the specified expression which can have
49/// any type. The result is returned as an RValue struct. If this is an
50/// aggregate expression, the aggloc/agglocvolatile arguments indicate where
51/// the result should be returned.
52RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
53 bool isAggLocVolatile) {
54 if (!hasAggregateLLVMType(E->getType()))
55 return RValue::get(EmitScalarExpr(E));
Chris Lattnerde0908b2008-04-04 16:54:41 +000056 else if (E->getType()->isAnyComplexType())
Chris Lattnere24c4cf2007-08-31 22:49:20 +000057 return RValue::getComplex(EmitComplexExpr(E));
58
59 EmitAggExpr(E, AggLoc, isAggLocVolatile);
60 return RValue::getAggregate(AggLoc);
61}
62
63
Chris Lattner4b009652007-07-25 00:24:17 +000064//===----------------------------------------------------------------------===//
65// LValue Expression Emission
66//===----------------------------------------------------------------------===//
67
68/// EmitLValue - Emit code to compute a designator that specifies the location
69/// of the expression.
70///
71/// This can return one of two things: a simple address or a bitfield
72/// reference. In either case, the LLVM Value* in the LValue structure is
73/// guaranteed to be an LLVM pointer type.
74///
75/// If this returns a bitfield reference, nothing about the pointee type of
76/// the LLVM value is known: For example, it may not be a pointer to an
77/// integer.
78///
79/// If this returns a normal address, and if the lvalue's C type is fixed
80/// size, this method guarantees that the returned pointer type will point to
81/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
82/// variable length type, this is not possible.
83///
84LValue CodeGenFunction::EmitLValue(const Expr *E) {
85 switch (E->getStmtClass()) {
Chris Lattnera52c8892007-08-26 05:06:40 +000086 default: {
Chris Lattnerc61e9f82008-03-30 23:25:33 +000087 printf("Statement class: %d\n", E->getStmtClass());
Chris Lattnere8f49632007-12-02 01:49:16 +000088 WarnUnsupported(E, "l-value expression");
Christopher Lamb4fe5e702007-12-17 01:11:20 +000089 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Chris Lattnera52c8892007-08-26 05:06:40 +000090 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
91 }
Chris Lattner4b009652007-07-25 00:24:17 +000092
Christopher Lambad327ba2007-12-29 05:02:41 +000093 case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +000094 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
95 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
96 case Expr::PreDefinedExprClass:
97 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
98 case Expr::StringLiteralClass:
99 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerb326b172008-03-30 23:03:07 +0000100
101 case Expr::ObjCIvarRefExprClass:
102 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000103
104 case Expr::UnaryOperatorClass:
105 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
106 case Expr::ArraySubscriptExprClass:
107 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemanaf6ed502008-04-18 23:10:10 +0000108 case Expr::ExtVectorElementExprClass:
109 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Devang Patel41b66252007-10-23 20:28:39 +0000110 case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000111 case Expr::CompoundLiteralExprClass:
112 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000113 }
114}
115
116/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
117/// this method emits the address of the lvalue, then loads the result as an
118/// rvalue, returning the rvalue.
119RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000120 if (LV.isSimple()) {
121 llvm::Value *Ptr = LV.getAddress();
122 const llvm::Type *EltTy =
123 cast<llvm::PointerType>(Ptr->getType())->getElementType();
124
125 // Simple scalar l-value.
Chris Lattner6b79f4e2008-01-30 07:01:17 +0000126 if (EltTy->isFirstClassType()) {
127 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
128
129 // Bool can have different representation in memory than in registers.
130 if (ExprType->isBooleanType()) {
131 if (V->getType() != llvm::Type::Int1Ty)
132 V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
133 }
134
135 return RValue::get(V);
136 }
Chris Lattner4b009652007-07-25 00:24:17 +0000137
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000138 assert(ExprType->isFunctionType() && "Unknown scalar value");
139 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000140 }
141
142 if (LV.isVectorElt()) {
143 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
144 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
145 "vecext"));
146 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000147
148 // If this is a reference to a subset of the elements of a vector, either
149 // shuffle the input or extract/insert them as appropriate.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000150 if (LV.isExtVectorElt())
151 return EmitLoadOfExtVectorElementLValue(LV, ExprType);
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000152
153 if (LV.isBitfield())
154 return EmitLoadOfBitfieldLValue(LV, ExprType);
155
156 assert(0 && "Unknown LValue type!");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000157 //an invalid RValue, but the assert will
158 //ensure that this point is never reached
159 return RValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000160}
161
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000162RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
163 QualType ExprType) {
164 llvm::Value *Ptr = LV.getBitfieldAddr();
165 const llvm::Type *EltTy =
166 cast<llvm::PointerType>(Ptr->getType())->getElementType();
167 unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
168 unsigned short BitfieldSize = LV.getBitfieldSize();
169 unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize;
170
171 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
172
173 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit);
174 V = Builder.CreateShl(V, ShAmt, "tmp");
175
176 ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize);
177 V = LV.isBitfieldSigned() ?
178 Builder.CreateAShr(V, ShAmt, "tmp") :
179 Builder.CreateLShr(V, ShAmt, "tmp");
Eli Friedmana04e70d2008-05-17 20:03:47 +0000180
181 // The bitfield type and the normal type differ when the storage sizes
182 // differ (currently just _Bool).
183 V = Builder.CreateIntCast(V, ConvertType(ExprType), false, "tmp");
184
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000185 return RValue::get(V);
186}
187
Chris Lattner944f7962007-08-03 16:18:34 +0000188// If this is a reference to a subset of the elements of a vector, either
189// shuffle the input or extract/insert them as appropriate.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000190RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
191 QualType ExprType) {
192 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), "tmp");
Chris Lattner944f7962007-08-03 16:18:34 +0000193
Nate Begemanc8e51f82008-05-09 06:41:27 +0000194 const llvm::Constant *Elts = LV.getExtVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000195
196 // If the result of the expression is a non-vector type, we must be
197 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000198 const VectorType *ExprVT = ExprType->getAsVectorType();
199 if (!ExprVT) {
Nate Begemanc8e51f82008-05-09 06:41:27 +0000200 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts);
Chris Lattner944f7962007-08-03 16:18:34 +0000201 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
202 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
203 }
204
205 // If the source and destination have the same number of elements, use a
206 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000207 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000208 unsigned NumSourceElts =
209 cast<llvm::VectorType>(Vec->getType())->getNumElements();
210
211 if (NumResultElts == NumSourceElts) {
212 llvm::SmallVector<llvm::Constant*, 4> Mask;
213 for (unsigned i = 0; i != NumResultElts; ++i) {
Nate Begemanc8e51f82008-05-09 06:41:27 +0000214 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts);
Chris Lattner944f7962007-08-03 16:18:34 +0000215 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
216 }
217
218 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
219 Vec = Builder.CreateShuffleVector(Vec,
220 llvm::UndefValue::get(Vec->getType()),
221 MaskV, "tmp");
222 return RValue::get(Vec);
223 }
224
225 // Start out with an undef of the result type.
226 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
227
228 // Extract/Insert each element of the result.
229 for (unsigned i = 0; i != NumResultElts; ++i) {
Nate Begemanc8e51f82008-05-09 06:41:27 +0000230 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts);
Chris Lattner944f7962007-08-03 16:18:34 +0000231 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
232 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
233
234 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
235 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
236 }
237
238 return RValue::get(Result);
239}
240
241
Chris Lattner4b009652007-07-25 00:24:17 +0000242
243/// EmitStoreThroughLValue - Store the specified rvalue into the specified
244/// lvalue, where both are guaranteed to the have the same type, and that type
245/// is 'Ty'.
246void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
247 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000248 if (!Dst.isSimple()) {
249 if (Dst.isVectorElt()) {
250 // Read/modify/write the vector, inserting the new element.
251 // FIXME: Volatility.
252 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000253 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner5bfdd232007-08-03 16:28:33 +0000254 Dst.getVectorIdx(), "vecins");
255 Builder.CreateStore(Vec, Dst.getVectorAddr());
256 return;
257 }
Chris Lattner4b009652007-07-25 00:24:17 +0000258
Nate Begemanaf6ed502008-04-18 23:10:10 +0000259 // If this is an update of extended vector elements, insert them as
260 // appropriate.
261 if (Dst.isExtVectorElt())
262 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000263
264 if (Dst.isBitfield())
265 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
266
Lauro Ramos Venancio14d39842008-01-22 22:38:35 +0000267 assert(0 && "Unknown LValue type");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000268 }
Chris Lattner4b009652007-07-25 00:24:17 +0000269
270 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000271 assert(Src.isScalar() && "Can't emit an agg store with this method");
272 // FIXME: Handle volatility etc.
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000273 const llvm::Type *SrcTy = Src.getScalarVal()->getType();
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000274 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
275 const llvm::Type *AddrTy = DstPtr->getElementType();
276 unsigned AS = DstPtr->getAddressSpace();
Chris Lattner4b009652007-07-25 00:24:17 +0000277
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000278 if (AddrTy != SrcTy)
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000279 DstAddr = Builder.CreateBitCast(DstAddr,
280 llvm::PointerType::get(SrcTy, AS),
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000281 "storetmp");
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000282 Builder.CreateStore(Src.getScalarVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000283}
284
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000285void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
286 QualType Ty) {
287 unsigned short StartBit = Dst.getBitfieldStartBit();
288 unsigned short BitfieldSize = Dst.getBitfieldSize();
289 llvm::Value *Ptr = Dst.getBitfieldAddr();
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000290
291 llvm::Value *NewVal = Src.getScalarVal();
292 llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp");
293
Eli Friedmana04e70d2008-05-17 20:03:47 +0000294 // The bitfield type and the normal type differ when the storage sizes
295 // differ (currently just _Bool).
296 const llvm::Type *EltTy = OldVal->getType();
297 unsigned EltTySize = CGM.getTargetData().getABITypeSizeInBits(EltTy);
298
299 NewVal = Builder.CreateIntCast(NewVal, EltTy, false, "tmp");
300
301 // Move the bits into the appropriate location
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000302 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit);
303 NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp");
304
305 llvm::Constant *Mask = llvm::ConstantInt::get(
306 llvm::APInt::getBitsSet(EltTySize, StartBit,
Dan Gohmana63ce8f2008-02-12 21:49:34 +0000307 StartBit + BitfieldSize));
Lauro Ramos Venancio2d7a34c2008-01-22 22:36:45 +0000308
309 // Mask out any bits that shouldn't be set in the result.
310 NewVal = Builder.CreateAnd(NewVal, Mask, "tmp");
311
312 // Next, mask out the bits this bit-field should include from the old value.
313 Mask = llvm::ConstantExpr::getNot(Mask);
314 OldVal = Builder.CreateAnd(OldVal, Mask, "tmp");
315
316 // Finally, merge the two together and store it.
317 NewVal = Builder.CreateOr(OldVal, NewVal, "tmp");
318
319 Builder.CreateStore(NewVal, Ptr);
320}
321
Nate Begemanaf6ed502008-04-18 23:10:10 +0000322void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
323 LValue Dst,
324 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000325 // This access turns into a read/modify/write of the vector. Load the input
326 // value now.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000327 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000328 // FIXME: Volatility.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000329 const llvm::Constant *Elts = Dst.getExtVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000330
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000331 llvm::Value *SrcVal = Src.getScalarVal();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000332
Chris Lattner940966d2007-08-03 16:37:04 +0000333 if (const VectorType *VTy = Ty->getAsVectorType()) {
334 unsigned NumSrcElts = VTy->getNumElements();
335
336 // Extract/Insert each element.
337 for (unsigned i = 0; i != NumSrcElts; ++i) {
338 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
339 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
340
Nate Begemanc8e51f82008-05-09 06:41:27 +0000341 unsigned Idx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts);
Chris Lattner940966d2007-08-03 16:37:04 +0000342 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
343 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
344 }
345 } else {
346 // If the Src is a scalar (not a vector) it must be updating one element.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000347 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000348 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
349 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000350 }
351
Nate Begemanaf6ed502008-04-18 23:10:10 +0000352 Builder.CreateStore(Vec, Dst.getExtVectorAddr());
Chris Lattner5bfdd232007-08-03 16:28:33 +0000353}
354
Chris Lattner4b009652007-07-25 00:24:17 +0000355
356LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000357 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
358
359 if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD))) {
Lauro Ramos Venancio2348d972008-02-16 22:30:38 +0000360 if (VD->getStorageClass() == VarDecl::Extern)
361 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
362 else {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000363 llvm::Value *V = LocalDeclMap[VD];
Lauro Ramos Venancio2348d972008-02-16 22:30:38 +0000364 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
365 return LValue::MakeAddr(V);
366 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000367 } else if (VD && VD->isFileVarDecl()) {
368 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
369 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000370 return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false));
Chris Lattner4b009652007-07-25 00:24:17 +0000371 }
372 assert(0 && "Unimp declref");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000373 //an invalid LValue, but the assert will
374 //ensure that this point is never reached.
375 return LValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000376}
377
378LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
379 // __extension__ doesn't affect lvalue-ness.
380 if (E->getOpcode() == UnaryOperator::Extension)
381 return EmitLValue(E->getSubExpr());
382
Chris Lattner5bf72022007-10-30 22:53:42 +0000383 switch (E->getOpcode()) {
384 default: assert(0 && "Unknown unary operator lvalue!");
385 case UnaryOperator::Deref:
386 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
387 case UnaryOperator::Real:
388 case UnaryOperator::Imag:
389 LValue LV = EmitLValue(E->getSubExpr());
Chris Lattner07307562008-03-19 05:19:41 +0000390 unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
391 return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
392 Idx, "idx"));
Chris Lattner5bf72022007-10-30 22:53:42 +0000393 }
Chris Lattner4b009652007-07-25 00:24:17 +0000394}
395
396LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
397 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
398 const char *StrData = E->getStrData();
399 unsigned Len = E->getByteLength();
Chris Lattnerdb6be562007-11-28 05:34:05 +0000400 std::string StringLiteral(StrData, StrData+Len);
401 return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral));
Chris Lattner4b009652007-07-25 00:24:17 +0000402}
403
404LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
Chris Lattner6e6a5972008-04-04 04:07:35 +0000405 std::string FunctionName;
406 if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
407 FunctionName = FD->getName();
408 }
409 else {
410 assert(0 && "Attempting to load predefined constant for invalid decl type");
411 }
Chris Lattner4b009652007-07-25 00:24:17 +0000412 std::string GlobalVarName;
413
414 switch (E->getIdentType()) {
415 default:
416 assert(0 && "unknown pre-defined ident type");
417 case PreDefinedExpr::Func:
418 GlobalVarName = "__func__.";
419 break;
420 case PreDefinedExpr::Function:
421 GlobalVarName = "__FUNCTION__.";
422 break;
423 case PreDefinedExpr::PrettyFunction:
424 // FIXME:: Demangle C++ method names
425 GlobalVarName = "__PRETTY_FUNCTION__.";
426 break;
427 }
428
Chris Lattner6e6a5972008-04-04 04:07:35 +0000429 GlobalVarName += FunctionName;
Chris Lattner4b009652007-07-25 00:24:17 +0000430
431 // FIXME: Can cache/reuse these within the module.
432 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
433
434 // Create a global variable for this.
435 C = new llvm::GlobalVariable(C->getType(), true,
436 llvm::GlobalValue::InternalLinkage,
437 C, GlobalVarName, CurFn->getParent());
Chris Lattner4b009652007-07-25 00:24:17 +0000438 return LValue::MakeAddr(C);
439}
440
441LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000442 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000443 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattner4b009652007-07-25 00:24:17 +0000444
445 // If the base is a vector type, then we are forming a vector element lvalue
446 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000447 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000448 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000449 LValue LHS = EmitLValue(E->getLHS());
450 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000451 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000452 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000453 }
454
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000455 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000456 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +0000457
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000458 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000459 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000460 bool IdxSigned = IdxTy->isSignedIntegerType();
461 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
462 if (IdxBitwidth != LLVMPointerWidth)
463 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
464 IdxSigned, "idxprom");
465
466 // We know that the pointer points to a type of the correct size, unless the
467 // size is a VLA.
Eli Friedman62f67fd2008-02-15 12:20:59 +0000468 if (!E->getType()->isConstantSizeType())
Chris Lattner4b009652007-07-25 00:24:17 +0000469 assert(0 && "VLA idx not implemented");
470 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
471}
472
Nate Begemana1ae7442008-05-13 21:03:02 +0000473static
474llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) {
475 llvm::SmallVector<llvm::Constant *, 4> CElts;
476
477 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
478 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i]));
479
480 return llvm::ConstantVector::get(&CElts[0], CElts.size());
481}
482
Chris Lattner65520192007-08-02 23:37:31 +0000483LValue CodeGenFunction::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000484EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000485 // Emit the base vector as an l-value.
486 LValue Base = EmitLValue(E->getBase());
Chris Lattner65520192007-08-02 23:37:31 +0000487
Nate Begemana1ae7442008-05-13 21:03:02 +0000488 // Encode the element access list into a vector of unsigned indices.
489 llvm::SmallVector<unsigned, 4> Indices;
490 E->getEncodedElementAccess(Indices);
491
492 if (Base.isSimple()) {
493 llvm::Constant *CV = GenerateConstantVector(Indices);
494 return LValue::MakeExtVectorElt(Base.getAddress(), CV);
495 }
496 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
497
498 llvm::Constant *BaseElts = Base.getExtVectorElts();
499 llvm::SmallVector<llvm::Constant *, 4> CElts;
500
501 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
502 if (isa<llvm::ConstantAggregateZero>(BaseElts))
503 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
504 else
505 CElts.push_back(BaseElts->getOperand(Indices[i]));
506 }
507 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
508 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV);
Chris Lattner65520192007-08-02 23:37:31 +0000509}
510
Devang Patel41b66252007-10-23 20:28:39 +0000511LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Patele1f79db2007-12-11 21:33:16 +0000512 bool isUnion = false;
Devang Patel9dd3e2b2007-10-24 22:26:28 +0000513 Expr *BaseExpr = E->getBase();
Devang Patel9dd3e2b2007-10-24 22:26:28 +0000514 llvm::Value *BaseValue = NULL;
Chris Lattner659079e2007-12-02 18:52:07 +0000515
516 // 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 +0000517 if (E->isArrow()) {
Devang Patel2b24fd92007-10-26 18:15:21 +0000518 BaseValue = EmitScalarExpr(BaseExpr);
Devang Patele1f79db2007-12-11 21:33:16 +0000519 const PointerType *PTy =
520 cast<PointerType>(BaseExpr->getType().getCanonicalType());
521 if (PTy->getPointeeType()->isUnionType())
522 isUnion = true;
523 }
Chris Lattner659079e2007-12-02 18:52:07 +0000524 else {
525 LValue BaseLV = EmitLValue(BaseExpr);
526 // FIXME: this isn't right for bitfields.
527 BaseValue = BaseLV.getAddress();
Devang Patele1f79db2007-12-11 21:33:16 +0000528 if (BaseExpr->getType()->isUnionType())
529 isUnion = true;
Chris Lattner659079e2007-12-02 18:52:07 +0000530 }
Devang Patel41b66252007-10-23 20:28:39 +0000531
532 FieldDecl *Field = E->getMemberDecl();
Eli Friedmand3550112008-02-09 08:50:58 +0000533 return EmitLValueForField(BaseValue, Field, isUnion);
534}
Devang Patel41b66252007-10-23 20:28:39 +0000535
Eli Friedmand3550112008-02-09 08:50:58 +0000536LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
537 FieldDecl* Field,
538 bool isUnion)
539{
540 llvm::Value *V;
541 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
Lauro Ramos Venancio63fc38f2008-02-07 19:29:53 +0000542
Chris Lattner07307562008-03-19 05:19:41 +0000543 if (!Field->isBitField()) {
544 V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
545 } else {
Eli Friedmana04e70d2008-05-17 20:03:47 +0000546 // FIXME: CodeGenTypes should expose a method to get the appropriate
547 // type for FieldTy (the appropriate type is ABI-dependent).
548 unsigned EltTySize =
549 CGM.getTargetData().getABITypeSizeInBits(ConvertType(Field->getType()));
550 const llvm::Type *FieldTy = llvm::IntegerType::get(EltTySize);
Chris Lattner07307562008-03-19 05:19:41 +0000551 const llvm::PointerType *BaseTy =
Lauro Ramos Venancio63fc38f2008-02-07 19:29:53 +0000552 cast<llvm::PointerType>(BaseValue->getType());
553 unsigned AS = BaseTy->getAddressSpace();
554 BaseValue = Builder.CreateBitCast(BaseValue,
555 llvm::PointerType::get(FieldTy, AS),
556 "tmp");
557 V = Builder.CreateGEP(BaseValue,
558 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
559 "tmp");
Lauro Ramos Venancio63fc38f2008-02-07 19:29:53 +0000560 }
Chris Lattner07307562008-03-19 05:19:41 +0000561
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000562 // Match union field type.
Lauro Ramos Venancio63fc38f2008-02-07 19:29:53 +0000563 if (isUnion) {
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000564 const llvm::Type * FieldTy = ConvertType(Field->getType());
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000565 const llvm::PointerType * BaseTy =
566 cast<llvm::PointerType>(BaseValue->getType());
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000567 if (FieldTy != BaseTy->getElementType()) {
Christopher Lambd62ab382007-12-29 04:06:57 +0000568 unsigned AS = BaseTy->getAddressSpace();
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000569 V = Builder.CreateBitCast(V,
Christopher Lambd62ab382007-12-29 04:06:57 +0000570 llvm::PointerType::get(FieldTy, AS),
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000571 "tmp");
Devang Patel9b1ca9e2007-10-26 19:42:18 +0000572 }
573 }
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000574
Chris Lattner07307562008-03-19 05:19:41 +0000575 if (!Field->isBitField())
Lauro Ramos Venanciob40307c2008-01-22 20:17:04 +0000576 return LValue::MakeAddr(V);
Chris Lattner07307562008-03-19 05:19:41 +0000577
578 CodeGenTypes::BitFieldInfo bitFieldInfo =
579 CGM.getTypes().getBitFieldInfo(Field);
580 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
581 Field->getType()->isSignedIntegerType());
Devang Patel41b66252007-10-23 20:28:39 +0000582}
583
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000584LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E) {
585 const llvm::Type *LTy = ConvertType(E->getType());
586 llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
587
588 const Expr* InitExpr = E->getInitializer();
589 LValue Result = LValue::MakeAddr(DeclPtr);
590
591 if (E->getType()->isComplexType()) {
592 EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
593 } else if (hasAggregateLLVMType(E->getType())) {
594 EmitAnyExpr(InitExpr, DeclPtr, false);
595 } else {
596 EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
597 }
598
599 return Result;
600}
601
Chris Lattner4b009652007-07-25 00:24:17 +0000602//===--------------------------------------------------------------------===//
603// Expression Emission
604//===--------------------------------------------------------------------===//
605
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000606
Chris Lattner4b009652007-07-25 00:24:17 +0000607RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000608 if (const ImplicitCastExpr *IcExpr =
609 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
610 if (const DeclRefExpr *DRExpr =
611 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
612 if (const FunctionDecl *FDecl =
613 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
614 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
615 return EmitBuiltinExpr(builtinID, E);
616
Chris Lattner9fba49a2007-08-24 05:35:26 +0000617 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Eli Friedman261f4ad2008-01-30 01:32:06 +0000618 return EmitCallExpr(Callee, E->getCallee()->getType(),
619 E->arg_begin(), E->getNumArgs());
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000620}
621
Eli Friedman261f4ad2008-01-30 01:32:06 +0000622RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args,
623 unsigned NumArgs) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000624 llvm::Value *Callee = EmitScalarExpr(FnExpr);
Eli Friedman261f4ad2008-01-30 01:32:06 +0000625 return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs);
Chris Lattner02c60f52007-08-31 04:44:06 +0000626}
627
Christopher Lambad327ba2007-12-29 05:02:41 +0000628LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
629 // Can only get l-value for call expression returning aggregate type
630 RValue RV = EmitCallExpr(E);
631 return LValue::MakeAddr(RV.getAggregateAddr());
632}
633
Chris Lattnerb326b172008-03-30 23:03:07 +0000634LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
635 // Objective-C objects are traditionally C structures with their layout
636 // defined at compile-time. In some implementations, their layout is not
637 // defined until run time in order to allow instance variables to be added to
638 // a class without recompiling all of the subclasses. If this is the case
639 // then the CGObjCRuntime subclass must return true to LateBoundIvars and
640 // implement the lookup itself.
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000641 if (CGM.getObjCRuntime()->LateBoundIVars()) {
Chris Lattnerb326b172008-03-30 23:03:07 +0000642 assert(0 && "FIXME: Implement support for late-bound instance variables");
643 return LValue(); // Not reached.
644 }
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000645
646 // Get a structure type for the object
647 QualType ExprTy = E->getBase()->getType();
648 const llvm::Type *ObjectType = ConvertType(ExprTy);
649 // TODO: Add a special case for isa (index 0)
650 // Work out which index the ivar is
651 const ObjCIvarDecl *Decl = E->getDecl();
652 unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl);
Chris Lattnerb326b172008-03-30 23:03:07 +0000653
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000654 // Get object pointer and coerce object pointer to correct type.
655 llvm::Value *Object = EmitLValue(E->getBase()).getAddress();
Chris Lattner6e6a5972008-04-04 04:07:35 +0000656 Object = Builder.CreateLoad(Object, E->getDecl()->getName());
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000657 if (Object->getType() != ObjectType)
658 Object = Builder.CreateBitCast(Object, ObjectType);
Chris Lattner6e6a5972008-04-04 04:07:35 +0000659
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000660
661 // Return a pointer to the right element.
662 return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index,
663 Decl->getName()));
Chris Lattnerb326b172008-03-30 23:03:07 +0000664}
665
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000666RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType,
Eli Friedman261f4ad2008-01-30 01:32:06 +0000667 Expr *const *ArgExprs, unsigned NumArgs) {
Chris Lattner4b009652007-07-25 00:24:17 +0000668 // The callee type will always be a pointer to function type, get the function
669 // type.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000670 FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType();
671 QualType ResultType = cast<FunctionType>(FnType)->getResultType();
Eli Friedman261f4ad2008-01-30 01:32:06 +0000672
Chris Lattner4b009652007-07-25 00:24:17 +0000673 llvm::SmallVector<llvm::Value*, 16> Args;
674
Chris Lattner59802042007-08-10 17:02:28 +0000675 // Handle struct-return functions by passing a pointer to the location that
676 // we would like to return into.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000677 if (hasAggregateLLVMType(ResultType)) {
Chris Lattner59802042007-08-10 17:02:28 +0000678 // Create a temporary alloca to hold the result of the call. :(
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000679 Args.push_back(CreateTempAlloca(ConvertType(ResultType)));
Chris Lattner59802042007-08-10 17:02:28 +0000680 // FIXME: set the stret attribute on the argument.
681 }
682
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000683 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
684 QualType ArgTy = ArgExprs[i]->getType();
Eli Friedmand3550112008-02-09 08:50:58 +0000685
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000686 if (!hasAggregateLLVMType(ArgTy)) {
687 // Scalar argument is passed by-value.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000688 Args.push_back(EmitScalarExpr(ArgExprs[i]));
Chris Lattnerde0908b2008-04-04 16:54:41 +0000689 } else if (ArgTy->isAnyComplexType()) {
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000690 // Make a temporary alloca to pass the argument.
691 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000692 EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false);
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000693 Args.push_back(DestMem);
694 } else {
695 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000696 EmitAggExpr(ArgExprs[i], DestMem, false);
Chris Lattnerb06c8dd2007-08-26 22:55:13 +0000697 Args.push_back(DestMem);
Chris Lattner4b009652007-07-25 00:24:17 +0000698 }
Chris Lattner4b009652007-07-25 00:24:17 +0000699 }
700
Nate Begemandc6262e2008-03-09 03:09:36 +0000701 llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size());
702 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
703 CI->setCallingConv(F->getCallingConv());
704 if (CI->getType() != llvm::Type::VoidTy)
705 CI->setName("call");
Chris Lattnerde0908b2008-04-04 16:54:41 +0000706 else if (ResultType->isAnyComplexType())
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000707 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000708 else if (hasAggregateLLVMType(ResultType))
Chris Lattner59802042007-08-10 17:02:28 +0000709 // Struct return.
710 return RValue::getAggregate(Args[0]);
Chris Lattner307da022007-11-30 17:56:23 +0000711 else {
712 // void return.
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000713 assert(ResultType->isVoidType() && "Should only have a void expr here");
Nate Begemandc6262e2008-03-09 03:09:36 +0000714 CI = 0;
Chris Lattner307da022007-11-30 17:56:23 +0000715 }
Chris Lattner59802042007-08-10 17:02:28 +0000716
Nate Begemandc6262e2008-03-09 03:09:36 +0000717 return RValue::get(CI);
Chris Lattner4b009652007-07-25 00:24:17 +0000718}