blob: 9697686b1a7ccbe507b16f14b6075df138d36eba [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"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/Support/MathExtras.h"
22using namespace clang;
23using namespace CodeGen;
24
25//===--------------------------------------------------------------------===//
26// Miscellaneous Helper Methods
27//===--------------------------------------------------------------------===//
28
29/// CreateTempAlloca - This creates a alloca and inserts it into the entry
30/// block.
31llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
32 const char *Name) {
33 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
34}
35
36/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37/// expression and compare the result against zero, returning an Int1Ty value.
38llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
39 QualType Ty;
40 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
41 return ConvertScalarValueToBool(Val, Ty);
42}
43
44/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
45/// load the real and imaginary pieces, returning them as Real/Imag.
46void CodeGenFunction::EmitLoadOfComplex(RValue V,
47 llvm::Value *&Real, llvm::Value *&Imag){
48 llvm::Value *Ptr = V.getAggregateAddr();
49
50 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
51 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
52 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
53 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
54
55 // FIXME: Handle volatility.
56 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
96 // The source value may be an integer, or a pointer.
97 assert(Val.isScalar() && "Can only convert from integer or pointer");
98 if (isa<llvm::PointerType>(Val.getVal()->getType()))
99 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
100 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
101 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
102 }
103
104 if (isa<PointerType>(ValTy)) {
105 // Must be an ptr to int cast.
106 const llvm::Type *DestTy = ConvertType(DstTy);
107 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
108 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
109 }
110
111 // Finally, we have the arithmetic types: real int/float and complex
112 // int/float. Handle real->real conversions first, they are the most
113 // common.
114 if (Val.isScalar() && DstTy->isRealType()) {
115 // We know that these are representable as scalars in LLVM, convert to LLVM
116 // types since they are easier to reason about.
117 llvm::Value *SrcVal = Val.getVal();
118 const llvm::Type *DestTy = ConvertType(DstTy);
119 if (SrcVal->getType() == DestTy) return Val;
120
121 llvm::Value *Result;
122 if (isa<llvm::IntegerType>(SrcVal->getType())) {
123 bool InputSigned = ValTy->isSignedIntegerType();
124 if (isa<llvm::IntegerType>(DestTy))
125 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
126 else if (InputSigned)
127 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
128 else
129 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
130 } else {
131 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
132 if (isa<llvm::IntegerType>(DestTy)) {
133 if (DstTy->isSignedIntegerType())
134 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
135 else
136 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
137 } else {
138 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
139 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
140 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
141 else
142 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
143 }
144 }
145 return RValue::get(Result);
146 }
147
148 assert(0 && "FIXME: We don't support complex conversions yet!");
149}
150
151
152/// ConvertScalarValueToBool - Convert the specified expression value to a
153/// boolean (i1) truth value. This is equivalent to "Val == 0".
154llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
155 Ty = Ty.getCanonicalType();
156 llvm::Value *Result;
157 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
158 switch (BT->getKind()) {
159 default: assert(0 && "Unknown scalar value");
160 case BuiltinType::Bool:
161 Result = Val.getVal();
162 // Bool is already evaluated right.
163 assert(Result->getType() == llvm::Type::Int1Ty &&
164 "Unexpected bool value type!");
165 return Result;
166 case BuiltinType::Char_S:
167 case BuiltinType::Char_U:
168 case BuiltinType::SChar:
169 case BuiltinType::UChar:
170 case BuiltinType::Short:
171 case BuiltinType::UShort:
172 case BuiltinType::Int:
173 case BuiltinType::UInt:
174 case BuiltinType::Long:
175 case BuiltinType::ULong:
176 case BuiltinType::LongLong:
177 case BuiltinType::ULongLong:
178 // Code below handles simple integers.
179 break;
180 case BuiltinType::Float:
181 case BuiltinType::Double:
182 case BuiltinType::LongDouble: {
183 // Compare against 0.0 for fp scalars.
184 Result = Val.getVal();
185 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
186 // FIXME: llvm-gcc produces a une comparison: validate this is right.
187 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
188 return Result;
189 }
190 }
191 } else if (isa<PointerType>(Ty) ||
192 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
193 // Code below handles this fine.
194 } else {
195 assert(isa<ComplexType>(Ty) && "Unknwon type!");
196 assert(0 && "FIXME: comparisons against complex not implemented yet");
197 }
198
199 // Usual case for integers, pointers, and enums: compare against zero.
200 Result = Val.getVal();
201
202 // Because of the type rules of C, we often end up computing a logical value,
203 // then zero extending it to int, then wanting it as a logical value again.
204 // Optimize this common case.
205 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
206 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
207 Result = ZI->getOperand(0);
208 ZI->eraseFromParent();
209 return Result;
210 }
211 }
212
213 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
214 return Builder.CreateICmpNE(Result, Zero, "tobool");
215}
216
217//===----------------------------------------------------------------------===//
218// LValue Expression Emission
219//===----------------------------------------------------------------------===//
220
221/// EmitLValue - Emit code to compute a designator that specifies the location
222/// of the expression.
223///
224/// This can return one of two things: a simple address or a bitfield
225/// reference. In either case, the LLVM Value* in the LValue structure is
226/// guaranteed to be an LLVM pointer type.
227///
228/// If this returns a bitfield reference, nothing about the pointee type of
229/// the LLVM value is known: For example, it may not be a pointer to an
230/// integer.
231///
232/// If this returns a normal address, and if the lvalue's C type is fixed
233/// size, this method guarantees that the returned pointer type will point to
234/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
235/// variable length type, this is not possible.
236///
237LValue CodeGenFunction::EmitLValue(const Expr *E) {
238 switch (E->getStmtClass()) {
239 default:
240 fprintf(stderr, "Unimplemented lvalue expr!\n");
241 E->dump();
242 return LValue::MakeAddr(llvm::UndefValue::get(
243 llvm::PointerType::get(llvm::Type::Int32Ty)));
244
245 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
246 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
247 case Expr::PreDefinedExprClass:
248 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
249 case Expr::StringLiteralClass:
250 return EmitStringLiteralLValue(cast<StringLiteral>(E));
251
252 case Expr::UnaryOperatorClass:
253 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
254 case Expr::ArraySubscriptExprClass:
255 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000256 case Expr::OCUVectorElementExprClass:
257 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000258 }
259}
260
261/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
262/// this method emits the address of the lvalue, then loads the result as an
263/// rvalue, returning the rvalue.
264RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
265 ExprType = ExprType.getCanonicalType();
266
267 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
276 // Otherwise, we have an aggregate lvalue.
277 return RValue::getAggregate(Ptr);
278 }
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 Lattner944f7962007-08-03 16:18:34 +0000297 QualType ExprType) {
298 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.
304 if (!isa<VectorType>(ExprType)) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000305 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000306 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
307 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
308 }
309
310 // If the source and destination have the same number of elements, use a
311 // vector shuffle instead of insert/extracts.
312 unsigned NumResultElts = cast<VectorType>(ExprType)->getNumElements();
313 unsigned NumSourceElts =
314 cast<llvm::VectorType>(Vec->getType())->getNumElements();
315
316 if (NumResultElts == NumSourceElts) {
317 llvm::SmallVector<llvm::Constant*, 4> Mask;
318 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000319 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000320 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
321 }
322
323 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
324 Vec = Builder.CreateShuffleVector(Vec,
325 llvm::UndefValue::get(Vec->getType()),
326 MaskV, "tmp");
327 return RValue::get(Vec);
328 }
329
330 // Start out with an undef of the result type.
331 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
332
333 // Extract/Insert each element of the result.
334 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000335 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000336 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
337 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
338
339 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
340 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
341 }
342
343 return RValue::get(Result);
344}
345
346
Chris Lattner4b009652007-07-25 00:24:17 +0000347RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
348 return EmitLoadOfLValue(EmitLValue(E), E->getType());
349}
350
351
352/// EmitStoreThroughLValue - Store the specified rvalue into the specified
353/// lvalue, where both are guaranteed to the have the same type, and that type
354/// is 'Ty'.
355void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
356 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000357 if (!Dst.isSimple()) {
358 if (Dst.isVectorElt()) {
359 // Read/modify/write the vector, inserting the new element.
360 // FIXME: Volatility.
361 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
362 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
363 Dst.getVectorIdx(), "vecins");
364 Builder.CreateStore(Vec, Dst.getVectorAddr());
365 return;
366 }
Chris Lattner4b009652007-07-25 00:24:17 +0000367
Chris Lattner5bfdd232007-08-03 16:28:33 +0000368 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000369 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000370 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
371
372 assert(0 && "FIXME: Don't support store to bitfield yet");
373 }
Chris Lattner4b009652007-07-25 00:24:17 +0000374
375 llvm::Value *DstAddr = Dst.getAddress();
376 if (Src.isScalar()) {
377 // FIXME: Handle volatility etc.
378 const llvm::Type *SrcTy = Src.getVal()->getType();
379 const llvm::Type *AddrTy =
380 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
381
382 if (AddrTy != SrcTy)
383 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
384 "storetmp");
385 Builder.CreateStore(Src.getVal(), DstAddr);
386 return;
387 }
388
389 // Don't use memcpy for complex numbers.
390 if (Ty->isComplexType()) {
391 llvm::Value *Real, *Imag;
392 EmitLoadOfComplex(Src, Real, Imag);
393 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
394 return;
395 }
396
397 // Aggregate assignment turns into llvm.memcpy.
398 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
399 llvm::Value *SrcAddr = Src.getAggregateAddr();
400
401 if (DstAddr->getType() != SBP)
402 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
403 if (SrcAddr->getType() != SBP)
404 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
405
406 unsigned Align = 1; // FIXME: Compute type alignments.
407 unsigned Size = 1234; // FIXME: Compute type sizes.
408
409 // FIXME: Handle variable sized types.
410 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
411 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
412
413 llvm::Value *MemCpyOps[4] = {
414 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
415 };
416
Chris Lattnera9572252007-08-01 06:24:52 +0000417 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
Chris Lattner4b009652007-07-25 00:24:17 +0000418}
419
Chris Lattner5bfdd232007-08-03 16:28:33 +0000420void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
421 QualType Ty) {
422 // This access turns into a read/modify/write of the vector. Load the input
423 // value now.
424 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
425 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000426 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000427
428 llvm::Value *SrcVal = Src.getVal();
429
Chris Lattner940966d2007-08-03 16:37:04 +0000430 if (const VectorType *VTy = Ty->getAsVectorType()) {
431 unsigned NumSrcElts = VTy->getNumElements();
432
433 // Extract/Insert each element.
434 for (unsigned i = 0; i != NumSrcElts; ++i) {
435 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
436 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
437
Chris Lattnera0d03a72007-08-03 17:31:20 +0000438 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000439 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
440 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
441 }
442 } else {
443 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000444 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000445 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
446 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000447 }
448
Chris Lattner5bfdd232007-08-03 16:28:33 +0000449 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
450}
451
Chris Lattner4b009652007-07-25 00:24:17 +0000452
453LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
454 const Decl *D = E->getDecl();
455 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
456 llvm::Value *V = LocalDeclMap[D];
457 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
458 return LValue::MakeAddr(V);
459 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
460 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
461 }
462 assert(0 && "Unimp declref");
463}
464
465LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
466 // __extension__ doesn't affect lvalue-ness.
467 if (E->getOpcode() == UnaryOperator::Extension)
468 return EmitLValue(E->getSubExpr());
469
470 assert(E->getOpcode() == UnaryOperator::Deref &&
471 "'*' is the only unary operator that produces an lvalue");
472 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
473}
474
475LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
476 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
477 const char *StrData = E->getStrData();
478 unsigned Len = E->getByteLength();
479
480 // FIXME: Can cache/reuse these within the module.
481 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
482
483 // Create a global variable for this.
484 C = new llvm::GlobalVariable(C->getType(), true,
485 llvm::GlobalValue::InternalLinkage,
486 C, ".str", CurFn->getParent());
487 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
488 llvm::Constant *Zeros[] = { Zero, Zero };
489 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
490 return LValue::MakeAddr(C);
491}
492
493LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
494 std::string FunctionName(CurFuncDecl->getName());
495 std::string GlobalVarName;
496
497 switch (E->getIdentType()) {
498 default:
499 assert(0 && "unknown pre-defined ident type");
500 case PreDefinedExpr::Func:
501 GlobalVarName = "__func__.";
502 break;
503 case PreDefinedExpr::Function:
504 GlobalVarName = "__FUNCTION__.";
505 break;
506 case PreDefinedExpr::PrettyFunction:
507 // FIXME:: Demangle C++ method names
508 GlobalVarName = "__PRETTY_FUNCTION__.";
509 break;
510 }
511
512 GlobalVarName += CurFuncDecl->getName();
513
514 // FIXME: Can cache/reuse these within the module.
515 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
516
517 // Create a global variable for this.
518 C = new llvm::GlobalVariable(C->getType(), true,
519 llvm::GlobalValue::InternalLinkage,
520 C, GlobalVarName, CurFn->getParent());
521 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
522 llvm::Constant *Zeros[] = { Zero, Zero };
523 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
524 return LValue::MakeAddr(C);
525}
526
527LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
528 // The index must always be a pointer or integer, neither of which is an
529 // aggregate. Emit it.
530 QualType IdxTy;
531 llvm::Value *Idx =
532 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
533
534 // If the base is a vector type, then we are forming a vector element lvalue
535 // with this subscript.
536 if (E->getBase()->getType()->isVectorType()) {
537 // Emit the vector as an lvalue to get its address.
538 LValue Base = EmitLValue(E->getBase());
539 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
540 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
541 return LValue::MakeVectorElt(Base.getAddress(), Idx);
542 }
543
544 // At this point, the base must be a pointer or integer, neither of which are
545 // aggregates. Emit it.
546 QualType BaseTy;
547 llvm::Value *Base =
548 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
549
550 // Usually the base is the pointer type, but sometimes it is the index.
551 // Canonicalize to have the pointer as the base.
552 if (isa<llvm::PointerType>(Idx->getType())) {
553 std::swap(Base, Idx);
554 std::swap(BaseTy, IdxTy);
555 }
556
557 // The pointer is now the base. Extend or truncate the index type to 32 or
558 // 64-bits.
559 bool IdxSigned = IdxTy->isSignedIntegerType();
560 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
561 if (IdxBitwidth != LLVMPointerWidth)
562 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
563 IdxSigned, "idxprom");
564
565 // We know that the pointer points to a type of the correct size, unless the
566 // size is a VLA.
567 if (!E->getType()->isConstantSizeType(getContext()))
568 assert(0 && "VLA idx not implemented");
569 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
570}
571
Chris Lattner65520192007-08-02 23:37:31 +0000572LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000573EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000574 // Emit the base vector as an l-value.
575 LValue Base = EmitLValue(E->getBase());
576 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
577
Chris Lattnera0d03a72007-08-03 17:31:20 +0000578 return LValue::MakeOCUVectorElt(Base.getAddress(),
579 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000580}
581
Chris Lattner4b009652007-07-25 00:24:17 +0000582//===--------------------------------------------------------------------===//
583// Expression Emission
584//===--------------------------------------------------------------------===//
585
586RValue CodeGenFunction::EmitExpr(const Expr *E) {
587 assert(E && "Null expression?");
588
589 switch (E->getStmtClass()) {
590 default:
591 fprintf(stderr, "Unimplemented expr!\n");
592 E->dump();
593 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
594
595 // l-values.
596 case Expr::DeclRefExprClass:
597 // DeclRef's of EnumConstantDecl's are simple rvalues.
598 if (const EnumConstantDecl *EC =
599 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
600 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
601 return EmitLoadOfLValue(E);
602 case Expr::ArraySubscriptExprClass:
603 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000604 case Expr::OCUVectorElementExprClass:
Chris Lattnera735fac2007-08-03 00:16:29 +0000605 return EmitLoadOfLValue(E);
Chris Lattner4b009652007-07-25 00:24:17 +0000606 case Expr::PreDefinedExprClass:
607 case Expr::StringLiteralClass:
608 return RValue::get(EmitLValue(E).getAddress());
609
610 // Leaf expressions.
611 case Expr::IntegerLiteralClass:
612 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
613 case Expr::FloatingLiteralClass:
614 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
615 case Expr::CharacterLiteralClass:
616 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner4ca7e752007-08-03 17:51:03 +0000617 case Expr::TypesCompatibleExprClass:
618 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000619
620 // Operators.
621 case Expr::ParenExprClass:
622 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
623 case Expr::UnaryOperatorClass:
624 return EmitUnaryOperator(cast<UnaryOperator>(E));
625 case Expr::SizeOfAlignOfTypeExprClass:
626 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
627 E->getType(),
628 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
629 case Expr::ImplicitCastExprClass:
630 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
631 case Expr::CastExprClass:
632 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
633 case Expr::CallExprClass:
634 return EmitCallExpr(cast<CallExpr>(E));
635 case Expr::BinaryOperatorClass:
636 return EmitBinaryOperator(cast<BinaryOperator>(E));
637
638 case Expr::ConditionalOperatorClass:
639 return EmitConditionalOperator(cast<ConditionalOperator>(E));
640 }
641
642}
643
644RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
645 return RValue::get(llvm::ConstantInt::get(E->getValue()));
646}
647RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
648 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
649 E->getValue()));
650}
651RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
652 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
653 E->getValue()));
654}
655
Chris Lattner4ca7e752007-08-03 17:51:03 +0000656RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
657 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
658 E->typesAreCompatible()));
659}
660
661
Chris Lattner4b009652007-07-25 00:24:17 +0000662RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
663 // Emit subscript expressions in rvalue context's. For most cases, this just
664 // loads the lvalue formed by the subscript expr. However, we have to be
665 // careful, because the base of a vector subscript is occasionally an rvalue,
666 // so we can't get it as an lvalue.
667 if (!E->getBase()->getType()->isVectorType())
668 return EmitLoadOfLValue(E);
669
670 // Handle the vector case. The base must be a vector, the index must be an
671 // integer value.
672 QualType BaseTy, IdxTy;
673 llvm::Value *Base =
674 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
675 llvm::Value *Idx =
676 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
677
678 // FIXME: Convert Idx to i32 type.
679
680 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
681}
682
683// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
684// have to handle a more broad range of conversions than explicit casts, as they
685// handle things like function to ptr-to-function decay etc.
686RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
687 QualType SrcTy;
688 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
689
690 // If the destination is void, just evaluate the source.
691 if (DestTy->isVoidType())
692 return RValue::getAggregate(0);
693
694 return EmitConversion(Src, SrcTy, DestTy);
695}
696
697RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
698 QualType CalleeTy;
699 llvm::Value *Callee =
700 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
701
702 // The callee type will always be a pointer to function type, get the function
703 // type.
704 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
705
706 // Get information about the argument types.
707 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
708
709 // Calling unprototyped functions provides no argument info.
710 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
711 ArgTyIt = FTP->arg_type_begin();
712 ArgTyEnd = FTP->arg_type_end();
713 }
714
715 llvm::SmallVector<llvm::Value*, 16> Args;
716
717 // FIXME: Handle struct return.
718 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
719 QualType ArgTy;
720 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
721
722 // If this argument has prototype information, convert it.
723 if (ArgTyIt != ArgTyEnd) {
724 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
725 } else {
726 // Otherwise, if passing through "..." or to a function with no prototype,
727 // perform the "default argument promotions" (C99 6.5.2.2p6), which
728 // includes the usual unary conversions, but also promotes float to
729 // double.
730 if (const BuiltinType *BT =
731 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
732 if (BT->getKind() == BuiltinType::Float)
733 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
734 llvm::Type::DoubleTy,"tmp"));
735 }
736 }
737
738
739 if (ArgVal.isScalar())
740 Args.push_back(ArgVal.getVal());
741 else // Pass by-address. FIXME: Set attribute bit on call.
742 Args.push_back(ArgVal.getAggregateAddr());
743 }
744
Chris Lattnera9572252007-08-01 06:24:52 +0000745 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000746 if (V->getType() != llvm::Type::VoidTy)
747 V->setName("call");
748
749 // FIXME: Struct return;
750 return RValue::get(V);
751}
752
753
754//===----------------------------------------------------------------------===//
755// Unary Operator Emission
756//===----------------------------------------------------------------------===//
757
758RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
759 QualType &ResTy) {
760 ResTy = E->getType().getCanonicalType();
761
762 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
763 // Functions are promoted to their address.
764 ResTy = getContext().getPointerType(ResTy);
765 return RValue::get(EmitLValue(E).getAddress());
766 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
767 // C99 6.3.2.1p3
768 ResTy = getContext().getPointerType(ary->getElementType());
769
770 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
771 // will not true when we add support for VLAs.
772 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
773
774 assert(isa<llvm::PointerType>(V->getType()) &&
775 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
776 ->getElementType()) &&
777 "Doesn't support VLAs yet!");
778 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
779 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
780 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
781 // FIXME: this probably isn't right, pending clarification from Steve.
782 llvm::Value *Val = EmitExpr(E).getVal();
783
784 // If the input is a signed integer, sign extend to the destination.
785 if (ResTy->isSignedIntegerType()) {
786 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
787 } else {
788 // This handles unsigned types, including bool.
789 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
790 }
791 ResTy = getContext().IntTy;
792
793 return RValue::get(Val);
794 }
795
796 // Otherwise, this is a float, double, int, struct, etc.
797 return EmitExpr(E);
798}
799
800
801RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
802 switch (E->getOpcode()) {
803 default:
804 printf("Unimplemented unary expr!\n");
805 E->dump();
806 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
807 case UnaryOperator::PostInc:
808 case UnaryOperator::PostDec:
809 case UnaryOperator::PreInc :
810 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
811 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
812 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
813 case UnaryOperator::Plus : return EmitUnaryPlus(E);
814 case UnaryOperator::Minus : return EmitUnaryMinus(E);
815 case UnaryOperator::Not : return EmitUnaryNot(E);
816 case UnaryOperator::LNot : return EmitUnaryLNot(E);
817 case UnaryOperator::SizeOf :
818 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
819 case UnaryOperator::AlignOf :
820 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
821 // FIXME: real/imag
822 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
823 }
824}
825
826RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
827 LValue LV = EmitLValue(E->getSubExpr());
828 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
829
830 // We know the operand is real or pointer type, so it must be an LLVM scalar.
831 assert(InVal.isScalar() && "Unknown thing to increment");
832 llvm::Value *InV = InVal.getVal();
833
834 int AmountVal = 1;
835 if (E->getOpcode() == UnaryOperator::PreDec ||
836 E->getOpcode() == UnaryOperator::PostDec)
837 AmountVal = -1;
838
839 llvm::Value *NextVal;
840 if (isa<llvm::IntegerType>(InV->getType())) {
841 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
842 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
843 } else if (InV->getType()->isFloatingPoint()) {
844 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
845 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
846 } else {
847 // FIXME: This is not right for pointers to VLA types.
848 assert(isa<llvm::PointerType>(InV->getType()));
849 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
850 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
851 }
852
853 RValue NextValToStore = RValue::get(NextVal);
854
855 // Store the updated result through the lvalue.
856 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
857
858 // If this is a postinc, return the value read from memory, otherwise use the
859 // updated value.
860 if (E->getOpcode() == UnaryOperator::PreDec ||
861 E->getOpcode() == UnaryOperator::PreInc)
862 return NextValToStore;
863 else
864 return InVal;
865}
866
867/// C99 6.5.3.2
868RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
869 // The address of the operand is just its lvalue. It cannot be a bitfield.
870 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
871}
872
873RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
874 // Unary plus just performs promotions on its arithmetic operand.
875 QualType Ty;
876 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
877}
878
879RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
880 // Unary minus performs promotions, then negates its arithmetic operand.
881 QualType Ty;
882 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
883
884 if (V.isScalar())
885 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
886
887 assert(0 && "FIXME: This doesn't handle complex operands yet");
888}
889
890RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
891 // Unary not performs promotions, then complements its integer operand.
892 QualType Ty;
893 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
894
895 if (V.isScalar())
896 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
897
898 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
899}
900
901
902/// C99 6.5.3.3
903RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
904 // Compare operand to zero.
905 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
906
907 // Invert value.
908 // TODO: Could dynamically modify easy computations here. For example, if
909 // the operand is an icmp ne, turn into icmp eq.
910 BoolVal = Builder.CreateNot(BoolVal, "lnot");
911
912 // ZExt result to int.
913 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
914}
915
916/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
917/// an integer (RetType).
918RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
919 QualType RetType, bool isSizeOf) {
920 /// FIXME: This doesn't handle VLAs yet!
921 std::pair<uint64_t, unsigned> Info =
922 getContext().getTypeInfo(TypeToSize, SourceLocation());
923
924 uint64_t Val = isSizeOf ? Info.first : Info.second;
925 Val /= 8; // Return size in bytes, not bits.
926
927 assert(RetType->isIntegerType() && "Result type must be an integer!");
928
929 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
930 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
931}
932
933
934//===--------------------------------------------------------------------===//
935// Binary Operator Emission
936//===--------------------------------------------------------------------===//
937
938// FIXME describe.
939QualType CodeGenFunction::
940EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
941 RValue &RHS) {
942 QualType LHSType, RHSType;
943 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
944 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
945
946 // If both operands have the same source type, we're done already.
947 if (LHSType == RHSType) return LHSType;
948
949 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
950 // The caller can deal with this (e.g. pointer + int).
951 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
952 return LHSType;
953
954 // At this point, we have two different arithmetic types.
955
956 // Handle complex types first (C99 6.3.1.8p1).
957 if (LHSType->isComplexType() || RHSType->isComplexType()) {
958 assert(0 && "FIXME: complex types unimp");
959#if 0
960 // if we have an integer operand, the result is the complex type.
961 if (rhs->isIntegerType())
962 return lhs;
963 if (lhs->isIntegerType())
964 return rhs;
965 return Context.maxComplexType(lhs, rhs);
966#endif
967 }
968
969 // If neither operand is complex, they must be scalars.
970 llvm::Value *LHSV = LHS.getVal();
971 llvm::Value *RHSV = RHS.getVal();
972
973 // If the LLVM types are already equal, then they only differed in sign, or it
974 // was something like char/signed char or double/long double.
975 if (LHSV->getType() == RHSV->getType())
976 return LHSType;
977
978 // Now handle "real" floating types (i.e. float, double, long double).
979 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
980 // if we have an integer operand, the result is the real floating type, and
981 // the integer converts to FP.
982 if (RHSType->isIntegerType()) {
983 // Promote the RHS to an FP type of the LHS, with the sign following the
984 // RHS.
985 if (RHSType->isSignedIntegerType())
986 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
987 else
988 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
989 return LHSType;
990 }
991
992 if (LHSType->isIntegerType()) {
993 // Promote the LHS to an FP type of the RHS, with the sign following the
994 // LHS.
995 if (LHSType->isSignedIntegerType())
996 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
997 else
998 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
999 return RHSType;
1000 }
1001
1002 // Otherwise, they are two FP types. Promote the smaller operand to the
1003 // bigger result.
1004 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
1005
1006 if (BiggerType == LHSType)
1007 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
1008 else
1009 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
1010 return BiggerType;
1011 }
1012
1013 // Finally, we have two integer types that are different according to C. Do
1014 // a sign or zero extension if needed.
1015
1016 // Otherwise, one type is smaller than the other.
1017 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
1018
1019 if (LHSType == ResTy) {
1020 if (RHSType->isSignedIntegerType())
1021 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
1022 else
1023 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
1024 } else {
1025 assert(RHSType == ResTy && "Unknown conversion");
1026 if (LHSType->isSignedIntegerType())
1027 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
1028 else
1029 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
1030 }
1031 return ResTy;
1032}
1033
1034/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
1035/// are strange in that the result of the operation is not the same type as the
1036/// intermediate computation. This function emits the LHS and RHS operands of
1037/// the compound assignment, promoting them to their common computation type.
1038///
1039/// Since the LHS is an lvalue, and the result is stored back through it, we
1040/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
1041/// RHS values are both in the computation type for the operator.
1042void CodeGenFunction::
1043EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
1044 LValue &LHSLV, RValue &LHS, RValue &RHS) {
1045 LHSLV = EmitLValue(E->getLHS());
1046
1047 // Load the LHS and RHS operands.
1048 QualType LHSTy = E->getLHS()->getType();
1049 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1050 QualType RHSTy;
1051 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1052
1053 // Shift operands do the usual unary conversions, but do not do the binary
1054 // conversions.
1055 if (E->isShiftAssignOp()) {
1056 // FIXME: This is broken. Implicit conversions should be made explicit,
1057 // so that this goes away. This causes us to reload the LHS.
1058 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
1059 }
1060
1061 // Convert the LHS and RHS to the common evaluation type.
1062 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
1063 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
1064}
1065
1066/// EmitCompoundAssignmentResult - Given a result value in the computation type,
1067/// truncate it down to the actual result type, store it through the LHS lvalue,
1068/// and return it.
1069RValue CodeGenFunction::
1070EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
1071 LValue LHSLV, RValue ResV) {
1072
1073 // Truncate back to the destination type.
1074 if (E->getComputationType() != E->getType())
1075 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
1076
1077 // Store the result value into the LHS.
1078 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
1079
1080 // Return the result.
1081 return ResV;
1082}
1083
1084
1085RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
1086 RValue LHS, RHS;
1087 switch (E->getOpcode()) {
1088 default:
1089 fprintf(stderr, "Unimplemented binary expr!\n");
1090 E->dump();
1091 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
1092 case BinaryOperator::Mul:
1093 EmitUsualArithmeticConversions(E, LHS, RHS);
1094 return EmitMul(LHS, RHS, E->getType());
1095 case BinaryOperator::Div:
1096 EmitUsualArithmeticConversions(E, LHS, RHS);
1097 return EmitDiv(LHS, RHS, E->getType());
1098 case BinaryOperator::Rem:
1099 EmitUsualArithmeticConversions(E, LHS, RHS);
1100 return EmitRem(LHS, RHS, E->getType());
1101 case BinaryOperator::Add: {
1102 QualType ExprTy = E->getType();
1103 if (ExprTy->isPointerType()) {
1104 Expr *LHSExpr = E->getLHS();
1105 QualType LHSTy;
1106 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1107 Expr *RHSExpr = E->getRHS();
1108 QualType RHSTy;
1109 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1110 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
1111 } else {
1112 EmitUsualArithmeticConversions(E, LHS, RHS);
1113 return EmitAdd(LHS, RHS, ExprTy);
1114 }
1115 }
1116 case BinaryOperator::Sub: {
1117 QualType ExprTy = E->getType();
1118 Expr *LHSExpr = E->getLHS();
1119 if (LHSExpr->getType()->isPointerType()) {
1120 QualType LHSTy;
1121 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1122 Expr *RHSExpr = E->getRHS();
1123 QualType RHSTy;
1124 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1125 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
1126 } else {
1127 EmitUsualArithmeticConversions(E, LHS, RHS);
1128 return EmitSub(LHS, RHS, ExprTy);
1129 }
1130 }
1131 case BinaryOperator::Shl:
1132 EmitShiftOperands(E, LHS, RHS);
1133 return EmitShl(LHS, RHS, E->getType());
1134 case BinaryOperator::Shr:
1135 EmitShiftOperands(E, LHS, RHS);
1136 return EmitShr(LHS, RHS, E->getType());
1137 case BinaryOperator::And:
1138 EmitUsualArithmeticConversions(E, LHS, RHS);
1139 return EmitAnd(LHS, RHS, E->getType());
1140 case BinaryOperator::Xor:
1141 EmitUsualArithmeticConversions(E, LHS, RHS);
1142 return EmitXor(LHS, RHS, E->getType());
1143 case BinaryOperator::Or :
1144 EmitUsualArithmeticConversions(E, LHS, RHS);
1145 return EmitOr(LHS, RHS, E->getType());
1146 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1147 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1148 case BinaryOperator::LT:
1149 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1150 llvm::ICmpInst::ICMP_SLT,
1151 llvm::FCmpInst::FCMP_OLT);
1152 case BinaryOperator::GT:
1153 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1154 llvm::ICmpInst::ICMP_SGT,
1155 llvm::FCmpInst::FCMP_OGT);
1156 case BinaryOperator::LE:
1157 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1158 llvm::ICmpInst::ICMP_SLE,
1159 llvm::FCmpInst::FCMP_OLE);
1160 case BinaryOperator::GE:
1161 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1162 llvm::ICmpInst::ICMP_SGE,
1163 llvm::FCmpInst::FCMP_OGE);
1164 case BinaryOperator::EQ:
1165 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1166 llvm::ICmpInst::ICMP_EQ,
1167 llvm::FCmpInst::FCMP_OEQ);
1168 case BinaryOperator::NE:
1169 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1170 llvm::ICmpInst::ICMP_NE,
1171 llvm::FCmpInst::FCMP_UNE);
1172 case BinaryOperator::Assign:
1173 return EmitBinaryAssign(E);
1174
1175 case BinaryOperator::MulAssign: {
1176 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1177 LValue LHSLV;
1178 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1179 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1180 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1181 }
1182 case BinaryOperator::DivAssign: {
1183 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1184 LValue LHSLV;
1185 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1186 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1187 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1188 }
1189 case BinaryOperator::RemAssign: {
1190 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1191 LValue LHSLV;
1192 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1193 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1194 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1195 }
1196 case BinaryOperator::AddAssign: {
1197 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1198 LValue LHSLV;
1199 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1200 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1201 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1202 }
1203 case BinaryOperator::SubAssign: {
1204 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1205 LValue LHSLV;
1206 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1207 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1208 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1209 }
1210 case BinaryOperator::ShlAssign: {
1211 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1212 LValue LHSLV;
1213 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1214 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1215 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1216 }
1217 case BinaryOperator::ShrAssign: {
1218 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1219 LValue LHSLV;
1220 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1221 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1222 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1223 }
1224 case BinaryOperator::AndAssign: {
1225 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1226 LValue LHSLV;
1227 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1228 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1229 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1230 }
1231 case BinaryOperator::OrAssign: {
1232 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1233 LValue LHSLV;
1234 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1235 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1236 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1237 }
1238 case BinaryOperator::XorAssign: {
1239 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1240 LValue LHSLV;
1241 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1242 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1243 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1244 }
1245 case BinaryOperator::Comma: return EmitBinaryComma(E);
1246 }
1247}
1248
1249RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1250 if (LHS.isScalar())
1251 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1252
1253 // Otherwise, this must be a complex number.
1254 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1255
1256 EmitLoadOfComplex(LHS, LHSR, LHSI);
1257 EmitLoadOfComplex(RHS, RHSR, RHSI);
1258
1259 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1260 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1261 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1262
1263 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1264 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1265 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1266
1267 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1268 EmitStoreOfComplex(ResR, ResI, Res);
1269 return RValue::getAggregate(Res);
1270}
1271
1272RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1273 if (LHS.isScalar()) {
1274 llvm::Value *RV;
1275 if (LHS.getVal()->getType()->isFloatingPoint())
1276 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1277 else if (ResTy->isUnsignedIntegerType())
1278 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1279 else
1280 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1281 return RValue::get(RV);
1282 }
1283 assert(0 && "FIXME: This doesn't handle complex operands yet");
1284}
1285
1286RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1287 if (LHS.isScalar()) {
1288 llvm::Value *RV;
1289 // Rem in C can't be a floating point type: C99 6.5.5p2.
1290 if (ResTy->isUnsignedIntegerType())
1291 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1292 else
1293 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1294 return RValue::get(RV);
1295 }
1296
1297 assert(0 && "FIXME: This doesn't handle complex operands yet");
1298}
1299
1300RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1301 if (LHS.isScalar())
1302 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1303
1304 // Otherwise, this must be a complex number.
1305 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1306
1307 EmitLoadOfComplex(LHS, LHSR, LHSI);
1308 EmitLoadOfComplex(RHS, RHSR, RHSI);
1309
1310 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1311 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1312
1313 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1314 EmitStoreOfComplex(ResR, ResI, Res);
1315 return RValue::getAggregate(Res);
1316}
1317
1318RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1319 RValue RHS, QualType RHSTy,
1320 QualType ResTy) {
1321 llvm::Value *LHSValue = LHS.getVal();
1322 llvm::Value *RHSValue = RHS.getVal();
1323 if (LHSTy->isPointerType()) {
1324 // pointer + int
1325 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1326 } else {
1327 // int + pointer
1328 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1329 }
1330}
1331
1332RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1333 if (LHS.isScalar())
1334 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1335
1336 assert(0 && "FIXME: This doesn't handle complex operands yet");
1337}
1338
1339RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1340 RValue RHS, QualType RHSTy,
1341 QualType ResTy) {
1342 llvm::Value *LHSValue = LHS.getVal();
1343 llvm::Value *RHSValue = RHS.getVal();
1344 if (const PointerType *RHSPtrType =
1345 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1346 // pointer - pointer
1347 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1348 QualType LHSElementType = LHSPtrType->getPointeeType();
1349 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1350 "can't subtract pointers with differing element types");
1351 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1352 SourceLocation()) / 8;
1353 const llvm::Type *ResultType = ConvertType(ResTy);
1354 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1355 "sub.ptr.lhs.cast");
1356 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1357 "sub.ptr.rhs.cast");
1358 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1359 "sub.ptr.sub");
1360
1361 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1362 // remainder. As such, we handle common power-of-two cases here to generate
1363 // better code.
1364 if (llvm::isPowerOf2_64(ElementSize)) {
1365 llvm::Value *ShAmt =
1366 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1367 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1368 } else {
1369 // Otherwise, do a full sdiv.
1370 llvm::Value *BytesPerElement =
1371 llvm::ConstantInt::get(ResultType, ElementSize);
1372 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1373 "sub.ptr.div"));
1374 }
1375 } else {
1376 // pointer - int
1377 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1378 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1379 }
1380}
1381
1382void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1383 RValue &LHS, RValue &RHS) {
1384 // For shifts, integer promotions are performed, but the usual arithmetic
1385 // conversions are not. The LHS and RHS need not have the same type.
1386 QualType ResTy;
1387 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1388 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1389}
1390
1391
1392RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1393 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1394
1395 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1396 // RHS to the same size as the LHS.
1397 if (LHS->getType() != RHS->getType())
1398 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1399
1400 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1401}
1402
1403RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1404 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1405
1406 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1407 // RHS to the same size as the LHS.
1408 if (LHS->getType() != RHS->getType())
1409 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1410
1411 if (ResTy->isUnsignedIntegerType())
1412 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1413 else
1414 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1415}
1416
1417RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1418 unsigned UICmpOpc, unsigned SICmpOpc,
1419 unsigned FCmpOpc) {
1420 RValue LHS, RHS;
1421 EmitUsualArithmeticConversions(E, LHS, RHS);
1422
1423 llvm::Value *Result;
1424 if (LHS.isScalar()) {
1425 if (LHS.getVal()->getType()->isFloatingPoint()) {
1426 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1427 LHS.getVal(), RHS.getVal(), "cmp");
1428 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1429 // FIXME: This check isn't right for "unsigned short < int" where ushort
1430 // promotes to int and does a signed compare.
1431 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1432 LHS.getVal(), RHS.getVal(), "cmp");
1433 } else {
1434 // Signed integers and pointers.
1435 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1436 LHS.getVal(), RHS.getVal(), "cmp");
1437 }
1438 } else {
1439 // Struct/union/complex
1440 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1441 EmitLoadOfComplex(LHS, LHSR, LHSI);
1442 EmitLoadOfComplex(RHS, RHSR, RHSI);
1443
1444 // FIXME: need to consider _Complex over integers too!
1445
1446 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1447 LHSR, RHSR, "cmp.r");
1448 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1449 LHSI, RHSI, "cmp.i");
1450 if (BinaryOperator::EQ == E->getOpcode()) {
1451 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1452 } else if (BinaryOperator::NE == E->getOpcode()) {
1453 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1454 } else {
1455 assert(0 && "Complex comparison other than == or != ?");
1456 }
1457 }
1458
1459 // ZExt result to int.
1460 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1461}
1462
1463RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1464 if (LHS.isScalar())
1465 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1466
1467 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1468}
1469
1470RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1471 if (LHS.isScalar())
1472 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1473
1474 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1475}
1476
1477RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1478 if (LHS.isScalar())
1479 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1480
1481 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1482}
1483
1484RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1485 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1486
1487 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1488 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1489
1490 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1491 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1492
1493 EmitBlock(RHSBlock);
1494 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1495
1496 // Reaquire the RHS block, as there may be subblocks inserted.
1497 RHSBlock = Builder.GetInsertBlock();
1498 EmitBlock(ContBlock);
1499
1500 // Create a PHI node. If we just evaluted the LHS condition, the result is
1501 // false. If we evaluated both, the result is the RHS condition.
1502 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1503 PN->reserveOperandSpace(2);
1504 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1505 PN->addIncoming(RHSCond, RHSBlock);
1506
1507 // ZExt result to int.
1508 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1509}
1510
1511RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1512 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1513
1514 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1515 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1516
1517 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1518 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1519
1520 EmitBlock(RHSBlock);
1521 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1522
1523 // Reaquire the RHS block, as there may be subblocks inserted.
1524 RHSBlock = Builder.GetInsertBlock();
1525 EmitBlock(ContBlock);
1526
1527 // Create a PHI node. If we just evaluted the LHS condition, the result is
1528 // true. If we evaluated both, the result is the RHS condition.
1529 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1530 PN->reserveOperandSpace(2);
1531 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1532 PN->addIncoming(RHSCond, RHSBlock);
1533
1534 // ZExt result to int.
1535 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1536}
1537
1538RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1539 LValue LHS = EmitLValue(E->getLHS());
1540
1541 QualType RHSTy;
1542 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1543
1544 // Convert the RHS to the type of the LHS.
1545 RHS = EmitConversion(RHS, RHSTy, E->getType());
1546
1547 // Store the value into the LHS.
1548 EmitStoreThroughLValue(RHS, LHS, E->getType());
1549
1550 // Return the converted RHS.
1551 return RHS;
1552}
1553
1554
1555RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1556 EmitExpr(E->getLHS());
1557 return EmitExpr(E->getRHS());
1558}
1559
1560RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1561 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1562 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1563 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1564
1565 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1566 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1567
1568 // FIXME: Implement this for aggregate values.
1569
1570 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1571 // that's not possible with the current design.
1572
1573 EmitBlock(LHSBlock);
1574 QualType LHSTy;
1575 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1576 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1577 Cond;
1578 Builder.CreateBr(ContBlock);
1579 LHSBlock = Builder.GetInsertBlock();
1580
1581 EmitBlock(RHSBlock);
1582 QualType RHSTy;
1583 llvm::Value *RHSValue =
1584 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1585 Builder.CreateBr(ContBlock);
1586 RHSBlock = Builder.GetInsertBlock();
1587
1588 const llvm::Type *LHSType = LHSValue->getType();
1589 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1590
1591 EmitBlock(ContBlock);
1592 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1593 PN->reserveOperandSpace(2);
1594 PN->addIncoming(LHSValue, LHSBlock);
1595 PN->addIncoming(RHSValue, RHSBlock);
1596
1597 return RValue::get(PN);
1598}