blob: 896db31a1b9293323a5420ef2ffbacdf0eaaf3dc [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
Chris Lattner99e0d792007-07-16 05:43:05 +000021#include "llvm/Support/MathExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using 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 Lattnerd4f08022007-08-08 17:43:05 +000039 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +000040}
41
42/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
43/// load the real and imaginary pieces, returning them as Real/Imag.
44void CodeGenFunction::EmitLoadOfComplex(RValue V,
45 llvm::Value *&Real, llvm::Value *&Imag){
46 llvm::Value *Ptr = V.getAggregateAddr();
47
48 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
49 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
Chris Lattner883f6a72007-08-11 00:04:45 +000050 // FIXME: It would be nice to make this "Ptr->getName()+realp"
Reid Spencer5f016e22007-07-11 17:01:13 +000051 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
52 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
53
54 // FIXME: Handle volatility.
Chris Lattner883f6a72007-08-11 00:04:45 +000055 // FIXME: It would be nice to make this "Ptr->getName()+real"
Reid Spencer5f016e22007-07-11 17:01:13 +000056 Real = Builder.CreateLoad(RealPtr, "real");
57 Imag = Builder.CreateLoad(ImagPtr, "imag");
58}
59
60/// EmitStoreOfComplex - Store the specified real/imag parts into the
61/// specified value pointer.
62void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
63 llvm::Value *ResPtr) {
64 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
65 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
66 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
67 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
68
69 // FIXME: Handle volatility.
70 Builder.CreateStore(Real, RealPtr);
71 Builder.CreateStore(Imag, ImagPtr);
72}
73
74//===--------------------------------------------------------------------===//
75// Conversions
76//===--------------------------------------------------------------------===//
77
78/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
79/// the type specified by DstTy, following the rules of C99 6.3.
80RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
81 QualType DstTy) {
82 ValTy = ValTy.getCanonicalType();
83 DstTy = DstTy.getCanonicalType();
84 if (ValTy == DstTy) return Val;
85
86 // Handle conversions to bool first, they are special: comparisons against 0.
87 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
88 if (DestBT->getKind() == BuiltinType::Bool)
89 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
90
91 // Handle pointer conversions next: pointers can only be converted to/from
92 // other pointers and integers.
93 if (isa<PointerType>(DstTy)) {
94 const llvm::Type *DestTy = ConvertType(DstTy);
95
Chris Lattner461766a2007-08-10 16:33:59 +000096 if (Val.getVal()->getType() == DestTy)
97 return Val;
98
Reid Spencer5f016e22007-07-11 17:01:13 +000099 // The source value may be an integer, or a pointer.
100 assert(Val.isScalar() && "Can only convert from integer or pointer");
101 if (isa<llvm::PointerType>(Val.getVal()->getType()))
102 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
103 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Chris Lattnerfa7c6452007-07-13 03:25:53 +0000104 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 }
106
107 if (isa<PointerType>(ValTy)) {
108 // Must be an ptr to int cast.
109 const llvm::Type *DestTy = ConvertType(DstTy);
110 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
111 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
112 }
113
114 // Finally, we have the arithmetic types: real int/float and complex
115 // int/float. Handle real->real conversions first, they are the most
116 // common.
117 if (Val.isScalar() && DstTy->isRealType()) {
118 // We know that these are representable as scalars in LLVM, convert to LLVM
119 // types since they are easier to reason about.
120 llvm::Value *SrcVal = Val.getVal();
121 const llvm::Type *DestTy = ConvertType(DstTy);
122 if (SrcVal->getType() == DestTy) return Val;
123
124 llvm::Value *Result;
125 if (isa<llvm::IntegerType>(SrcVal->getType())) {
126 bool InputSigned = ValTy->isSignedIntegerType();
127 if (isa<llvm::IntegerType>(DestTy))
128 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
129 else if (InputSigned)
130 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
131 else
132 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
133 } else {
134 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
135 if (isa<llvm::IntegerType>(DestTy)) {
136 if (DstTy->isSignedIntegerType())
137 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
138 else
139 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
140 } else {
141 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
142 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
143 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
144 else
145 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
146 }
147 }
148 return RValue::get(Result);
149 }
150
151 assert(0 && "FIXME: We don't support complex conversions yet!");
152}
153
154
155/// ConvertScalarValueToBool - Convert the specified expression value to a
156/// boolean (i1) truth value. This is equivalent to "Val == 0".
157llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
158 Ty = Ty.getCanonicalType();
159 llvm::Value *Result;
160 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
161 switch (BT->getKind()) {
162 default: assert(0 && "Unknown scalar value");
163 case BuiltinType::Bool:
164 Result = Val.getVal();
165 // Bool is already evaluated right.
166 assert(Result->getType() == llvm::Type::Int1Ty &&
167 "Unexpected bool value type!");
168 return Result;
169 case BuiltinType::Char_S:
170 case BuiltinType::Char_U:
171 case BuiltinType::SChar:
172 case BuiltinType::UChar:
173 case BuiltinType::Short:
174 case BuiltinType::UShort:
175 case BuiltinType::Int:
176 case BuiltinType::UInt:
177 case BuiltinType::Long:
178 case BuiltinType::ULong:
179 case BuiltinType::LongLong:
180 case BuiltinType::ULongLong:
181 // Code below handles simple integers.
182 break;
183 case BuiltinType::Float:
184 case BuiltinType::Double:
185 case BuiltinType::LongDouble: {
186 // Compare against 0.0 for fp scalars.
187 Result = Val.getVal();
188 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
189 // FIXME: llvm-gcc produces a une comparison: validate this is right.
190 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
191 return Result;
192 }
193 }
194 } else if (isa<PointerType>(Ty) ||
195 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
196 // Code below handles this fine.
197 } else {
198 assert(isa<ComplexType>(Ty) && "Unknwon type!");
199 assert(0 && "FIXME: comparisons against complex not implemented yet");
200 }
201
202 // Usual case for integers, pointers, and enums: compare against zero.
203 Result = Val.getVal();
204
205 // Because of the type rules of C, we often end up computing a logical value,
206 // then zero extending it to int, then wanting it as a logical value again.
207 // Optimize this common case.
208 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
209 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
210 Result = ZI->getOperand(0);
211 ZI->eraseFromParent();
212 return Result;
213 }
214 }
215
216 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
217 return Builder.CreateICmpNE(Result, Zero, "tobool");
218}
219
220//===----------------------------------------------------------------------===//
221// LValue Expression Emission
222//===----------------------------------------------------------------------===//
223
224/// EmitLValue - Emit code to compute a designator that specifies the location
225/// of the expression.
226///
227/// This can return one of two things: a simple address or a bitfield
228/// reference. In either case, the LLVM Value* in the LValue structure is
229/// guaranteed to be an LLVM pointer type.
230///
231/// If this returns a bitfield reference, nothing about the pointee type of
232/// the LLVM value is known: For example, it may not be a pointer to an
233/// integer.
234///
235/// If this returns a normal address, and if the lvalue's C type is fixed
236/// size, this method guarantees that the returned pointer type will point to
237/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
238/// variable length type, this is not possible.
239///
240LValue CodeGenFunction::EmitLValue(const Expr *E) {
241 switch (E->getStmtClass()) {
242 default:
243 fprintf(stderr, "Unimplemented lvalue expr!\n");
244 E->dump();
245 return LValue::MakeAddr(llvm::UndefValue::get(
246 llvm::PointerType::get(llvm::Type::Int32Ty)));
247
248 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
249 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson22742662007-07-21 05:21:51 +0000250 case Expr::PreDefinedExprClass:
251 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 case Expr::StringLiteralClass:
253 return EmitStringLiteralLValue(cast<StringLiteral>(E));
254
255 case Expr::UnaryOperatorClass:
256 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
257 case Expr::ArraySubscriptExprClass:
258 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattner6481a572007-08-03 17:31:20 +0000259 case Expr::OCUVectorElementExprClass:
260 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000261 }
262}
263
264/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
265/// this method emits the address of the lvalue, then loads the result as an
266/// rvalue, returning the rvalue.
267RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 if (LV.isSimple()) {
269 llvm::Value *Ptr = LV.getAddress();
270 const llvm::Type *EltTy =
271 cast<llvm::PointerType>(Ptr->getType())->getElementType();
272
273 // Simple scalar l-value.
274 if (EltTy->isFirstClassType())
275 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
276
Chris Lattner883f6a72007-08-11 00:04:45 +0000277 assert(ExprType->isFunctionType() && "Unknown scalar value");
278 return RValue::get(Ptr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 }
280
281 if (LV.isVectorElt()) {
282 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
283 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
284 "vecext"));
285 }
Chris Lattner46ea8eb2007-08-03 00:16:29 +0000286
287 // If this is a reference to a subset of the elements of a vector, either
288 // shuffle the input or extract/insert them as appropriate.
Chris Lattner6481a572007-08-03 17:31:20 +0000289 if (LV.isOCUVectorElt())
290 return EmitLoadOfOCUElementLValue(LV, ExprType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000291
292 assert(0 && "Bitfield ref not impl!");
293}
294
Chris Lattner34cdc862007-08-03 16:18:34 +0000295// If this is a reference to a subset of the elements of a vector, either
296// shuffle the input or extract/insert them as appropriate.
Chris Lattner6481a572007-08-03 17:31:20 +0000297RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattnercf60cd22007-08-10 17:10:08 +0000298 QualType ExprType) {
Chris Lattner34cdc862007-08-03 16:18:34 +0000299 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
300
Chris Lattner6481a572007-08-03 17:31:20 +0000301 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner34cdc862007-08-03 16:18:34 +0000302
303 // If the result of the expression is a non-vector type, we must be
304 // extracting a single element. Just codegen as an extractelement.
Chris Lattnercf60cd22007-08-10 17:10:08 +0000305 const VectorType *ExprVT = ExprType->getAsVectorType();
306 if (!ExprVT) {
Chris Lattner6481a572007-08-03 17:31:20 +0000307 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner34cdc862007-08-03 16:18:34 +0000308 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
309 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
310 }
311
312 // If the source and destination have the same number of elements, use a
313 // vector shuffle instead of insert/extracts.
Chris Lattnercf60cd22007-08-10 17:10:08 +0000314 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner34cdc862007-08-03 16:18:34 +0000315 unsigned NumSourceElts =
316 cast<llvm::VectorType>(Vec->getType())->getNumElements();
317
318 if (NumResultElts == NumSourceElts) {
319 llvm::SmallVector<llvm::Constant*, 4> Mask;
320 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattner6481a572007-08-03 17:31:20 +0000321 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner34cdc862007-08-03 16:18:34 +0000322 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
323 }
324
325 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
326 Vec = Builder.CreateShuffleVector(Vec,
327 llvm::UndefValue::get(Vec->getType()),
328 MaskV, "tmp");
329 return RValue::get(Vec);
330 }
331
332 // Start out with an undef of the result type.
333 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
334
335 // Extract/Insert each element of the result.
336 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattner6481a572007-08-03 17:31:20 +0000337 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner34cdc862007-08-03 16:18:34 +0000338 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
339 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
340
341 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
342 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
343 }
344
345 return RValue::get(Result);
346}
347
348
Reid Spencer5f016e22007-07-11 17:01:13 +0000349RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
350 return EmitLoadOfLValue(EmitLValue(E), E->getType());
351}
352
353
354/// EmitStoreThroughLValue - Store the specified rvalue into the specified
355/// lvalue, where both are guaranteed to the have the same type, and that type
356/// is 'Ty'.
357void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
358 QualType Ty) {
Chris Lattner017d6aa2007-08-03 16:28:33 +0000359 if (!Dst.isSimple()) {
360 if (Dst.isVectorElt()) {
361 // Read/modify/write the vector, inserting the new element.
362 // FIXME: Volatility.
363 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
364 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
365 Dst.getVectorIdx(), "vecins");
366 Builder.CreateStore(Vec, Dst.getVectorAddr());
367 return;
368 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000369
Chris Lattner017d6aa2007-08-03 16:28:33 +0000370 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattner6481a572007-08-03 17:31:20 +0000371 if (Dst.isOCUVectorElt())
Chris Lattner017d6aa2007-08-03 16:28:33 +0000372 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
373
374 assert(0 && "FIXME: Don't support store to bitfield yet");
375 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000376
377 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattner883f6a72007-08-11 00:04:45 +0000378 assert(Src.isScalar() && "Can't emit an agg store with this method");
379 // FIXME: Handle volatility etc.
380 const llvm::Type *SrcTy = Src.getVal()->getType();
381 const llvm::Type *AddrTy =
382 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
Chris Lattner883f6a72007-08-11 00:04:45 +0000384 if (AddrTy != SrcTy)
385 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
386 "storetmp");
387 Builder.CreateStore(Src.getVal(), DstAddr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388}
389
Chris Lattner017d6aa2007-08-03 16:28:33 +0000390void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
391 QualType Ty) {
392 // This access turns into a read/modify/write of the vector. Load the input
393 // value now.
394 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
395 // FIXME: Volatility.
Chris Lattner6481a572007-08-03 17:31:20 +0000396 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner017d6aa2007-08-03 16:28:33 +0000397
398 llvm::Value *SrcVal = Src.getVal();
399
Chris Lattner7e6b51b2007-08-03 16:37:04 +0000400 if (const VectorType *VTy = Ty->getAsVectorType()) {
401 unsigned NumSrcElts = VTy->getNumElements();
402
403 // Extract/Insert each element.
404 for (unsigned i = 0; i != NumSrcElts; ++i) {
405 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
406 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
407
Chris Lattner6481a572007-08-03 17:31:20 +0000408 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner7e6b51b2007-08-03 16:37:04 +0000409 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
410 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
411 }
412 } else {
413 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattner6481a572007-08-03 17:31:20 +0000414 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner017d6aa2007-08-03 16:28:33 +0000415 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
416 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner017d6aa2007-08-03 16:28:33 +0000417 }
418
Chris Lattner017d6aa2007-08-03 16:28:33 +0000419 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
420}
421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422
423LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
424 const Decl *D = E->getDecl();
425 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
426 llvm::Value *V = LocalDeclMap[D];
427 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
428 return LValue::MakeAddr(V);
429 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
430 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
431 }
432 assert(0 && "Unimp declref");
433}
434
435LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
436 // __extension__ doesn't affect lvalue-ness.
437 if (E->getOpcode() == UnaryOperator::Extension)
438 return EmitLValue(E->getSubExpr());
439
440 assert(E->getOpcode() == UnaryOperator::Deref &&
441 "'*' is the only unary operator that produces an lvalue");
442 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
443}
444
445LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
446 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
447 const char *StrData = E->getStrData();
448 unsigned Len = E->getByteLength();
449
450 // FIXME: Can cache/reuse these within the module.
451 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
452
453 // Create a global variable for this.
454 C = new llvm::GlobalVariable(C->getType(), true,
455 llvm::GlobalValue::InternalLinkage,
456 C, ".str", CurFn->getParent());
457 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
458 llvm::Constant *Zeros[] = { Zero, Zero };
459 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
460 return LValue::MakeAddr(C);
461}
462
Anders Carlsson22742662007-07-21 05:21:51 +0000463LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
464 std::string FunctionName(CurFuncDecl->getName());
465 std::string GlobalVarName;
466
467 switch (E->getIdentType()) {
468 default:
469 assert(0 && "unknown pre-defined ident type");
470 case PreDefinedExpr::Func:
471 GlobalVarName = "__func__.";
472 break;
473 case PreDefinedExpr::Function:
474 GlobalVarName = "__FUNCTION__.";
475 break;
476 case PreDefinedExpr::PrettyFunction:
477 // FIXME:: Demangle C++ method names
478 GlobalVarName = "__PRETTY_FUNCTION__.";
479 break;
480 }
481
482 GlobalVarName += CurFuncDecl->getName();
483
484 // FIXME: Can cache/reuse these within the module.
485 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
486
487 // Create a global variable for this.
488 C = new llvm::GlobalVariable(C->getType(), true,
489 llvm::GlobalValue::InternalLinkage,
490 C, GlobalVarName, CurFn->getParent());
491 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
492 llvm::Constant *Zeros[] = { Zero, Zero };
493 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
494 return LValue::MakeAddr(C);
495}
496
Reid Spencer5f016e22007-07-11 17:01:13 +0000497LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
498 // The index must always be a pointer or integer, neither of which is an
499 // aggregate. Emit it.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000500 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000501
502 // If the base is a vector type, then we are forming a vector element lvalue
503 // with this subscript.
504 if (E->getBase()->getType()->isVectorType()) {
505 // Emit the vector as an lvalue to get its address.
506 LValue Base = EmitLValue(E->getBase());
507 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
508 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
509 return LValue::MakeVectorElt(Base.getAddress(), Idx);
510 }
511
512 // At this point, the base must be a pointer or integer, neither of which are
513 // aggregates. Emit it.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000514 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000515
516 // Usually the base is the pointer type, but sometimes it is the index.
517 // Canonicalize to have the pointer as the base.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000518 QualType BaseTy = E->getBase()->getType();
519 QualType IdxTy = E->getIdx()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 if (isa<llvm::PointerType>(Idx->getType())) {
521 std::swap(Base, Idx);
522 std::swap(BaseTy, IdxTy);
523 }
524
525 // The pointer is now the base. Extend or truncate the index type to 32 or
526 // 64-bits.
527 bool IdxSigned = IdxTy->isSignedIntegerType();
528 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
529 if (IdxBitwidth != LLVMPointerWidth)
530 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
531 IdxSigned, "idxprom");
532
533 // We know that the pointer points to a type of the correct size, unless the
534 // size is a VLA.
Chris Lattner590b6642007-07-15 23:26:56 +0000535 if (!E->getType()->isConstantSizeType(getContext()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 assert(0 && "VLA idx not implemented");
537 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
538}
539
Chris Lattner349aaec2007-08-02 23:37:31 +0000540LValue CodeGenFunction::
Chris Lattner6481a572007-08-03 17:31:20 +0000541EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner349aaec2007-08-02 23:37:31 +0000542 // Emit the base vector as an l-value.
543 LValue Base = EmitLValue(E->getBase());
544 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
545
Chris Lattner6481a572007-08-03 17:31:20 +0000546 return LValue::MakeOCUVectorElt(Base.getAddress(),
547 E->getEncodedElementAccess());
Chris Lattner349aaec2007-08-02 23:37:31 +0000548}
549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550//===--------------------------------------------------------------------===//
551// Expression Emission
552//===--------------------------------------------------------------------===//
553
554RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattner883f6a72007-08-11 00:04:45 +0000555 assert(E && !hasAggregateLLVMType(E->getType()) &&
556 "Invalid scalar expression to emit");
Reid Spencer5f016e22007-07-11 17:01:13 +0000557
558 switch (E->getStmtClass()) {
559 default:
560 fprintf(stderr, "Unimplemented expr!\n");
561 E->dump();
562 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
563
564 // l-values.
565 case Expr::DeclRefExprClass:
566 // DeclRef's of EnumConstantDecl's are simple rvalues.
567 if (const EnumConstantDecl *EC =
568 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
569 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
570 return EmitLoadOfLValue(E);
571 case Expr::ArraySubscriptExprClass:
572 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattner6481a572007-08-03 17:31:20 +0000573 case Expr::OCUVectorElementExprClass:
Chris Lattner46ea8eb2007-08-03 00:16:29 +0000574 return EmitLoadOfLValue(E);
Anders Carlsson22742662007-07-21 05:21:51 +0000575 case Expr::PreDefinedExprClass:
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 case Expr::StringLiteralClass:
577 return RValue::get(EmitLValue(E).getAddress());
578
579 // Leaf expressions.
580 case Expr::IntegerLiteralClass:
581 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
582 case Expr::FloatingLiteralClass:
583 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000584 case Expr::CharacterLiteralClass:
585 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner30bf3ae2007-08-03 17:51:03 +0000586 case Expr::TypesCompatibleExprClass:
587 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000588
589 // Operators.
590 case Expr::ParenExprClass:
591 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
592 case Expr::UnaryOperatorClass:
593 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000594 case Expr::SizeOfAlignOfTypeExprClass:
595 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
596 E->getType(),
597 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000598 case Expr::ImplicitCastExprClass:
599 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 case Expr::CastExprClass:
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000601 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 case Expr::CallExprClass:
603 return EmitCallExpr(cast<CallExpr>(E));
604 case Expr::BinaryOperatorClass:
605 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000606
607 case Expr::ConditionalOperatorClass:
608 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner94f05e32007-08-04 00:20:15 +0000609 case Expr::ChooseExprClass:
610 return EmitChooseExpr(cast<ChooseExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000612}
613
614RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
615 return RValue::get(llvm::ConstantInt::get(E->getValue()));
616}
617RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
618 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
619 E->getValue()));
620}
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000621RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
622 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
623 E->getValue()));
624}
Reid Spencer5f016e22007-07-11 17:01:13 +0000625
Chris Lattner30bf3ae2007-08-03 17:51:03 +0000626RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
627 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
628 E->typesAreCompatible()));
629}
630
Chris Lattner94f05e32007-08-04 00:20:15 +0000631/// EmitChooseExpr - Implement __builtin_choose_expr.
632RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
633 llvm::APSInt CondVal(32);
634 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
635 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
636
637 // Emit the LHS or RHS as appropriate.
638 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
639}
640
Chris Lattner30bf3ae2007-08-03 17:51:03 +0000641
Reid Spencer5f016e22007-07-11 17:01:13 +0000642RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
643 // Emit subscript expressions in rvalue context's. For most cases, this just
644 // loads the lvalue formed by the subscript expr. However, we have to be
645 // careful, because the base of a vector subscript is occasionally an rvalue,
646 // so we can't get it as an lvalue.
647 if (!E->getBase()->getType()->isVectorType())
648 return EmitLoadOfLValue(E);
649
650 // Handle the vector case. The base must be a vector, the index must be an
651 // integer value.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000652 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
653 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000654
655 // FIXME: Convert Idx to i32 type.
656
657 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
658}
659
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000660// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
661// have to handle a more broad range of conversions than explicit casts, as they
662// handle things like function to ptr-to-function decay etc.
663RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000664 RValue Src = EmitExpr(Op);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665
666 // If the destination is void, just evaluate the source.
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000667 if (DestTy->isVoidType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 return RValue::getAggregate(0);
669
Chris Lattnerd4f08022007-08-08 17:43:05 +0000670 return EmitConversion(Src, Op->getType(), DestTy);
Reid Spencer5f016e22007-07-11 17:01:13 +0000671}
672
673RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000674 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000675
676 // The callee type will always be a pointer to function type, get the function
677 // type.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000678 QualType CalleeTy = E->getCallee()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
680
681 // Get information about the argument types.
682 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
683
684 // Calling unprototyped functions provides no argument info.
685 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
686 ArgTyIt = FTP->arg_type_begin();
687 ArgTyEnd = FTP->arg_type_end();
688 }
689
690 llvm::SmallVector<llvm::Value*, 16> Args;
691
Chris Lattnercc666af2007-08-10 17:02:28 +0000692 // Handle struct-return functions by passing a pointer to the location that
693 // we would like to return into.
694 if (hasAggregateLLVMType(E->getType())) {
695 // Create a temporary alloca to hold the result of the call. :(
696 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
697 // FIXME: set the stret attribute on the argument.
698 }
699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000701 QualType ArgTy = E->getArg(i)->getType();
702 RValue ArgVal = EmitExpr(E->getArg(i));
Reid Spencer5f016e22007-07-11 17:01:13 +0000703
704 // If this argument has prototype information, convert it.
705 if (ArgTyIt != ArgTyEnd) {
706 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
707 } else {
708 // Otherwise, if passing through "..." or to a function with no prototype,
709 // perform the "default argument promotions" (C99 6.5.2.2p6), which
710 // includes the usual unary conversions, but also promotes float to
711 // double.
712 if (const BuiltinType *BT =
713 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
714 if (BT->getKind() == BuiltinType::Float)
715 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
716 llvm::Type::DoubleTy,"tmp"));
717 }
718 }
719
720
721 if (ArgVal.isScalar())
722 Args.push_back(ArgVal.getVal());
723 else // Pass by-address. FIXME: Set attribute bit on call.
724 Args.push_back(ArgVal.getAggregateAddr());
725 }
726
Chris Lattnerbf986512007-08-01 06:24:52 +0000727 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 if (V->getType() != llvm::Type::VoidTy)
729 V->setName("call");
Chris Lattnercc666af2007-08-10 17:02:28 +0000730 else if (hasAggregateLLVMType(E->getType()))
731 // Struct return.
732 return RValue::getAggregate(Args[0]);
733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 return RValue::get(V);
735}
736
737
738//===----------------------------------------------------------------------===//
739// Unary Operator Emission
740//===----------------------------------------------------------------------===//
741
Reid Spencer5f016e22007-07-11 17:01:13 +0000742RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
743 switch (E->getOpcode()) {
744 default:
745 printf("Unimplemented unary expr!\n");
746 E->dump();
747 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattner57274792007-07-11 23:43:46 +0000748 case UnaryOperator::PostInc:
749 case UnaryOperator::PostDec:
750 case UnaryOperator::PreInc :
751 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
752 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
753 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
754 case UnaryOperator::Plus : return EmitUnaryPlus(E);
755 case UnaryOperator::Minus : return EmitUnaryMinus(E);
756 case UnaryOperator::Not : return EmitUnaryNot(E);
757 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000758 case UnaryOperator::SizeOf :
759 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
760 case UnaryOperator::AlignOf :
761 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 // FIXME: real/imag
763 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
764 }
765}
766
Chris Lattner57274792007-07-11 23:43:46 +0000767RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
768 LValue LV = EmitLValue(E->getSubExpr());
769 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
770
771 // We know the operand is real or pointer type, so it must be an LLVM scalar.
772 assert(InVal.isScalar() && "Unknown thing to increment");
773 llvm::Value *InV = InVal.getVal();
774
775 int AmountVal = 1;
776 if (E->getOpcode() == UnaryOperator::PreDec ||
777 E->getOpcode() == UnaryOperator::PostDec)
778 AmountVal = -1;
779
780 llvm::Value *NextVal;
781 if (isa<llvm::IntegerType>(InV->getType())) {
782 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
783 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
784 } else if (InV->getType()->isFloatingPoint()) {
785 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
786 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
787 } else {
788 // FIXME: This is not right for pointers to VLA types.
789 assert(isa<llvm::PointerType>(InV->getType()));
790 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
791 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
792 }
793
794 RValue NextValToStore = RValue::get(NextVal);
795
796 // Store the updated result through the lvalue.
797 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
798
799 // If this is a postinc, return the value read from memory, otherwise use the
800 // updated value.
801 if (E->getOpcode() == UnaryOperator::PreDec ||
802 E->getOpcode() == UnaryOperator::PreInc)
803 return NextValToStore;
804 else
805 return InVal;
806}
807
Reid Spencer5f016e22007-07-11 17:01:13 +0000808/// C99 6.5.3.2
809RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
810 // The address of the operand is just its lvalue. It cannot be a bitfield.
811 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
812}
813
814RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000815 assert(E->getType().getCanonicalType() ==
816 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
817 // Unary plus just returns its value.
818 return EmitExpr(E->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000819}
820
821RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000822 assert(E->getType().getCanonicalType() ==
823 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
824
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000826 RValue V = EmitExpr(E->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000827
828 if (V.isScalar())
829 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
830
831 assert(0 && "FIXME: This doesn't handle complex operands yet");
832}
833
834RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
835 // Unary not performs promotions, then complements its integer operand.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000836 RValue V = EmitExpr(E->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000837
838 if (V.isScalar())
839 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
840
841 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
842}
843
844
845/// C99 6.5.3.3
846RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
847 // Compare operand to zero.
848 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
849
850 // Invert value.
851 // TODO: Could dynamically modify easy computations here. For example, if
852 // the operand is an icmp ne, turn into icmp eq.
853 BoolVal = Builder.CreateNot(BoolVal, "lnot");
854
855 // ZExt result to int.
856 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
857}
858
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000859/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
860/// an integer (RetType).
861RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
862 QualType RetType, bool isSizeOf) {
863 /// FIXME: This doesn't handle VLAs yet!
864 std::pair<uint64_t, unsigned> Info =
865 getContext().getTypeInfo(TypeToSize, SourceLocation());
866
867 uint64_t Val = isSizeOf ? Info.first : Info.second;
868 Val /= 8; // Return size in bytes, not bits.
869
870 assert(RetType->isIntegerType() && "Result type must be an integer!");
871
872 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
873 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
874}
875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876
877//===--------------------------------------------------------------------===//
878// Binary Operator Emission
879//===--------------------------------------------------------------------===//
880
Reid Spencer5f016e22007-07-11 17:01:13 +0000881
882/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
883/// are strange in that the result of the operation is not the same type as the
884/// intermediate computation. This function emits the LHS and RHS operands of
885/// the compound assignment, promoting them to their common computation type.
886///
887/// Since the LHS is an lvalue, and the result is stored back through it, we
888/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
889/// RHS values are both in the computation type for the operator.
890void CodeGenFunction::
891EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
892 LValue &LHSLV, RValue &LHS, RValue &RHS) {
893 LHSLV = EmitLValue(E->getLHS());
894
895 // Load the LHS and RHS operands.
896 QualType LHSTy = E->getLHS()->getType();
897 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattnerd4f08022007-08-08 17:43:05 +0000898 RHS = EmitExpr(E->getRHS());
899 QualType RHSTy = E->getRHS()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000900
901 // Convert the LHS and RHS to the common evaluation type.
902 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
903 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
904}
905
906/// EmitCompoundAssignmentResult - Given a result value in the computation type,
907/// truncate it down to the actual result type, store it through the LHS lvalue,
908/// and return it.
909RValue CodeGenFunction::
910EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
911 LValue LHSLV, RValue ResV) {
912
913 // Truncate back to the destination type.
914 if (E->getComputationType() != E->getType())
915 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
916
917 // Store the result value into the LHS.
918 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
919
920 // Return the result.
921 return ResV;
922}
923
924
925RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
926 RValue LHS, RHS;
927 switch (E->getOpcode()) {
928 default:
929 fprintf(stderr, "Unimplemented binary expr!\n");
930 E->dump();
931 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
932 case BinaryOperator::Mul:
Chris Lattner6c216162007-08-08 17:49:18 +0000933 LHS = EmitExpr(E->getLHS());
934 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000935 return EmitMul(LHS, RHS, E->getType());
936 case BinaryOperator::Div:
Chris Lattner6c216162007-08-08 17:49:18 +0000937 LHS = EmitExpr(E->getLHS());
938 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 return EmitDiv(LHS, RHS, E->getType());
940 case BinaryOperator::Rem:
Chris Lattner6c216162007-08-08 17:49:18 +0000941 LHS = EmitExpr(E->getLHS());
942 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 return EmitRem(LHS, RHS, E->getType());
Chris Lattner6c216162007-08-08 17:49:18 +0000944 case BinaryOperator::Add:
945 LHS = EmitExpr(E->getLHS());
946 RHS = EmitExpr(E->getRHS());
947 if (!E->getType()->isPointerType())
948 return EmitAdd(LHS, RHS, E->getType());
949
950 return EmitPointerAdd(LHS, E->getLHS()->getType(),
951 RHS, E->getRHS()->getType(), E->getType());
952 case BinaryOperator::Sub:
953 LHS = EmitExpr(E->getLHS());
954 RHS = EmitExpr(E->getRHS());
955
956 if (!E->getLHS()->getType()->isPointerType())
957 return EmitSub(LHS, RHS, E->getType());
958
959 return EmitPointerSub(LHS, E->getLHS()->getType(),
960 RHS, E->getRHS()->getType(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 case BinaryOperator::Shl:
Chris Lattnerd4f08022007-08-08 17:43:05 +0000962 LHS = EmitExpr(E->getLHS());
963 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 return EmitShl(LHS, RHS, E->getType());
965 case BinaryOperator::Shr:
Chris Lattnerd4f08022007-08-08 17:43:05 +0000966 LHS = EmitExpr(E->getLHS());
967 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 return EmitShr(LHS, RHS, E->getType());
969 case BinaryOperator::And:
Chris Lattner6c216162007-08-08 17:49:18 +0000970 LHS = EmitExpr(E->getLHS());
971 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 return EmitAnd(LHS, RHS, E->getType());
973 case BinaryOperator::Xor:
Chris Lattner6c216162007-08-08 17:49:18 +0000974 LHS = EmitExpr(E->getLHS());
975 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 return EmitXor(LHS, RHS, E->getType());
977 case BinaryOperator::Or :
Chris Lattner6c216162007-08-08 17:49:18 +0000978 LHS = EmitExpr(E->getLHS());
979 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 return EmitOr(LHS, RHS, E->getType());
981 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
982 case BinaryOperator::LOr: return EmitBinaryLOr(E);
983 case BinaryOperator::LT:
984 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
985 llvm::ICmpInst::ICMP_SLT,
986 llvm::FCmpInst::FCMP_OLT);
987 case BinaryOperator::GT:
988 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
989 llvm::ICmpInst::ICMP_SGT,
990 llvm::FCmpInst::FCMP_OGT);
991 case BinaryOperator::LE:
992 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
993 llvm::ICmpInst::ICMP_SLE,
994 llvm::FCmpInst::FCMP_OLE);
995 case BinaryOperator::GE:
996 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
997 llvm::ICmpInst::ICMP_SGE,
998 llvm::FCmpInst::FCMP_OGE);
999 case BinaryOperator::EQ:
1000 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1001 llvm::ICmpInst::ICMP_EQ,
1002 llvm::FCmpInst::FCMP_OEQ);
1003 case BinaryOperator::NE:
1004 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1005 llvm::ICmpInst::ICMP_NE,
1006 llvm::FCmpInst::FCMP_UNE);
1007 case BinaryOperator::Assign:
1008 return EmitBinaryAssign(E);
1009
1010 case BinaryOperator::MulAssign: {
1011 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1012 LValue LHSLV;
1013 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1014 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1015 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1016 }
1017 case BinaryOperator::DivAssign: {
1018 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1019 LValue LHSLV;
1020 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1021 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1022 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1023 }
1024 case BinaryOperator::RemAssign: {
1025 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1026 LValue LHSLV;
1027 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1028 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1029 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1030 }
1031 case BinaryOperator::AddAssign: {
1032 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1033 LValue LHSLV;
1034 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1035 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1036 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1037 }
1038 case BinaryOperator::SubAssign: {
1039 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1040 LValue LHSLV;
1041 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1042 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1043 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1044 }
1045 case BinaryOperator::ShlAssign: {
1046 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1047 LValue LHSLV;
1048 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1049 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1050 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1051 }
1052 case BinaryOperator::ShrAssign: {
1053 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1054 LValue LHSLV;
1055 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1056 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1057 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1058 }
1059 case BinaryOperator::AndAssign: {
1060 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1061 LValue LHSLV;
1062 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1063 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1064 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1065 }
1066 case BinaryOperator::OrAssign: {
1067 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1068 LValue LHSLV;
1069 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1070 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1071 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1072 }
1073 case BinaryOperator::XorAssign: {
1074 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1075 LValue LHSLV;
1076 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1077 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1078 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1079 }
1080 case BinaryOperator::Comma: return EmitBinaryComma(E);
1081 }
1082}
1083
1084RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1085 if (LHS.isScalar())
1086 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1087
Gabor Greif4db18f22007-07-13 23:33:18 +00001088 // Otherwise, this must be a complex number.
1089 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1090
1091 EmitLoadOfComplex(LHS, LHSR, LHSI);
1092 EmitLoadOfComplex(RHS, RHSR, RHSI);
1093
1094 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1095 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1096 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1097
1098 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1099 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1100 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1101
1102 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1103 EmitStoreOfComplex(ResR, ResI, Res);
1104 return RValue::getAggregate(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001105}
1106
1107RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1108 if (LHS.isScalar()) {
1109 llvm::Value *RV;
1110 if (LHS.getVal()->getType()->isFloatingPoint())
1111 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1112 else if (ResTy->isUnsignedIntegerType())
1113 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1114 else
1115 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1116 return RValue::get(RV);
1117 }
1118 assert(0 && "FIXME: This doesn't handle complex operands yet");
1119}
1120
1121RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1122 if (LHS.isScalar()) {
1123 llvm::Value *RV;
1124 // Rem in C can't be a floating point type: C99 6.5.5p2.
1125 if (ResTy->isUnsignedIntegerType())
1126 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1127 else
1128 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1129 return RValue::get(RV);
1130 }
1131
1132 assert(0 && "FIXME: This doesn't handle complex operands yet");
1133}
1134
1135RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1136 if (LHS.isScalar())
1137 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1138
1139 // Otherwise, this must be a complex number.
1140 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1141
1142 EmitLoadOfComplex(LHS, LHSR, LHSI);
1143 EmitLoadOfComplex(RHS, RHSR, RHSI);
1144
1145 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1146 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1147
1148 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1149 EmitStoreOfComplex(ResR, ResI, Res);
1150 return RValue::getAggregate(Res);
1151}
1152
Chris Lattner8b9023b2007-07-13 03:05:23 +00001153RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1154 RValue RHS, QualType RHSTy,
1155 QualType ResTy) {
1156 llvm::Value *LHSValue = LHS.getVal();
1157 llvm::Value *RHSValue = RHS.getVal();
1158 if (LHSTy->isPointerType()) {
1159 // pointer + int
1160 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1161 } else {
1162 // int + pointer
1163 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1164 }
1165}
1166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1168 if (LHS.isScalar())
1169 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1170
1171 assert(0 && "FIXME: This doesn't handle complex operands yet");
1172}
1173
Chris Lattner8b9023b2007-07-13 03:05:23 +00001174RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1175 RValue RHS, QualType RHSTy,
1176 QualType ResTy) {
1177 llvm::Value *LHSValue = LHS.getVal();
1178 llvm::Value *RHSValue = RHS.getVal();
1179 if (const PointerType *RHSPtrType =
1180 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1181 // pointer - pointer
1182 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1183 QualType LHSElementType = LHSPtrType->getPointeeType();
1184 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1185 "can't subtract pointers with differing element types");
Chris Lattner99e0d792007-07-16 05:43:05 +00001186 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001187 SourceLocation()) / 8;
Chris Lattner8b9023b2007-07-13 03:05:23 +00001188 const llvm::Type *ResultType = ConvertType(ResTy);
1189 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1190 "sub.ptr.lhs.cast");
1191 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1192 "sub.ptr.rhs.cast");
1193 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1194 "sub.ptr.sub");
Chris Lattner99e0d792007-07-16 05:43:05 +00001195
1196 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1197 // remainder. As such, we handle common power-of-two cases here to generate
1198 // better code.
1199 if (llvm::isPowerOf2_64(ElementSize)) {
1200 llvm::Value *ShAmt =
1201 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1202 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1203 } else {
1204 // Otherwise, do a full sdiv.
1205 llvm::Value *BytesPerElement =
1206 llvm::ConstantInt::get(ResultType, ElementSize);
1207 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1208 "sub.ptr.div"));
1209 }
Chris Lattner8b9023b2007-07-13 03:05:23 +00001210 } else {
1211 // pointer - int
1212 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1213 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1214 }
1215}
1216
Reid Spencer5f016e22007-07-11 17:01:13 +00001217RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1218 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1219
1220 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1221 // RHS to the same size as the LHS.
1222 if (LHS->getType() != RHS->getType())
1223 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1224
1225 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1226}
1227
1228RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1229 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1230
1231 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1232 // RHS to the same size as the LHS.
1233 if (LHS->getType() != RHS->getType())
1234 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1235
1236 if (ResTy->isUnsignedIntegerType())
1237 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1238 else
1239 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1240}
1241
1242RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1243 unsigned UICmpOpc, unsigned SICmpOpc,
1244 unsigned FCmpOpc) {
Chris Lattner6c216162007-08-08 17:49:18 +00001245 RValue LHS = EmitExpr(E->getLHS());
1246 RValue RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001247
1248 llvm::Value *Result;
1249 if (LHS.isScalar()) {
1250 if (LHS.getVal()->getType()->isFloatingPoint()) {
1251 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1252 LHS.getVal(), RHS.getVal(), "cmp");
1253 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1254 // FIXME: This check isn't right for "unsigned short < int" where ushort
1255 // promotes to int and does a signed compare.
1256 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1257 LHS.getVal(), RHS.getVal(), "cmp");
1258 } else {
1259 // Signed integers and pointers.
1260 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1261 LHS.getVal(), RHS.getVal(), "cmp");
1262 }
1263 } else {
1264 // Struct/union/complex
Gabor Greif4db18f22007-07-13 23:33:18 +00001265 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1266 EmitLoadOfComplex(LHS, LHSR, LHSI);
1267 EmitLoadOfComplex(RHS, RHSR, RHSI);
1268
Gabor Greifd5e0d982007-07-14 20:05:18 +00001269 // FIXME: need to consider _Complex over integers too!
1270
Gabor Greif4db18f22007-07-13 23:33:18 +00001271 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1272 LHSR, RHSR, "cmp.r");
1273 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1274 LHSI, RHSI, "cmp.i");
1275 if (BinaryOperator::EQ == E->getOpcode()) {
1276 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1277 } else if (BinaryOperator::NE == E->getOpcode()) {
1278 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1279 } else {
1280 assert(0 && "Complex comparison other than == or != ?");
1281 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 }
Gabor Greif4db18f22007-07-13 23:33:18 +00001283
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // ZExt result to int.
1285 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1286}
1287
1288RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1289 if (LHS.isScalar())
1290 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1291
1292 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1293}
1294
1295RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1296 if (LHS.isScalar())
1297 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1298
1299 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1300}
1301
1302RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1303 if (LHS.isScalar())
1304 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1305
1306 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1307}
1308
1309RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1310 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1311
1312 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1313 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1314
1315 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1316 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1317
1318 EmitBlock(RHSBlock);
1319 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1320
1321 // Reaquire the RHS block, as there may be subblocks inserted.
1322 RHSBlock = Builder.GetInsertBlock();
1323 EmitBlock(ContBlock);
1324
1325 // Create a PHI node. If we just evaluted the LHS condition, the result is
1326 // false. If we evaluated both, the result is the RHS condition.
1327 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1328 PN->reserveOperandSpace(2);
1329 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1330 PN->addIncoming(RHSCond, RHSBlock);
1331
1332 // ZExt result to int.
1333 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1334}
1335
1336RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1337 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1338
1339 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1340 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1341
1342 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1343 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1344
1345 EmitBlock(RHSBlock);
1346 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1347
1348 // Reaquire the RHS block, as there may be subblocks inserted.
1349 RHSBlock = Builder.GetInsertBlock();
1350 EmitBlock(ContBlock);
1351
1352 // Create a PHI node. If we just evaluted the LHS condition, the result is
1353 // true. If we evaluated both, the result is the RHS condition.
1354 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1355 PN->reserveOperandSpace(2);
1356 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1357 PN->addIncoming(RHSCond, RHSBlock);
1358
1359 // ZExt result to int.
1360 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1361}
1362
1363RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +00001364 assert(E->getLHS()->getType().getCanonicalType() ==
1365 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 LValue LHS = EmitLValue(E->getLHS());
Chris Lattnerd4f08022007-08-08 17:43:05 +00001367 RValue RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
1369 // Store the value into the LHS.
1370 EmitStoreThroughLValue(RHS, LHS, E->getType());
Chris Lattner883f6a72007-08-11 00:04:45 +00001371
1372 // Return the RHS.
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 return RHS;
1374}
1375
1376
1377RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1378 EmitExpr(E->getLHS());
1379 return EmitExpr(E->getRHS());
1380}
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001381
1382RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1383 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1384 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1385 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1386
1387 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1388 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1389
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001390 EmitBlock(LHSBlock);
Chris Lattnerd4f08022007-08-08 17:43:05 +00001391 // Handle the GNU extension for missing LHS.
1392 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001393 Builder.CreateBr(ContBlock);
1394 LHSBlock = Builder.GetInsertBlock();
1395
1396 EmitBlock(RHSBlock);
Chris Lattnerd4f08022007-08-08 17:43:05 +00001397
1398 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001399 Builder.CreateBr(ContBlock);
1400 RHSBlock = Builder.GetInsertBlock();
1401
1402 const llvm::Type *LHSType = LHSValue->getType();
1403 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1404
1405 EmitBlock(ContBlock);
1406 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1407 PN->reserveOperandSpace(2);
1408 PN->addIncoming(LHSValue, LHSBlock);
1409 PN->addIncoming(RHSValue, RHSBlock);
1410
1411 return RValue::get(PN);
1412}