blob: 534376edf1e14748c00ede2892dd8c0959005256 [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));
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000640 case Expr::ChooseExprClass:
641 return EmitChooseExpr(cast<ChooseExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000642 }
643
644}
645
646RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
647 return RValue::get(llvm::ConstantInt::get(E->getValue()));
648}
649RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
650 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
651 E->getValue()));
652}
653RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
654 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
655 E->getValue()));
656}
657
Chris Lattner4ca7e752007-08-03 17:51:03 +0000658RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
659 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
660 E->typesAreCompatible()));
661}
662
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000663/// EmitChooseExpr - Implement __builtin_choose_expr.
664RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
665 llvm::APSInt CondVal(32);
666 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
667 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
668
669 // Emit the LHS or RHS as appropriate.
670 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
671}
672
Chris Lattner4ca7e752007-08-03 17:51:03 +0000673
Chris Lattner4b009652007-07-25 00:24:17 +0000674RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
675 // Emit subscript expressions in rvalue context's. For most cases, this just
676 // loads the lvalue formed by the subscript expr. However, we have to be
677 // careful, because the base of a vector subscript is occasionally an rvalue,
678 // so we can't get it as an lvalue.
679 if (!E->getBase()->getType()->isVectorType())
680 return EmitLoadOfLValue(E);
681
682 // Handle the vector case. The base must be a vector, the index must be an
683 // integer value.
684 QualType BaseTy, IdxTy;
685 llvm::Value *Base =
686 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
687 llvm::Value *Idx =
688 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
689
690 // FIXME: Convert Idx to i32 type.
691
692 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
693}
694
695// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
696// have to handle a more broad range of conversions than explicit casts, as they
697// handle things like function to ptr-to-function decay etc.
698RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
699 QualType SrcTy;
700 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
701
702 // If the destination is void, just evaluate the source.
703 if (DestTy->isVoidType())
704 return RValue::getAggregate(0);
705
706 return EmitConversion(Src, SrcTy, DestTy);
707}
708
709RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
710 QualType CalleeTy;
711 llvm::Value *Callee =
712 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
713
714 // The callee type will always be a pointer to function type, get the function
715 // type.
716 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
717
718 // Get information about the argument types.
719 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
720
721 // Calling unprototyped functions provides no argument info.
722 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
723 ArgTyIt = FTP->arg_type_begin();
724 ArgTyEnd = FTP->arg_type_end();
725 }
726
727 llvm::SmallVector<llvm::Value*, 16> Args;
728
729 // FIXME: Handle struct return.
730 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
731 QualType ArgTy;
732 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
733
734 // If this argument has prototype information, convert it.
735 if (ArgTyIt != ArgTyEnd) {
736 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
737 } else {
738 // Otherwise, if passing through "..." or to a function with no prototype,
739 // perform the "default argument promotions" (C99 6.5.2.2p6), which
740 // includes the usual unary conversions, but also promotes float to
741 // double.
742 if (const BuiltinType *BT =
743 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
744 if (BT->getKind() == BuiltinType::Float)
745 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
746 llvm::Type::DoubleTy,"tmp"));
747 }
748 }
749
750
751 if (ArgVal.isScalar())
752 Args.push_back(ArgVal.getVal());
753 else // Pass by-address. FIXME: Set attribute bit on call.
754 Args.push_back(ArgVal.getAggregateAddr());
755 }
756
Chris Lattnera9572252007-08-01 06:24:52 +0000757 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000758 if (V->getType() != llvm::Type::VoidTy)
759 V->setName("call");
760
761 // FIXME: Struct return;
762 return RValue::get(V);
763}
764
765
766//===----------------------------------------------------------------------===//
767// Unary Operator Emission
768//===----------------------------------------------------------------------===//
769
770RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
771 QualType &ResTy) {
772 ResTy = E->getType().getCanonicalType();
773
774 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
775 // Functions are promoted to their address.
776 ResTy = getContext().getPointerType(ResTy);
777 return RValue::get(EmitLValue(E).getAddress());
778 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
779 // C99 6.3.2.1p3
780 ResTy = getContext().getPointerType(ary->getElementType());
781
782 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
783 // will not true when we add support for VLAs.
784 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
785
786 assert(isa<llvm::PointerType>(V->getType()) &&
787 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
788 ->getElementType()) &&
789 "Doesn't support VLAs yet!");
790 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
791 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
792 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
793 // FIXME: this probably isn't right, pending clarification from Steve.
794 llvm::Value *Val = EmitExpr(E).getVal();
795
796 // If the input is a signed integer, sign extend to the destination.
797 if (ResTy->isSignedIntegerType()) {
798 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
799 } else {
800 // This handles unsigned types, including bool.
801 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
802 }
803 ResTy = getContext().IntTy;
804
805 return RValue::get(Val);
806 }
807
808 // Otherwise, this is a float, double, int, struct, etc.
809 return EmitExpr(E);
810}
811
812
813RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
814 switch (E->getOpcode()) {
815 default:
816 printf("Unimplemented unary expr!\n");
817 E->dump();
818 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
819 case UnaryOperator::PostInc:
820 case UnaryOperator::PostDec:
821 case UnaryOperator::PreInc :
822 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
823 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
824 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
825 case UnaryOperator::Plus : return EmitUnaryPlus(E);
826 case UnaryOperator::Minus : return EmitUnaryMinus(E);
827 case UnaryOperator::Not : return EmitUnaryNot(E);
828 case UnaryOperator::LNot : return EmitUnaryLNot(E);
829 case UnaryOperator::SizeOf :
830 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
831 case UnaryOperator::AlignOf :
832 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
833 // FIXME: real/imag
834 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
835 }
836}
837
838RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
839 LValue LV = EmitLValue(E->getSubExpr());
840 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
841
842 // We know the operand is real or pointer type, so it must be an LLVM scalar.
843 assert(InVal.isScalar() && "Unknown thing to increment");
844 llvm::Value *InV = InVal.getVal();
845
846 int AmountVal = 1;
847 if (E->getOpcode() == UnaryOperator::PreDec ||
848 E->getOpcode() == UnaryOperator::PostDec)
849 AmountVal = -1;
850
851 llvm::Value *NextVal;
852 if (isa<llvm::IntegerType>(InV->getType())) {
853 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
854 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
855 } else if (InV->getType()->isFloatingPoint()) {
856 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
857 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
858 } else {
859 // FIXME: This is not right for pointers to VLA types.
860 assert(isa<llvm::PointerType>(InV->getType()));
861 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
862 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
863 }
864
865 RValue NextValToStore = RValue::get(NextVal);
866
867 // Store the updated result through the lvalue.
868 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
869
870 // If this is a postinc, return the value read from memory, otherwise use the
871 // updated value.
872 if (E->getOpcode() == UnaryOperator::PreDec ||
873 E->getOpcode() == UnaryOperator::PreInc)
874 return NextValToStore;
875 else
876 return InVal;
877}
878
879/// C99 6.5.3.2
880RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
881 // The address of the operand is just its lvalue. It cannot be a bitfield.
882 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
883}
884
885RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
886 // Unary plus just performs promotions on its arithmetic operand.
887 QualType Ty;
888 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
889}
890
891RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
892 // Unary minus performs promotions, then negates its arithmetic operand.
893 QualType Ty;
894 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
895
896 if (V.isScalar())
897 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
898
899 assert(0 && "FIXME: This doesn't handle complex operands yet");
900}
901
902RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
903 // Unary not performs promotions, then complements its integer operand.
904 QualType Ty;
905 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
906
907 if (V.isScalar())
908 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
909
910 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
911}
912
913
914/// C99 6.5.3.3
915RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
916 // Compare operand to zero.
917 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
918
919 // Invert value.
920 // TODO: Could dynamically modify easy computations here. For example, if
921 // the operand is an icmp ne, turn into icmp eq.
922 BoolVal = Builder.CreateNot(BoolVal, "lnot");
923
924 // ZExt result to int.
925 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
926}
927
928/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
929/// an integer (RetType).
930RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
931 QualType RetType, bool isSizeOf) {
932 /// FIXME: This doesn't handle VLAs yet!
933 std::pair<uint64_t, unsigned> Info =
934 getContext().getTypeInfo(TypeToSize, SourceLocation());
935
936 uint64_t Val = isSizeOf ? Info.first : Info.second;
937 Val /= 8; // Return size in bytes, not bits.
938
939 assert(RetType->isIntegerType() && "Result type must be an integer!");
940
941 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
942 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
943}
944
945
946//===--------------------------------------------------------------------===//
947// Binary Operator Emission
948//===--------------------------------------------------------------------===//
949
950// FIXME describe.
951QualType CodeGenFunction::
952EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
953 RValue &RHS) {
954 QualType LHSType, RHSType;
955 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
956 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
957
958 // If both operands have the same source type, we're done already.
959 if (LHSType == RHSType) return LHSType;
960
961 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
962 // The caller can deal with this (e.g. pointer + int).
963 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
964 return LHSType;
965
966 // At this point, we have two different arithmetic types.
967
968 // Handle complex types first (C99 6.3.1.8p1).
969 if (LHSType->isComplexType() || RHSType->isComplexType()) {
970 assert(0 && "FIXME: complex types unimp");
971#if 0
972 // if we have an integer operand, the result is the complex type.
973 if (rhs->isIntegerType())
974 return lhs;
975 if (lhs->isIntegerType())
976 return rhs;
977 return Context.maxComplexType(lhs, rhs);
978#endif
979 }
980
981 // If neither operand is complex, they must be scalars.
982 llvm::Value *LHSV = LHS.getVal();
983 llvm::Value *RHSV = RHS.getVal();
984
985 // If the LLVM types are already equal, then they only differed in sign, or it
986 // was something like char/signed char or double/long double.
987 if (LHSV->getType() == RHSV->getType())
988 return LHSType;
989
990 // Now handle "real" floating types (i.e. float, double, long double).
991 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
992 // if we have an integer operand, the result is the real floating type, and
993 // the integer converts to FP.
994 if (RHSType->isIntegerType()) {
995 // Promote the RHS to an FP type of the LHS, with the sign following the
996 // RHS.
997 if (RHSType->isSignedIntegerType())
998 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
999 else
1000 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
1001 return LHSType;
1002 }
1003
1004 if (LHSType->isIntegerType()) {
1005 // Promote the LHS to an FP type of the RHS, with the sign following the
1006 // LHS.
1007 if (LHSType->isSignedIntegerType())
1008 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
1009 else
1010 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
1011 return RHSType;
1012 }
1013
1014 // Otherwise, they are two FP types. Promote the smaller operand to the
1015 // bigger result.
1016 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
1017
1018 if (BiggerType == LHSType)
1019 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
1020 else
1021 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
1022 return BiggerType;
1023 }
1024
1025 // Finally, we have two integer types that are different according to C. Do
1026 // a sign or zero extension if needed.
1027
1028 // Otherwise, one type is smaller than the other.
1029 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
1030
1031 if (LHSType == ResTy) {
1032 if (RHSType->isSignedIntegerType())
1033 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
1034 else
1035 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
1036 } else {
1037 assert(RHSType == ResTy && "Unknown conversion");
1038 if (LHSType->isSignedIntegerType())
1039 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
1040 else
1041 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
1042 }
1043 return ResTy;
1044}
1045
1046/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
1047/// are strange in that the result of the operation is not the same type as the
1048/// intermediate computation. This function emits the LHS and RHS operands of
1049/// the compound assignment, promoting them to their common computation type.
1050///
1051/// Since the LHS is an lvalue, and the result is stored back through it, we
1052/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
1053/// RHS values are both in the computation type for the operator.
1054void CodeGenFunction::
1055EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
1056 LValue &LHSLV, RValue &LHS, RValue &RHS) {
1057 LHSLV = EmitLValue(E->getLHS());
1058
1059 // Load the LHS and RHS operands.
1060 QualType LHSTy = E->getLHS()->getType();
1061 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1062 QualType RHSTy;
1063 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1064
1065 // Shift operands do the usual unary conversions, but do not do the binary
1066 // conversions.
1067 if (E->isShiftAssignOp()) {
1068 // FIXME: This is broken. Implicit conversions should be made explicit,
1069 // so that this goes away. This causes us to reload the LHS.
1070 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
1071 }
1072
1073 // Convert the LHS and RHS to the common evaluation type.
1074 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
1075 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
1076}
1077
1078/// EmitCompoundAssignmentResult - Given a result value in the computation type,
1079/// truncate it down to the actual result type, store it through the LHS lvalue,
1080/// and return it.
1081RValue CodeGenFunction::
1082EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
1083 LValue LHSLV, RValue ResV) {
1084
1085 // Truncate back to the destination type.
1086 if (E->getComputationType() != E->getType())
1087 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
1088
1089 // Store the result value into the LHS.
1090 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
1091
1092 // Return the result.
1093 return ResV;
1094}
1095
1096
1097RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
1098 RValue LHS, RHS;
1099 switch (E->getOpcode()) {
1100 default:
1101 fprintf(stderr, "Unimplemented binary expr!\n");
1102 E->dump();
1103 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
1104 case BinaryOperator::Mul:
1105 EmitUsualArithmeticConversions(E, LHS, RHS);
1106 return EmitMul(LHS, RHS, E->getType());
1107 case BinaryOperator::Div:
1108 EmitUsualArithmeticConversions(E, LHS, RHS);
1109 return EmitDiv(LHS, RHS, E->getType());
1110 case BinaryOperator::Rem:
1111 EmitUsualArithmeticConversions(E, LHS, RHS);
1112 return EmitRem(LHS, RHS, E->getType());
1113 case BinaryOperator::Add: {
1114 QualType ExprTy = E->getType();
1115 if (ExprTy->isPointerType()) {
1116 Expr *LHSExpr = E->getLHS();
1117 QualType LHSTy;
1118 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1119 Expr *RHSExpr = E->getRHS();
1120 QualType RHSTy;
1121 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1122 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
1123 } else {
1124 EmitUsualArithmeticConversions(E, LHS, RHS);
1125 return EmitAdd(LHS, RHS, ExprTy);
1126 }
1127 }
1128 case BinaryOperator::Sub: {
1129 QualType ExprTy = E->getType();
1130 Expr *LHSExpr = E->getLHS();
1131 if (LHSExpr->getType()->isPointerType()) {
1132 QualType LHSTy;
1133 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1134 Expr *RHSExpr = E->getRHS();
1135 QualType RHSTy;
1136 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1137 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
1138 } else {
1139 EmitUsualArithmeticConversions(E, LHS, RHS);
1140 return EmitSub(LHS, RHS, ExprTy);
1141 }
1142 }
1143 case BinaryOperator::Shl:
1144 EmitShiftOperands(E, LHS, RHS);
1145 return EmitShl(LHS, RHS, E->getType());
1146 case BinaryOperator::Shr:
1147 EmitShiftOperands(E, LHS, RHS);
1148 return EmitShr(LHS, RHS, E->getType());
1149 case BinaryOperator::And:
1150 EmitUsualArithmeticConversions(E, LHS, RHS);
1151 return EmitAnd(LHS, RHS, E->getType());
1152 case BinaryOperator::Xor:
1153 EmitUsualArithmeticConversions(E, LHS, RHS);
1154 return EmitXor(LHS, RHS, E->getType());
1155 case BinaryOperator::Or :
1156 EmitUsualArithmeticConversions(E, LHS, RHS);
1157 return EmitOr(LHS, RHS, E->getType());
1158 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1159 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1160 case BinaryOperator::LT:
1161 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1162 llvm::ICmpInst::ICMP_SLT,
1163 llvm::FCmpInst::FCMP_OLT);
1164 case BinaryOperator::GT:
1165 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1166 llvm::ICmpInst::ICMP_SGT,
1167 llvm::FCmpInst::FCMP_OGT);
1168 case BinaryOperator::LE:
1169 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1170 llvm::ICmpInst::ICMP_SLE,
1171 llvm::FCmpInst::FCMP_OLE);
1172 case BinaryOperator::GE:
1173 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1174 llvm::ICmpInst::ICMP_SGE,
1175 llvm::FCmpInst::FCMP_OGE);
1176 case BinaryOperator::EQ:
1177 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1178 llvm::ICmpInst::ICMP_EQ,
1179 llvm::FCmpInst::FCMP_OEQ);
1180 case BinaryOperator::NE:
1181 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1182 llvm::ICmpInst::ICMP_NE,
1183 llvm::FCmpInst::FCMP_UNE);
1184 case BinaryOperator::Assign:
1185 return EmitBinaryAssign(E);
1186
1187 case BinaryOperator::MulAssign: {
1188 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1189 LValue LHSLV;
1190 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1191 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1192 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1193 }
1194 case BinaryOperator::DivAssign: {
1195 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1196 LValue LHSLV;
1197 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1198 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1199 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1200 }
1201 case BinaryOperator::RemAssign: {
1202 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1203 LValue LHSLV;
1204 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1205 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1206 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1207 }
1208 case BinaryOperator::AddAssign: {
1209 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1210 LValue LHSLV;
1211 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1212 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1213 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1214 }
1215 case BinaryOperator::SubAssign: {
1216 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1217 LValue LHSLV;
1218 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1219 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1220 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1221 }
1222 case BinaryOperator::ShlAssign: {
1223 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1224 LValue LHSLV;
1225 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1226 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1227 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1228 }
1229 case BinaryOperator::ShrAssign: {
1230 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1231 LValue LHSLV;
1232 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1233 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1234 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1235 }
1236 case BinaryOperator::AndAssign: {
1237 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1238 LValue LHSLV;
1239 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1240 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1241 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1242 }
1243 case BinaryOperator::OrAssign: {
1244 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1245 LValue LHSLV;
1246 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1247 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1248 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1249 }
1250 case BinaryOperator::XorAssign: {
1251 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1252 LValue LHSLV;
1253 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1254 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1255 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1256 }
1257 case BinaryOperator::Comma: return EmitBinaryComma(E);
1258 }
1259}
1260
1261RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1262 if (LHS.isScalar())
1263 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1264
1265 // Otherwise, this must be a complex number.
1266 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1267
1268 EmitLoadOfComplex(LHS, LHSR, LHSI);
1269 EmitLoadOfComplex(RHS, RHSR, RHSI);
1270
1271 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1272 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1273 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1274
1275 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1276 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1277 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1278
1279 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1280 EmitStoreOfComplex(ResR, ResI, Res);
1281 return RValue::getAggregate(Res);
1282}
1283
1284RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1285 if (LHS.isScalar()) {
1286 llvm::Value *RV;
1287 if (LHS.getVal()->getType()->isFloatingPoint())
1288 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1289 else if (ResTy->isUnsignedIntegerType())
1290 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1291 else
1292 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1293 return RValue::get(RV);
1294 }
1295 assert(0 && "FIXME: This doesn't handle complex operands yet");
1296}
1297
1298RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1299 if (LHS.isScalar()) {
1300 llvm::Value *RV;
1301 // Rem in C can't be a floating point type: C99 6.5.5p2.
1302 if (ResTy->isUnsignedIntegerType())
1303 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1304 else
1305 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1306 return RValue::get(RV);
1307 }
1308
1309 assert(0 && "FIXME: This doesn't handle complex operands yet");
1310}
1311
1312RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1313 if (LHS.isScalar())
1314 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1315
1316 // Otherwise, this must be a complex number.
1317 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1318
1319 EmitLoadOfComplex(LHS, LHSR, LHSI);
1320 EmitLoadOfComplex(RHS, RHSR, RHSI);
1321
1322 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1323 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1324
1325 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1326 EmitStoreOfComplex(ResR, ResI, Res);
1327 return RValue::getAggregate(Res);
1328}
1329
1330RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1331 RValue RHS, QualType RHSTy,
1332 QualType ResTy) {
1333 llvm::Value *LHSValue = LHS.getVal();
1334 llvm::Value *RHSValue = RHS.getVal();
1335 if (LHSTy->isPointerType()) {
1336 // pointer + int
1337 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1338 } else {
1339 // int + pointer
1340 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1341 }
1342}
1343
1344RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1345 if (LHS.isScalar())
1346 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1347
1348 assert(0 && "FIXME: This doesn't handle complex operands yet");
1349}
1350
1351RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1352 RValue RHS, QualType RHSTy,
1353 QualType ResTy) {
1354 llvm::Value *LHSValue = LHS.getVal();
1355 llvm::Value *RHSValue = RHS.getVal();
1356 if (const PointerType *RHSPtrType =
1357 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1358 // pointer - pointer
1359 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1360 QualType LHSElementType = LHSPtrType->getPointeeType();
1361 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1362 "can't subtract pointers with differing element types");
1363 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1364 SourceLocation()) / 8;
1365 const llvm::Type *ResultType = ConvertType(ResTy);
1366 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1367 "sub.ptr.lhs.cast");
1368 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1369 "sub.ptr.rhs.cast");
1370 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1371 "sub.ptr.sub");
1372
1373 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1374 // remainder. As such, we handle common power-of-two cases here to generate
1375 // better code.
1376 if (llvm::isPowerOf2_64(ElementSize)) {
1377 llvm::Value *ShAmt =
1378 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1379 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1380 } else {
1381 // Otherwise, do a full sdiv.
1382 llvm::Value *BytesPerElement =
1383 llvm::ConstantInt::get(ResultType, ElementSize);
1384 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1385 "sub.ptr.div"));
1386 }
1387 } else {
1388 // pointer - int
1389 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1390 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1391 }
1392}
1393
1394void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1395 RValue &LHS, RValue &RHS) {
1396 // For shifts, integer promotions are performed, but the usual arithmetic
1397 // conversions are not. The LHS and RHS need not have the same type.
1398 QualType ResTy;
1399 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1400 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1401}
1402
1403
1404RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1405 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1406
1407 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1408 // RHS to the same size as the LHS.
1409 if (LHS->getType() != RHS->getType())
1410 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1411
1412 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1413}
1414
1415RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1416 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1417
1418 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1419 // RHS to the same size as the LHS.
1420 if (LHS->getType() != RHS->getType())
1421 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1422
1423 if (ResTy->isUnsignedIntegerType())
1424 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1425 else
1426 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1427}
1428
1429RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1430 unsigned UICmpOpc, unsigned SICmpOpc,
1431 unsigned FCmpOpc) {
1432 RValue LHS, RHS;
1433 EmitUsualArithmeticConversions(E, LHS, RHS);
1434
1435 llvm::Value *Result;
1436 if (LHS.isScalar()) {
1437 if (LHS.getVal()->getType()->isFloatingPoint()) {
1438 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1439 LHS.getVal(), RHS.getVal(), "cmp");
1440 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1441 // FIXME: This check isn't right for "unsigned short < int" where ushort
1442 // promotes to int and does a signed compare.
1443 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1444 LHS.getVal(), RHS.getVal(), "cmp");
1445 } else {
1446 // Signed integers and pointers.
1447 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1448 LHS.getVal(), RHS.getVal(), "cmp");
1449 }
1450 } else {
1451 // Struct/union/complex
1452 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1453 EmitLoadOfComplex(LHS, LHSR, LHSI);
1454 EmitLoadOfComplex(RHS, RHSR, RHSI);
1455
1456 // FIXME: need to consider _Complex over integers too!
1457
1458 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1459 LHSR, RHSR, "cmp.r");
1460 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1461 LHSI, RHSI, "cmp.i");
1462 if (BinaryOperator::EQ == E->getOpcode()) {
1463 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1464 } else if (BinaryOperator::NE == E->getOpcode()) {
1465 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1466 } else {
1467 assert(0 && "Complex comparison other than == or != ?");
1468 }
1469 }
1470
1471 // ZExt result to int.
1472 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1473}
1474
1475RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1476 if (LHS.isScalar())
1477 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1478
1479 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1480}
1481
1482RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1483 if (LHS.isScalar())
1484 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1485
1486 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1487}
1488
1489RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1490 if (LHS.isScalar())
1491 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1492
1493 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1494}
1495
1496RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1497 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1498
1499 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1500 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1501
1502 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1503 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1504
1505 EmitBlock(RHSBlock);
1506 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1507
1508 // Reaquire the RHS block, as there may be subblocks inserted.
1509 RHSBlock = Builder.GetInsertBlock();
1510 EmitBlock(ContBlock);
1511
1512 // Create a PHI node. If we just evaluted the LHS condition, the result is
1513 // false. If we evaluated both, the result is the RHS condition.
1514 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1515 PN->reserveOperandSpace(2);
1516 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1517 PN->addIncoming(RHSCond, RHSBlock);
1518
1519 // ZExt result to int.
1520 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1521}
1522
1523RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1524 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1525
1526 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1527 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1528
1529 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1530 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1531
1532 EmitBlock(RHSBlock);
1533 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1534
1535 // Reaquire the RHS block, as there may be subblocks inserted.
1536 RHSBlock = Builder.GetInsertBlock();
1537 EmitBlock(ContBlock);
1538
1539 // Create a PHI node. If we just evaluted the LHS condition, the result is
1540 // true. If we evaluated both, the result is the RHS condition.
1541 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1542 PN->reserveOperandSpace(2);
1543 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1544 PN->addIncoming(RHSCond, RHSBlock);
1545
1546 // ZExt result to int.
1547 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1548}
1549
1550RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1551 LValue LHS = EmitLValue(E->getLHS());
1552
1553 QualType RHSTy;
1554 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1555
1556 // Convert the RHS to the type of the LHS.
1557 RHS = EmitConversion(RHS, RHSTy, E->getType());
1558
1559 // Store the value into the LHS.
1560 EmitStoreThroughLValue(RHS, LHS, E->getType());
1561
1562 // Return the converted RHS.
1563 return RHS;
1564}
1565
1566
1567RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1568 EmitExpr(E->getLHS());
1569 return EmitExpr(E->getRHS());
1570}
1571
1572RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1573 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1574 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1575 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1576
1577 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1578 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1579
1580 // FIXME: Implement this for aggregate values.
1581
1582 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1583 // that's not possible with the current design.
1584
1585 EmitBlock(LHSBlock);
1586 QualType LHSTy;
1587 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1588 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1589 Cond;
1590 Builder.CreateBr(ContBlock);
1591 LHSBlock = Builder.GetInsertBlock();
1592
1593 EmitBlock(RHSBlock);
1594 QualType RHSTy;
1595 llvm::Value *RHSValue =
1596 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1597 Builder.CreateBr(ContBlock);
1598 RHSBlock = Builder.GetInsertBlock();
1599
1600 const llvm::Type *LHSType = LHSValue->getType();
1601 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1602
1603 EmitBlock(ContBlock);
1604 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1605 PN->reserveOperandSpace(2);
1606 PN->addIncoming(LHSValue, LHSBlock);
1607 PN->addIncoming(RHSValue, RHSBlock);
1608
1609 return RValue::get(PN);
1610}