blob: d0c241398b699d0140656932411b19283acc682d [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
Anders Carlsson49865302007-08-20 18:05:56 +000017#include "clang/Lex/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/Support/MathExtras.h"
23using namespace clang;
24using namespace CodeGen;
25
26//===--------------------------------------------------------------------===//
27// Miscellaneous Helper Methods
28//===--------------------------------------------------------------------===//
29
30/// CreateTempAlloca - This creates a alloca and inserts it into the entry
31/// block.
32llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
33 const char *Name) {
34 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35}
36
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
39llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +000040 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +000041}
42
43/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
44/// load the real and imaginary pieces, returning them as Real/Imag.
Chris Lattnera7300102007-08-21 04:59:27 +000045void CodeGenFunction::EmitLoadOfComplex(llvm::Value *SrcPtr,
Chris Lattner4b009652007-07-25 00:24:17 +000046 llvm::Value *&Real, llvm::Value *&Imag){
Chris Lattner4b009652007-07-25 00:24:17 +000047 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
48 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +000049 // FIXME: It would be nice to make this "Ptr->getName()+realp"
Chris Lattnera7300102007-08-21 04:59:27 +000050 llvm::Value *RealPtr = Builder.CreateGEP(SrcPtr, Zero, Zero, "realp");
51 llvm::Value *ImagPtr = Builder.CreateGEP(SrcPtr, Zero, One, "imagp");
Chris Lattner4b009652007-07-25 00:24:17 +000052
53 // FIXME: Handle volatility.
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +000054 // FIXME: It would be nice to make this "Ptr->getName()+real"
Chris Lattner4b009652007-07-25 00:24:17 +000055 Real = Builder.CreateLoad(RealPtr, "real");
56 Imag = Builder.CreateLoad(ImagPtr, "imag");
57}
58
59/// EmitStoreOfComplex - Store the specified real/imag parts into the
60/// specified value pointer.
61void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
62 llvm::Value *ResPtr) {
63 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
64 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
65 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
66 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
67
68 // FIXME: Handle volatility.
69 Builder.CreateStore(Real, RealPtr);
70 Builder.CreateStore(Imag, ImagPtr);
71}
72
73//===--------------------------------------------------------------------===//
74// Conversions
75//===--------------------------------------------------------------------===//
76
77/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
78/// the type specified by DstTy, following the rules of C99 6.3.
79RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
80 QualType DstTy) {
81 ValTy = ValTy.getCanonicalType();
82 DstTy = DstTy.getCanonicalType();
83 if (ValTy == DstTy) return Val;
84
85 // Handle conversions to bool first, they are special: comparisons against 0.
86 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
87 if (DestBT->getKind() == BuiltinType::Bool)
88 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
89
90 // Handle pointer conversions next: pointers can only be converted to/from
91 // other pointers and integers.
92 if (isa<PointerType>(DstTy)) {
93 const llvm::Type *DestTy = ConvertType(DstTy);
94
Chris Lattner2a420172007-08-10 16:33:59 +000095 if (Val.getVal()->getType() == DestTy)
96 return Val;
97
Chris Lattner4b009652007-07-25 00:24:17 +000098 // The source value may be an integer, or a pointer.
99 assert(Val.isScalar() && "Can only convert from integer or pointer");
100 if (isa<llvm::PointerType>(Val.getVal()->getType()))
101 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
102 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
103 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
104 }
105
106 if (isa<PointerType>(ValTy)) {
107 // Must be an ptr to int cast.
108 const llvm::Type *DestTy = ConvertType(DstTy);
109 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
110 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
111 }
112
113 // Finally, we have the arithmetic types: real int/float and complex
114 // int/float. Handle real->real conversions first, they are the most
115 // common.
116 if (Val.isScalar() && DstTy->isRealType()) {
117 // We know that these are representable as scalars in LLVM, convert to LLVM
118 // types since they are easier to reason about.
119 llvm::Value *SrcVal = Val.getVal();
120 const llvm::Type *DestTy = ConvertType(DstTy);
121 if (SrcVal->getType() == DestTy) return Val;
122
123 llvm::Value *Result;
124 if (isa<llvm::IntegerType>(SrcVal->getType())) {
125 bool InputSigned = ValTy->isSignedIntegerType();
126 if (isa<llvm::IntegerType>(DestTy))
127 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
128 else if (InputSigned)
129 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
130 else
131 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
132 } else {
133 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
134 if (isa<llvm::IntegerType>(DestTy)) {
135 if (DstTy->isSignedIntegerType())
136 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
137 else
138 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
139 } else {
140 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
141 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
142 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
143 else
144 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
145 }
146 }
147 return RValue::get(Result);
148 }
149
150 assert(0 && "FIXME: We don't support complex conversions yet!");
151}
152
153
154/// ConvertScalarValueToBool - Convert the specified expression value to a
155/// boolean (i1) truth value. This is equivalent to "Val == 0".
156llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
157 Ty = Ty.getCanonicalType();
158 llvm::Value *Result;
159 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
160 switch (BT->getKind()) {
161 default: assert(0 && "Unknown scalar value");
162 case BuiltinType::Bool:
163 Result = Val.getVal();
164 // Bool is already evaluated right.
165 assert(Result->getType() == llvm::Type::Int1Ty &&
166 "Unexpected bool value type!");
167 return Result;
168 case BuiltinType::Char_S:
169 case BuiltinType::Char_U:
170 case BuiltinType::SChar:
171 case BuiltinType::UChar:
172 case BuiltinType::Short:
173 case BuiltinType::UShort:
174 case BuiltinType::Int:
175 case BuiltinType::UInt:
176 case BuiltinType::Long:
177 case BuiltinType::ULong:
178 case BuiltinType::LongLong:
179 case BuiltinType::ULongLong:
180 // Code below handles simple integers.
181 break;
182 case BuiltinType::Float:
183 case BuiltinType::Double:
184 case BuiltinType::LongDouble: {
185 // Compare against 0.0 for fp scalars.
186 Result = Val.getVal();
187 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
188 // FIXME: llvm-gcc produces a une comparison: validate this is right.
189 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
190 return Result;
191 }
192 }
193 } else if (isa<PointerType>(Ty) ||
194 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
195 // Code below handles this fine.
196 } else {
197 assert(isa<ComplexType>(Ty) && "Unknwon type!");
198 assert(0 && "FIXME: comparisons against complex not implemented yet");
199 }
200
201 // Usual case for integers, pointers, and enums: compare against zero.
202 Result = Val.getVal();
203
204 // Because of the type rules of C, we often end up computing a logical value,
205 // then zero extending it to int, then wanting it as a logical value again.
206 // Optimize this common case.
207 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
208 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
209 Result = ZI->getOperand(0);
210 ZI->eraseFromParent();
211 return Result;
212 }
213 }
214
215 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
216 return Builder.CreateICmpNE(Result, Zero, "tobool");
217}
218
219//===----------------------------------------------------------------------===//
220// LValue Expression Emission
221//===----------------------------------------------------------------------===//
222
223/// EmitLValue - Emit code to compute a designator that specifies the location
224/// of the expression.
225///
226/// This can return one of two things: a simple address or a bitfield
227/// reference. In either case, the LLVM Value* in the LValue structure is
228/// guaranteed to be an LLVM pointer type.
229///
230/// If this returns a bitfield reference, nothing about the pointee type of
231/// the LLVM value is known: For example, it may not be a pointer to an
232/// integer.
233///
234/// If this returns a normal address, and if the lvalue's C type is fixed
235/// size, this method guarantees that the returned pointer type will point to
236/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
237/// variable length type, this is not possible.
238///
239LValue CodeGenFunction::EmitLValue(const Expr *E) {
240 switch (E->getStmtClass()) {
241 default:
242 fprintf(stderr, "Unimplemented lvalue expr!\n");
243 E->dump();
244 return LValue::MakeAddr(llvm::UndefValue::get(
245 llvm::PointerType::get(llvm::Type::Int32Ty)));
246
247 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
248 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
249 case Expr::PreDefinedExprClass:
250 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
251 case Expr::StringLiteralClass:
252 return EmitStringLiteralLValue(cast<StringLiteral>(E));
253
254 case Expr::UnaryOperatorClass:
255 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
256 case Expr::ArraySubscriptExprClass:
257 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000258 case Expr::OCUVectorElementExprClass:
259 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000260 }
261}
262
263/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
264/// this method emits the address of the lvalue, then loads the result as an
265/// rvalue, returning the rvalue.
266RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000267 if (LV.isSimple()) {
268 llvm::Value *Ptr = LV.getAddress();
269 const llvm::Type *EltTy =
270 cast<llvm::PointerType>(Ptr->getType())->getElementType();
271
272 // Simple scalar l-value.
273 if (EltTy->isFirstClassType())
274 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
275
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000276 assert(ExprType->isFunctionType() && "Unknown scalar value");
277 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000278 }
279
280 if (LV.isVectorElt()) {
281 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
282 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
283 "vecext"));
284 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000285
286 // If this is a reference to a subset of the elements of a vector, either
287 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000288 if (LV.isOCUVectorElt())
289 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000290
291 assert(0 && "Bitfield ref not impl!");
292}
293
Chris Lattner944f7962007-08-03 16:18:34 +0000294// If this is a reference to a subset of the elements of a vector, either
295// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000296RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000297 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000298 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
299
Chris Lattnera0d03a72007-08-03 17:31:20 +0000300 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000301
302 // If the result of the expression is a non-vector type, we must be
303 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000304 const VectorType *ExprVT = ExprType->getAsVectorType();
305 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000306 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000307 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
308 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
309 }
310
311 // If the source and destination have the same number of elements, use a
312 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000313 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000314 unsigned NumSourceElts =
315 cast<llvm::VectorType>(Vec->getType())->getNumElements();
316
317 if (NumResultElts == NumSourceElts) {
318 llvm::SmallVector<llvm::Constant*, 4> Mask;
319 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000320 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000321 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
322 }
323
324 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
325 Vec = Builder.CreateShuffleVector(Vec,
326 llvm::UndefValue::get(Vec->getType()),
327 MaskV, "tmp");
328 return RValue::get(Vec);
329 }
330
331 // Start out with an undef of the result type.
332 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
333
334 // Extract/Insert each element of the result.
335 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000336 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000337 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
338 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
339
340 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
341 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
342 }
343
344 return RValue::get(Result);
345}
346
347
Chris Lattner4b009652007-07-25 00:24:17 +0000348RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
349 return EmitLoadOfLValue(EmitLValue(E), E->getType());
350}
351
352
353/// EmitStoreThroughLValue - Store the specified rvalue into the specified
354/// lvalue, where both are guaranteed to the have the same type, and that type
355/// is 'Ty'.
356void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
357 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000358 if (!Dst.isSimple()) {
359 if (Dst.isVectorElt()) {
360 // Read/modify/write the vector, inserting the new element.
361 // FIXME: Volatility.
362 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
363 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
364 Dst.getVectorIdx(), "vecins");
365 Builder.CreateStore(Vec, Dst.getVectorAddr());
366 return;
367 }
Chris Lattner4b009652007-07-25 00:24:17 +0000368
Chris Lattner5bfdd232007-08-03 16:28:33 +0000369 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000370 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000371 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
372
373 assert(0 && "FIXME: Don't support store to bitfield yet");
374 }
Chris Lattner4b009652007-07-25 00:24:17 +0000375
376 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000377 assert(Src.isScalar() && "Can't emit an agg store with this method");
378 // FIXME: Handle volatility etc.
379 const llvm::Type *SrcTy = Src.getVal()->getType();
380 const llvm::Type *AddrTy =
381 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner4b009652007-07-25 00:24:17 +0000382
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000383 if (AddrTy != SrcTy)
384 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
385 "storetmp");
386 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000387}
388
Chris Lattner5bfdd232007-08-03 16:28:33 +0000389void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
390 QualType Ty) {
391 // This access turns into a read/modify/write of the vector. Load the input
392 // value now.
393 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
394 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000395 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000396
397 llvm::Value *SrcVal = Src.getVal();
398
Chris Lattner940966d2007-08-03 16:37:04 +0000399 if (const VectorType *VTy = Ty->getAsVectorType()) {
400 unsigned NumSrcElts = VTy->getNumElements();
401
402 // Extract/Insert each element.
403 for (unsigned i = 0; i != NumSrcElts; ++i) {
404 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
405 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
406
Chris Lattnera0d03a72007-08-03 17:31:20 +0000407 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000408 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
409 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
410 }
411 } else {
412 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000413 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000414 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
415 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000416 }
417
Chris Lattner5bfdd232007-08-03 16:28:33 +0000418 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
419}
420
Chris Lattner4b009652007-07-25 00:24:17 +0000421
422LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
423 const Decl *D = E->getDecl();
424 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
425 llvm::Value *V = LocalDeclMap[D];
426 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
427 return LValue::MakeAddr(V);
428 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
429 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
430 }
431 assert(0 && "Unimp declref");
432}
433
434LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
435 // __extension__ doesn't affect lvalue-ness.
436 if (E->getOpcode() == UnaryOperator::Extension)
437 return EmitLValue(E->getSubExpr());
438
439 assert(E->getOpcode() == UnaryOperator::Deref &&
440 "'*' is the only unary operator that produces an lvalue");
441 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
442}
443
444LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
445 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
446 const char *StrData = E->getStrData();
447 unsigned Len = E->getByteLength();
448
449 // FIXME: Can cache/reuse these within the module.
450 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
451
452 // Create a global variable for this.
453 C = new llvm::GlobalVariable(C->getType(), true,
454 llvm::GlobalValue::InternalLinkage,
455 C, ".str", CurFn->getParent());
456 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
457 llvm::Constant *Zeros[] = { Zero, Zero };
458 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
459 return LValue::MakeAddr(C);
460}
461
462LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
463 std::string FunctionName(CurFuncDecl->getName());
464 std::string GlobalVarName;
465
466 switch (E->getIdentType()) {
467 default:
468 assert(0 && "unknown pre-defined ident type");
469 case PreDefinedExpr::Func:
470 GlobalVarName = "__func__.";
471 break;
472 case PreDefinedExpr::Function:
473 GlobalVarName = "__FUNCTION__.";
474 break;
475 case PreDefinedExpr::PrettyFunction:
476 // FIXME:: Demangle C++ method names
477 GlobalVarName = "__PRETTY_FUNCTION__.";
478 break;
479 }
480
481 GlobalVarName += CurFuncDecl->getName();
482
483 // FIXME: Can cache/reuse these within the module.
484 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
485
486 // Create a global variable for this.
487 C = new llvm::GlobalVariable(C->getType(), true,
488 llvm::GlobalValue::InternalLinkage,
489 C, GlobalVarName, CurFn->getParent());
490 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
491 llvm::Constant *Zeros[] = { Zero, Zero };
492 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
493 return LValue::MakeAddr(C);
494}
495
496LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000497 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000498 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000499
500 // If the base is a vector type, then we are forming a vector element lvalue
501 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000502 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000503 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000504 LValue LHS = EmitLValue(E->getLHS());
505 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000506 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000507 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000508 }
509
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000510 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000511 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000512
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000513 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000514 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000515 bool IdxSigned = IdxTy->isSignedIntegerType();
516 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
517 if (IdxBitwidth != LLVMPointerWidth)
518 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
519 IdxSigned, "idxprom");
520
521 // We know that the pointer points to a type of the correct size, unless the
522 // size is a VLA.
523 if (!E->getType()->isConstantSizeType(getContext()))
524 assert(0 && "VLA idx not implemented");
525 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
526}
527
Chris Lattner65520192007-08-02 23:37:31 +0000528LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000529EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000530 // Emit the base vector as an l-value.
531 LValue Base = EmitLValue(E->getBase());
532 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
533
Chris Lattnera0d03a72007-08-03 17:31:20 +0000534 return LValue::MakeOCUVectorElt(Base.getAddress(),
535 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000536}
537
Chris Lattner4b009652007-07-25 00:24:17 +0000538//===--------------------------------------------------------------------===//
539// Expression Emission
540//===--------------------------------------------------------------------===//
541
542RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000543 assert(E && !hasAggregateLLVMType(E->getType()) &&
544 "Invalid scalar expression to emit");
Chris Lattner4b009652007-07-25 00:24:17 +0000545
546 switch (E->getStmtClass()) {
547 default:
548 fprintf(stderr, "Unimplemented expr!\n");
549 E->dump();
550 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
551
552 // l-values.
553 case Expr::DeclRefExprClass:
554 // DeclRef's of EnumConstantDecl's are simple rvalues.
555 if (const EnumConstantDecl *EC =
556 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
557 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
558 return EmitLoadOfLValue(E);
559 case Expr::ArraySubscriptExprClass:
560 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000561 case Expr::OCUVectorElementExprClass:
Chris Lattnera735fac2007-08-03 00:16:29 +0000562 return EmitLoadOfLValue(E);
Chris Lattner4b009652007-07-25 00:24:17 +0000563 case Expr::PreDefinedExprClass:
564 case Expr::StringLiteralClass:
565 return RValue::get(EmitLValue(E).getAddress());
566
567 // Leaf expressions.
568 case Expr::IntegerLiteralClass:
569 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
570 case Expr::FloatingLiteralClass:
571 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
572 case Expr::CharacterLiteralClass:
573 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner4ca7e752007-08-03 17:51:03 +0000574 case Expr::TypesCompatibleExprClass:
575 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000576
577 // Operators.
578 case Expr::ParenExprClass:
579 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
580 case Expr::UnaryOperatorClass:
581 return EmitUnaryOperator(cast<UnaryOperator>(E));
582 case Expr::SizeOfAlignOfTypeExprClass:
583 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
584 E->getType(),
585 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
586 case Expr::ImplicitCastExprClass:
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000587 return EmitImplicitCastExpr(cast<ImplicitCastExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000588 case Expr::CastExprClass:
589 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
590 case Expr::CallExprClass:
591 return EmitCallExpr(cast<CallExpr>(E));
592 case Expr::BinaryOperatorClass:
593 return EmitBinaryOperator(cast<BinaryOperator>(E));
594
595 case Expr::ConditionalOperatorClass:
596 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000597 case Expr::ChooseExprClass:
598 return EmitChooseExpr(cast<ChooseExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000599 }
Chris Lattner4b009652007-07-25 00:24:17 +0000600}
601
602RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
603 return RValue::get(llvm::ConstantInt::get(E->getValue()));
604}
605RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
606 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
607 E->getValue()));
608}
609RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
610 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
611 E->getValue()));
612}
613
Chris Lattner4ca7e752007-08-03 17:51:03 +0000614RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
615 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
616 E->typesAreCompatible()));
617}
618
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000619/// EmitChooseExpr - Implement __builtin_choose_expr.
620RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
621 llvm::APSInt CondVal(32);
622 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
623 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
624
625 // Emit the LHS or RHS as appropriate.
626 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
627}
628
Chris Lattner4ca7e752007-08-03 17:51:03 +0000629
Chris Lattner4b009652007-07-25 00:24:17 +0000630RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
631 // Emit subscript expressions in rvalue context's. For most cases, this just
632 // loads the lvalue formed by the subscript expr. However, we have to be
633 // careful, because the base of a vector subscript is occasionally an rvalue,
634 // so we can't get it as an lvalue.
635 if (!E->getBase()->getType()->isVectorType())
636 return EmitLoadOfLValue(E);
637
638 // Handle the vector case. The base must be a vector, the index must be an
639 // integer value.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000640 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
641 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000642
643 // FIXME: Convert Idx to i32 type.
644
645 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
646}
647
648// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
649// have to handle a more broad range of conversions than explicit casts, as they
650// handle things like function to ptr-to-function decay etc.
651RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000652 RValue Src = EmitExpr(Op);
Chris Lattner4b009652007-07-25 00:24:17 +0000653
654 // If the destination is void, just evaluate the source.
655 if (DestTy->isVoidType())
656 return RValue::getAggregate(0);
657
Chris Lattner2af72ac2007-08-08 17:43:05 +0000658 return EmitConversion(Src, Op->getType(), DestTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000659}
660
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000661/// EmitImplicitCastExpr - Implicit casts are the same as normal casts, but also
662/// handle things like function to pointer-to-function decay, and array to
663/// pointer decay.
664RValue CodeGenFunction::EmitImplicitCastExpr(const ImplicitCastExpr *E) {
665 const Expr *Op = E->getSubExpr();
666 QualType OpTy = Op->getType().getCanonicalType();
667
668 // If this is due to array->pointer conversion, emit the array expression as
669 // an l-value.
670 if (isa<ArrayType>(OpTy)) {
671 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
672 // will not true when we add support for VLAs.
673 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
674
675 assert(isa<llvm::PointerType>(V->getType()) &&
676 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
677 ->getElementType()) &&
678 "Doesn't support VLAs yet!");
679 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
680 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
681 }
682
683 return EmitCastExpr(Op, E->getType());
684}
685
Chris Lattner4b009652007-07-25 00:24:17 +0000686RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000687 if (const ImplicitCastExpr *IcExpr =
688 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
689 if (const DeclRefExpr *DRExpr =
690 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
691 if (const FunctionDecl *FDecl =
692 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
693 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
694 return EmitBuiltinExpr(builtinID, E);
695
Chris Lattner2af72ac2007-08-08 17:43:05 +0000696 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000697
698 // The callee type will always be a pointer to function type, get the function
699 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000700 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000701 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
702
703 // Get information about the argument types.
704 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
705
706 // Calling unprototyped functions provides no argument info.
707 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
708 ArgTyIt = FTP->arg_type_begin();
709 ArgTyEnd = FTP->arg_type_end();
710 }
711
712 llvm::SmallVector<llvm::Value*, 16> Args;
713
Chris Lattner59802042007-08-10 17:02:28 +0000714 // Handle struct-return functions by passing a pointer to the location that
715 // we would like to return into.
716 if (hasAggregateLLVMType(E->getType())) {
717 // Create a temporary alloca to hold the result of the call. :(
718 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
719 // FIXME: set the stret attribute on the argument.
720 }
721
Chris Lattner4b009652007-07-25 00:24:17 +0000722 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000723 QualType ArgTy = E->getArg(i)->getType();
724 RValue ArgVal = EmitExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000725
726 // If this argument has prototype information, convert it.
727 if (ArgTyIt != ArgTyEnd) {
728 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
729 } else {
730 // Otherwise, if passing through "..." or to a function with no prototype,
731 // perform the "default argument promotions" (C99 6.5.2.2p6), which
732 // includes the usual unary conversions, but also promotes float to
733 // double.
734 if (const BuiltinType *BT =
735 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
736 if (BT->getKind() == BuiltinType::Float)
737 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
738 llvm::Type::DoubleTy,"tmp"));
739 }
740 }
741
742
743 if (ArgVal.isScalar())
744 Args.push_back(ArgVal.getVal());
745 else // Pass by-address. FIXME: Set attribute bit on call.
746 Args.push_back(ArgVal.getAggregateAddr());
747 }
748
Chris Lattnera9572252007-08-01 06:24:52 +0000749 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000750 if (V->getType() != llvm::Type::VoidTy)
751 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000752 else if (hasAggregateLLVMType(E->getType()))
753 // Struct return.
754 return RValue::getAggregate(Args[0]);
755
Chris Lattner4b009652007-07-25 00:24:17 +0000756 return RValue::get(V);
757}
758
759
760//===----------------------------------------------------------------------===//
761// Unary Operator Emission
762//===----------------------------------------------------------------------===//
763
Chris Lattner4b009652007-07-25 00:24:17 +0000764RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
765 switch (E->getOpcode()) {
766 default:
767 printf("Unimplemented unary expr!\n");
768 E->dump();
769 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
770 case UnaryOperator::PostInc:
771 case UnaryOperator::PostDec:
772 case UnaryOperator::PreInc :
773 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
774 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
775 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
776 case UnaryOperator::Plus : return EmitUnaryPlus(E);
777 case UnaryOperator::Minus : return EmitUnaryMinus(E);
778 case UnaryOperator::Not : return EmitUnaryNot(E);
779 case UnaryOperator::LNot : return EmitUnaryLNot(E);
780 case UnaryOperator::SizeOf :
781 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
782 case UnaryOperator::AlignOf :
783 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
784 // FIXME: real/imag
785 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
786 }
787}
788
789RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
790 LValue LV = EmitLValue(E->getSubExpr());
791 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
792
793 // We know the operand is real or pointer type, so it must be an LLVM scalar.
794 assert(InVal.isScalar() && "Unknown thing to increment");
795 llvm::Value *InV = InVal.getVal();
796
797 int AmountVal = 1;
798 if (E->getOpcode() == UnaryOperator::PreDec ||
799 E->getOpcode() == UnaryOperator::PostDec)
800 AmountVal = -1;
801
802 llvm::Value *NextVal;
803 if (isa<llvm::IntegerType>(InV->getType())) {
804 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
805 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
806 } else if (InV->getType()->isFloatingPoint()) {
807 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
808 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
809 } else {
810 // FIXME: This is not right for pointers to VLA types.
811 assert(isa<llvm::PointerType>(InV->getType()));
812 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
813 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
814 }
815
816 RValue NextValToStore = RValue::get(NextVal);
817
818 // Store the updated result through the lvalue.
819 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
820
821 // If this is a postinc, return the value read from memory, otherwise use the
822 // updated value.
823 if (E->getOpcode() == UnaryOperator::PreDec ||
824 E->getOpcode() == UnaryOperator::PreInc)
825 return NextValToStore;
826 else
827 return InVal;
828}
829
830/// C99 6.5.3.2
831RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
832 // The address of the operand is just its lvalue. It cannot be a bitfield.
833 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
834}
835
836RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000837 assert(E->getType().getCanonicalType() ==
838 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
839 // Unary plus just returns its value.
840 return EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000841}
842
843RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000844 assert(E->getType().getCanonicalType() ==
845 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
846
Chris Lattner4b009652007-07-25 00:24:17 +0000847 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000848 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000849
850 if (V.isScalar())
851 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
852
853 assert(0 && "FIXME: This doesn't handle complex operands yet");
854}
855
856RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
857 // Unary not performs promotions, then complements its integer operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000858 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000859
860 if (V.isScalar())
861 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
862
863 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
864}
865
866
867/// C99 6.5.3.3
868RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
869 // Compare operand to zero.
870 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
871
872 // Invert value.
873 // TODO: Could dynamically modify easy computations here. For example, if
874 // the operand is an icmp ne, turn into icmp eq.
875 BoolVal = Builder.CreateNot(BoolVal, "lnot");
876
877 // ZExt result to int.
878 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
879}
880
881/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
882/// an integer (RetType).
883RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
884 QualType RetType, bool isSizeOf) {
885 /// FIXME: This doesn't handle VLAs yet!
886 std::pair<uint64_t, unsigned> Info =
887 getContext().getTypeInfo(TypeToSize, SourceLocation());
888
889 uint64_t Val = isSizeOf ? Info.first : Info.second;
890 Val /= 8; // Return size in bytes, not bits.
891
892 assert(RetType->isIntegerType() && "Result type must be an integer!");
893
894 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
895 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
896}
897
898
899//===--------------------------------------------------------------------===//
900// Binary Operator Emission
901//===--------------------------------------------------------------------===//
902
Chris Lattner4b009652007-07-25 00:24:17 +0000903
904/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
905/// are strange in that the result of the operation is not the same type as the
906/// intermediate computation. This function emits the LHS and RHS operands of
907/// the compound assignment, promoting them to their common computation type.
908///
909/// Since the LHS is an lvalue, and the result is stored back through it, we
910/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
911/// RHS values are both in the computation type for the operator.
912void CodeGenFunction::
913EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
914 LValue &LHSLV, RValue &LHS, RValue &RHS) {
915 LHSLV = EmitLValue(E->getLHS());
916
917 // Load the LHS and RHS operands.
918 QualType LHSTy = E->getLHS()->getType();
919 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner2af72ac2007-08-08 17:43:05 +0000920 RHS = EmitExpr(E->getRHS());
921 QualType RHSTy = E->getRHS()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000922
923 // Convert the LHS and RHS to the common evaluation type.
924 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
925 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
926}
927
928/// EmitCompoundAssignmentResult - Given a result value in the computation type,
929/// truncate it down to the actual result type, store it through the LHS lvalue,
930/// and return it.
931RValue CodeGenFunction::
932EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
933 LValue LHSLV, RValue ResV) {
934
935 // Truncate back to the destination type.
936 if (E->getComputationType() != E->getType())
937 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
938
939 // Store the result value into the LHS.
940 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
941
942 // Return the result.
943 return ResV;
944}
945
946
947RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
948 RValue LHS, RHS;
949 switch (E->getOpcode()) {
950 default:
951 fprintf(stderr, "Unimplemented binary expr!\n");
952 E->dump();
953 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
954 case BinaryOperator::Mul:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000955 LHS = EmitExpr(E->getLHS());
956 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000957 return EmitMul(LHS, RHS, E->getType());
958 case BinaryOperator::Div:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000959 LHS = EmitExpr(E->getLHS());
960 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000961 return EmitDiv(LHS, RHS, E->getType());
962 case BinaryOperator::Rem:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000963 LHS = EmitExpr(E->getLHS());
964 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000965 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerbf49e992007-08-08 17:49:18 +0000966 case BinaryOperator::Add:
967 LHS = EmitExpr(E->getLHS());
968 RHS = EmitExpr(E->getRHS());
969 if (!E->getType()->isPointerType())
970 return EmitAdd(LHS, RHS, E->getType());
971
972 return EmitPointerAdd(LHS, E->getLHS()->getType(),
973 RHS, E->getRHS()->getType(), E->getType());
974 case BinaryOperator::Sub:
975 LHS = EmitExpr(E->getLHS());
976 RHS = EmitExpr(E->getRHS());
977
978 if (!E->getLHS()->getType()->isPointerType())
979 return EmitSub(LHS, RHS, E->getType());
980
981 return EmitPointerSub(LHS, E->getLHS()->getType(),
982 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +0000983 case BinaryOperator::Shl:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000984 LHS = EmitExpr(E->getLHS());
985 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000986 return EmitShl(LHS, RHS, E->getType());
987 case BinaryOperator::Shr:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000988 LHS = EmitExpr(E->getLHS());
989 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000990 return EmitShr(LHS, RHS, E->getType());
991 case BinaryOperator::And:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000992 LHS = EmitExpr(E->getLHS());
993 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000994 return EmitAnd(LHS, RHS, E->getType());
995 case BinaryOperator::Xor:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000996 LHS = EmitExpr(E->getLHS());
997 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000998 return EmitXor(LHS, RHS, E->getType());
999 case BinaryOperator::Or :
Chris Lattnerbf49e992007-08-08 17:49:18 +00001000 LHS = EmitExpr(E->getLHS());
1001 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001002 return EmitOr(LHS, RHS, E->getType());
1003 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1004 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1005 case BinaryOperator::LT:
1006 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1007 llvm::ICmpInst::ICMP_SLT,
1008 llvm::FCmpInst::FCMP_OLT);
1009 case BinaryOperator::GT:
1010 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1011 llvm::ICmpInst::ICMP_SGT,
1012 llvm::FCmpInst::FCMP_OGT);
1013 case BinaryOperator::LE:
1014 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1015 llvm::ICmpInst::ICMP_SLE,
1016 llvm::FCmpInst::FCMP_OLE);
1017 case BinaryOperator::GE:
1018 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1019 llvm::ICmpInst::ICMP_SGE,
1020 llvm::FCmpInst::FCMP_OGE);
1021 case BinaryOperator::EQ:
1022 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1023 llvm::ICmpInst::ICMP_EQ,
1024 llvm::FCmpInst::FCMP_OEQ);
1025 case BinaryOperator::NE:
1026 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1027 llvm::ICmpInst::ICMP_NE,
1028 llvm::FCmpInst::FCMP_UNE);
1029 case BinaryOperator::Assign:
1030 return EmitBinaryAssign(E);
1031
1032 case BinaryOperator::MulAssign: {
1033 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1034 LValue LHSLV;
1035 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1036 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1037 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1038 }
1039 case BinaryOperator::DivAssign: {
1040 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1041 LValue LHSLV;
1042 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1043 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1044 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1045 }
1046 case BinaryOperator::RemAssign: {
1047 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1048 LValue LHSLV;
1049 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1050 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1051 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1052 }
1053 case BinaryOperator::AddAssign: {
1054 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1055 LValue LHSLV;
1056 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1057 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1058 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1059 }
1060 case BinaryOperator::SubAssign: {
1061 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1062 LValue LHSLV;
1063 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1064 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1065 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1066 }
1067 case BinaryOperator::ShlAssign: {
1068 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1069 LValue LHSLV;
1070 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1071 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1072 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1073 }
1074 case BinaryOperator::ShrAssign: {
1075 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1076 LValue LHSLV;
1077 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1078 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1079 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1080 }
1081 case BinaryOperator::AndAssign: {
1082 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1083 LValue LHSLV;
1084 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1085 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1086 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1087 }
1088 case BinaryOperator::OrAssign: {
1089 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1090 LValue LHSLV;
1091 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1092 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1093 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1094 }
1095 case BinaryOperator::XorAssign: {
1096 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1097 LValue LHSLV;
1098 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1099 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1100 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1101 }
1102 case BinaryOperator::Comma: return EmitBinaryComma(E);
1103 }
1104}
1105
1106RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattnera7300102007-08-21 04:59:27 +00001107 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
Chris Lattner4b009652007-07-25 00:24:17 +00001108}
1109
1110RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner9a4e2c62007-08-21 16:34:16 +00001111 if (LHS.getVal()->getType()->isFloatingPoint())
1112 return RValue::get(Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div"));
1113 else if (ResTy->isUnsignedIntegerType())
1114 return RValue::get(Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div"));
1115 else
1116 return RValue::get(Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div"));
Chris Lattner4b009652007-07-25 00:24:17 +00001117}
1118
1119RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner9a4e2c62007-08-21 16:34:16 +00001120 // Rem in C can't be a floating point type: C99 6.5.5p2.
1121 if (ResTy->isUnsignedIntegerType())
1122 return RValue::get(Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem"));
1123 else
1124 return RValue::get(Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem"));
Chris Lattner4b009652007-07-25 00:24:17 +00001125}
1126
1127RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattnera7300102007-08-21 04:59:27 +00001128 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattner4b009652007-07-25 00:24:17 +00001129}
1130
1131RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1132 RValue RHS, QualType RHSTy,
1133 QualType ResTy) {
1134 llvm::Value *LHSValue = LHS.getVal();
1135 llvm::Value *RHSValue = RHS.getVal();
1136 if (LHSTy->isPointerType()) {
1137 // pointer + int
1138 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1139 } else {
1140 // int + pointer
1141 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1142 }
1143}
1144
1145RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner9a4e2c62007-08-21 16:34:16 +00001146 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
Chris Lattner4b009652007-07-25 00:24:17 +00001147}
1148
1149RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1150 RValue RHS, QualType RHSTy,
1151 QualType ResTy) {
1152 llvm::Value *LHSValue = LHS.getVal();
1153 llvm::Value *RHSValue = RHS.getVal();
1154 if (const PointerType *RHSPtrType =
1155 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1156 // pointer - pointer
1157 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1158 QualType LHSElementType = LHSPtrType->getPointeeType();
1159 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1160 "can't subtract pointers with differing element types");
1161 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1162 SourceLocation()) / 8;
1163 const llvm::Type *ResultType = ConvertType(ResTy);
1164 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1165 "sub.ptr.lhs.cast");
1166 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1167 "sub.ptr.rhs.cast");
1168 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1169 "sub.ptr.sub");
1170
1171 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1172 // remainder. As such, we handle common power-of-two cases here to generate
1173 // better code.
1174 if (llvm::isPowerOf2_64(ElementSize)) {
1175 llvm::Value *ShAmt =
1176 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1177 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1178 } else {
1179 // Otherwise, do a full sdiv.
1180 llvm::Value *BytesPerElement =
1181 llvm::ConstantInt::get(ResultType, ElementSize);
1182 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1183 "sub.ptr.div"));
1184 }
1185 } else {
1186 // pointer - int
1187 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1188 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1189 }
1190}
1191
Chris Lattner4b009652007-07-25 00:24:17 +00001192RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1193 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1194
1195 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1196 // RHS to the same size as the LHS.
1197 if (LHS->getType() != RHS->getType())
1198 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1199
1200 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1201}
1202
1203RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1204 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1205
1206 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1207 // RHS to the same size as the LHS.
1208 if (LHS->getType() != RHS->getType())
1209 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1210
1211 if (ResTy->isUnsignedIntegerType())
1212 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1213 else
1214 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1215}
1216
1217RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1218 unsigned UICmpOpc, unsigned SICmpOpc,
1219 unsigned FCmpOpc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001220 llvm::Value *Result;
Chris Lattner5280c5f2007-08-21 16:57:55 +00001221 QualType LHSTy = E->getLHS()->getType();
1222 if (!LHSTy->isComplexType()) {
1223 RValue LHS = EmitExpr(E->getLHS());
1224 RValue RHS = EmitExpr(E->getRHS());
1225
1226 if (LHSTy->isRealFloatingType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001227 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1228 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner5280c5f2007-08-21 16:57:55 +00001229 } else if (LHSTy->isUnsignedIntegerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001230 // FIXME: This check isn't right for "unsigned short < int" where ushort
1231 // promotes to int and does a signed compare.
1232 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1233 LHS.getVal(), RHS.getVal(), "cmp");
1234 } else {
1235 // Signed integers and pointers.
1236 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1237 LHS.getVal(), RHS.getVal(), "cmp");
1238 }
1239 } else {
Chris Lattner5280c5f2007-08-21 16:57:55 +00001240 // Complex Comparison: can only be an equality comparison.
1241 ComplexPairTy LHS = EmitComplexExpr(E->getLHS());
1242 ComplexPairTy RHS = EmitComplexExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001243
Chris Lattner5280c5f2007-08-21 16:57:55 +00001244 QualType CETy =
1245 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
1246
1247 llvm::Value *ResultR, *ResultI;
1248 if (CETy->isRealFloatingType()) {
1249 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1250 LHS.first, RHS.first, "cmp.r");
1251 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1252 LHS.second, RHS.second, "cmp.i");
Chris Lattner4b009652007-07-25 00:24:17 +00001253 } else {
Chris Lattner5280c5f2007-08-21 16:57:55 +00001254 unsigned Opc = CETy->isUnsignedIntegerType() ? UICmpOpc : SICmpOpc;
1255 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)Opc,
1256 LHS.first, RHS.first, "cmp.r");
1257 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)Opc,
1258 LHS.second, RHS.second, "cmp.i");
Chris Lattner4b009652007-07-25 00:24:17 +00001259 }
Chris Lattner5280c5f2007-08-21 16:57:55 +00001260
1261 if (E->getOpcode() == BinaryOperator::EQ) {
1262 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1263 } else {
1264 assert(E->getOpcode() == BinaryOperator::NE &&
1265 "Complex comparison other than == or != ?");
1266 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1267 }
Chris Lattner4b009652007-07-25 00:24:17 +00001268 }
1269
1270 // ZExt result to int.
1271 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1272}
1273
1274RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1275 if (LHS.isScalar())
1276 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1277
1278 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1279}
1280
1281RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1282 if (LHS.isScalar())
1283 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1284
1285 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1286}
1287
1288RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1289 if (LHS.isScalar())
1290 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1291
1292 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1293}
1294
1295RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1296 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1297
1298 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1299 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1300
1301 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1302 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1303
1304 EmitBlock(RHSBlock);
1305 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1306
1307 // Reaquire the RHS block, as there may be subblocks inserted.
1308 RHSBlock = Builder.GetInsertBlock();
1309 EmitBlock(ContBlock);
1310
1311 // Create a PHI node. If we just evaluted the LHS condition, the result is
1312 // false. If we evaluated both, the result is the RHS condition.
1313 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1314 PN->reserveOperandSpace(2);
1315 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1316 PN->addIncoming(RHSCond, RHSBlock);
1317
1318 // ZExt result to int.
1319 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1320}
1321
1322RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1323 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1324
1325 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1326 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1327
1328 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1329 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1330
1331 EmitBlock(RHSBlock);
1332 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1333
1334 // Reaquire the RHS block, as there may be subblocks inserted.
1335 RHSBlock = Builder.GetInsertBlock();
1336 EmitBlock(ContBlock);
1337
1338 // Create a PHI node. If we just evaluted the LHS condition, the result is
1339 // true. If we evaluated both, the result is the RHS condition.
1340 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1341 PN->reserveOperandSpace(2);
1342 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1343 PN->addIncoming(RHSCond, RHSBlock);
1344
1345 // ZExt result to int.
1346 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1347}
1348
1349RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +00001350 assert(E->getLHS()->getType().getCanonicalType() ==
1351 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner4b009652007-07-25 00:24:17 +00001352 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2af72ac2007-08-08 17:43:05 +00001353 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001354
1355 // Store the value into the LHS.
1356 EmitStoreThroughLValue(RHS, LHS, E->getType());
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +00001357
1358 // Return the RHS.
Chris Lattner4b009652007-07-25 00:24:17 +00001359 return RHS;
1360}
1361
1362
1363RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1364 EmitExpr(E->getLHS());
1365 return EmitExpr(E->getRHS());
1366}
1367
1368RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1369 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1370 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1371 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1372
1373 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1374 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1375
Chris Lattner4b009652007-07-25 00:24:17 +00001376 EmitBlock(LHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001377 // Handle the GNU extension for missing LHS.
1378 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner4b009652007-07-25 00:24:17 +00001379 Builder.CreateBr(ContBlock);
1380 LHSBlock = Builder.GetInsertBlock();
1381
1382 EmitBlock(RHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001383
1384 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +00001385 Builder.CreateBr(ContBlock);
1386 RHSBlock = Builder.GetInsertBlock();
1387
1388 const llvm::Type *LHSType = LHSValue->getType();
1389 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1390
1391 EmitBlock(ContBlock);
1392 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1393 PN->reserveOperandSpace(2);
1394 PN->addIncoming(LHSValue, LHSBlock);
1395 PN->addIncoming(RHSValue, RHSBlock);
1396
1397 return RValue::get(PN);
1398}