blob: 08bd93f22db909852f479647e2de9fe611f44475 [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) {
Chris Lattner2af72ac2007-08-08 17:43:05 +000039 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +000040}
41
42/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
43/// load the real and imaginary pieces, returning them as Real/Imag.
44void CodeGenFunction::EmitLoadOfComplex(RValue V,
45 llvm::Value *&Real, llvm::Value *&Imag){
46 llvm::Value *Ptr = V.getAggregateAddr();
47
48 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
49 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
50 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
51 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
52
53 // FIXME: Handle volatility.
54 Real = Builder.CreateLoad(RealPtr, "real");
55 Imag = Builder.CreateLoad(ImagPtr, "imag");
56}
57
58/// EmitStoreOfComplex - Store the specified real/imag parts into the
59/// specified value pointer.
60void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
61 llvm::Value *ResPtr) {
62 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
63 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
64 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
65 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
66
67 // FIXME: Handle volatility.
68 Builder.CreateStore(Real, RealPtr);
69 Builder.CreateStore(Imag, ImagPtr);
70}
71
72//===--------------------------------------------------------------------===//
73// Conversions
74//===--------------------------------------------------------------------===//
75
76/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
77/// the type specified by DstTy, following the rules of C99 6.3.
78RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
79 QualType DstTy) {
80 ValTy = ValTy.getCanonicalType();
81 DstTy = DstTy.getCanonicalType();
82 if (ValTy == DstTy) return Val;
83
84 // Handle conversions to bool first, they are special: comparisons against 0.
85 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
86 if (DestBT->getKind() == BuiltinType::Bool)
87 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
88
89 // Handle pointer conversions next: pointers can only be converted to/from
90 // other pointers and integers.
91 if (isa<PointerType>(DstTy)) {
92 const llvm::Type *DestTy = ConvertType(DstTy);
93
Chris Lattner2a420172007-08-10 16:33:59 +000094 if (Val.getVal()->getType() == DestTy)
95 return Val;
96
Chris Lattner4b009652007-07-25 00:24:17 +000097 // The source value may be an integer, or a pointer.
98 assert(Val.isScalar() && "Can only convert from integer or pointer");
99 if (isa<llvm::PointerType>(Val.getVal()->getType()))
100 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
101 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
102 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
103 }
104
105 if (isa<PointerType>(ValTy)) {
106 // Must be an ptr to int cast.
107 const llvm::Type *DestTy = ConvertType(DstTy);
108 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
109 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
110 }
111
112 // Finally, we have the arithmetic types: real int/float and complex
113 // int/float. Handle real->real conversions first, they are the most
114 // common.
115 if (Val.isScalar() && DstTy->isRealType()) {
116 // We know that these are representable as scalars in LLVM, convert to LLVM
117 // types since they are easier to reason about.
118 llvm::Value *SrcVal = Val.getVal();
119 const llvm::Type *DestTy = ConvertType(DstTy);
120 if (SrcVal->getType() == DestTy) return Val;
121
122 llvm::Value *Result;
123 if (isa<llvm::IntegerType>(SrcVal->getType())) {
124 bool InputSigned = ValTy->isSignedIntegerType();
125 if (isa<llvm::IntegerType>(DestTy))
126 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
127 else if (InputSigned)
128 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
129 else
130 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
131 } else {
132 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
133 if (isa<llvm::IntegerType>(DestTy)) {
134 if (DstTy->isSignedIntegerType())
135 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
136 else
137 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
138 } else {
139 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
140 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
141 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
142 else
143 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
144 }
145 }
146 return RValue::get(Result);
147 }
148
149 assert(0 && "FIXME: We don't support complex conversions yet!");
150}
151
152
153/// ConvertScalarValueToBool - Convert the specified expression value to a
154/// boolean (i1) truth value. This is equivalent to "Val == 0".
155llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
156 Ty = Ty.getCanonicalType();
157 llvm::Value *Result;
158 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
159 switch (BT->getKind()) {
160 default: assert(0 && "Unknown scalar value");
161 case BuiltinType::Bool:
162 Result = Val.getVal();
163 // Bool is already evaluated right.
164 assert(Result->getType() == llvm::Type::Int1Ty &&
165 "Unexpected bool value type!");
166 return Result;
167 case BuiltinType::Char_S:
168 case BuiltinType::Char_U:
169 case BuiltinType::SChar:
170 case BuiltinType::UChar:
171 case BuiltinType::Short:
172 case BuiltinType::UShort:
173 case BuiltinType::Int:
174 case BuiltinType::UInt:
175 case BuiltinType::Long:
176 case BuiltinType::ULong:
177 case BuiltinType::LongLong:
178 case BuiltinType::ULongLong:
179 // Code below handles simple integers.
180 break;
181 case BuiltinType::Float:
182 case BuiltinType::Double:
183 case BuiltinType::LongDouble: {
184 // Compare against 0.0 for fp scalars.
185 Result = Val.getVal();
186 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
187 // FIXME: llvm-gcc produces a une comparison: validate this is right.
188 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
189 return Result;
190 }
191 }
192 } else if (isa<PointerType>(Ty) ||
193 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
194 // Code below handles this fine.
195 } else {
196 assert(isa<ComplexType>(Ty) && "Unknwon type!");
197 assert(0 && "FIXME: comparisons against complex not implemented yet");
198 }
199
200 // Usual case for integers, pointers, and enums: compare against zero.
201 Result = Val.getVal();
202
203 // Because of the type rules of C, we often end up computing a logical value,
204 // then zero extending it to int, then wanting it as a logical value again.
205 // Optimize this common case.
206 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
207 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
208 Result = ZI->getOperand(0);
209 ZI->eraseFromParent();
210 return Result;
211 }
212 }
213
214 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
215 return Builder.CreateICmpNE(Result, Zero, "tobool");
216}
217
218//===----------------------------------------------------------------------===//
219// LValue Expression Emission
220//===----------------------------------------------------------------------===//
221
222/// EmitLValue - Emit code to compute a designator that specifies the location
223/// of the expression.
224///
225/// This can return one of two things: a simple address or a bitfield
226/// reference. In either case, the LLVM Value* in the LValue structure is
227/// guaranteed to be an LLVM pointer type.
228///
229/// If this returns a bitfield reference, nothing about the pointee type of
230/// the LLVM value is known: For example, it may not be a pointer to an
231/// integer.
232///
233/// If this returns a normal address, and if the lvalue's C type is fixed
234/// size, this method guarantees that the returned pointer type will point to
235/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
236/// variable length type, this is not possible.
237///
238LValue CodeGenFunction::EmitLValue(const Expr *E) {
239 switch (E->getStmtClass()) {
240 default:
241 fprintf(stderr, "Unimplemented lvalue expr!\n");
242 E->dump();
243 return LValue::MakeAddr(llvm::UndefValue::get(
244 llvm::PointerType::get(llvm::Type::Int32Ty)));
245
246 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
247 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
248 case Expr::PreDefinedExprClass:
249 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
250 case Expr::StringLiteralClass:
251 return EmitStringLiteralLValue(cast<StringLiteral>(E));
252
253 case Expr::UnaryOperatorClass:
254 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
255 case Expr::ArraySubscriptExprClass:
256 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000257 case Expr::OCUVectorElementExprClass:
258 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000259 }
260}
261
262/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
263/// this method emits the address of the lvalue, then loads the result as an
264/// rvalue, returning the rvalue.
265RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000266 if (LV.isSimple()) {
267 llvm::Value *Ptr = LV.getAddress();
268 const llvm::Type *EltTy =
269 cast<llvm::PointerType>(Ptr->getType())->getElementType();
270
271 // Simple scalar l-value.
272 if (EltTy->isFirstClassType())
273 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
274
Chris Lattner2a420172007-08-10 16:33:59 +0000275 if (ExprType->isFunctionType())
276 return RValue::get(Ptr);
277
Chris Lattner4b009652007-07-25 00:24:17 +0000278 // Otherwise, we have an aggregate lvalue.
279 return RValue::getAggregate(Ptr);
280 }
281
282 if (LV.isVectorElt()) {
283 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
284 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
285 "vecext"));
286 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000287
288 // If this is a reference to a subset of the elements of a vector, either
289 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000290 if (LV.isOCUVectorElt())
291 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000292
293 assert(0 && "Bitfield ref not impl!");
294}
295
Chris Lattner944f7962007-08-03 16:18:34 +0000296// If this is a reference to a subset of the elements of a vector, either
297// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000298RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner944f7962007-08-03 16:18:34 +0000299 QualType ExprType) {
300 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
301
Chris Lattnera0d03a72007-08-03 17:31:20 +0000302 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000303
304 // If the result of the expression is a non-vector type, we must be
305 // extracting a single element. Just codegen as an extractelement.
306 if (!isa<VectorType>(ExprType)) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000307 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000308 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
309 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
310 }
311
312 // If the source and destination have the same number of elements, use a
313 // vector shuffle instead of insert/extracts.
314 unsigned NumResultElts = cast<VectorType>(ExprType)->getNumElements();
315 unsigned NumSourceElts =
316 cast<llvm::VectorType>(Vec->getType())->getNumElements();
317
318 if (NumResultElts == NumSourceElts) {
319 llvm::SmallVector<llvm::Constant*, 4> Mask;
320 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000321 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000322 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
323 }
324
325 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
326 Vec = Builder.CreateShuffleVector(Vec,
327 llvm::UndefValue::get(Vec->getType()),
328 MaskV, "tmp");
329 return RValue::get(Vec);
330 }
331
332 // Start out with an undef of the result type.
333 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
334
335 // Extract/Insert each element of the result.
336 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000337 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000338 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
339 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
340
341 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
342 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
343 }
344
345 return RValue::get(Result);
346}
347
348
Chris Lattner4b009652007-07-25 00:24:17 +0000349RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
350 return EmitLoadOfLValue(EmitLValue(E), E->getType());
351}
352
353
354/// EmitStoreThroughLValue - Store the specified rvalue into the specified
355/// lvalue, where both are guaranteed to the have the same type, and that type
356/// is 'Ty'.
357void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
358 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000359 if (!Dst.isSimple()) {
360 if (Dst.isVectorElt()) {
361 // Read/modify/write the vector, inserting the new element.
362 // FIXME: Volatility.
363 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
364 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
365 Dst.getVectorIdx(), "vecins");
366 Builder.CreateStore(Vec, Dst.getVectorAddr());
367 return;
368 }
Chris Lattner4b009652007-07-25 00:24:17 +0000369
Chris Lattner5bfdd232007-08-03 16:28:33 +0000370 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000371 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000372 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
373
374 assert(0 && "FIXME: Don't support store to bitfield yet");
375 }
Chris Lattner4b009652007-07-25 00:24:17 +0000376
377 llvm::Value *DstAddr = Dst.getAddress();
378 if (Src.isScalar()) {
379 // FIXME: Handle volatility etc.
380 const llvm::Type *SrcTy = Src.getVal()->getType();
381 const llvm::Type *AddrTy =
382 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
383
384 if (AddrTy != SrcTy)
385 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
386 "storetmp");
387 Builder.CreateStore(Src.getVal(), DstAddr);
388 return;
389 }
390
391 // Don't use memcpy for complex numbers.
392 if (Ty->isComplexType()) {
393 llvm::Value *Real, *Imag;
394 EmitLoadOfComplex(Src, Real, Imag);
395 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
396 return;
397 }
398
399 // Aggregate assignment turns into llvm.memcpy.
400 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
401 llvm::Value *SrcAddr = Src.getAggregateAddr();
402
403 if (DstAddr->getType() != SBP)
404 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
405 if (SrcAddr->getType() != SBP)
406 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
407
408 unsigned Align = 1; // FIXME: Compute type alignments.
409 unsigned Size = 1234; // FIXME: Compute type sizes.
410
411 // FIXME: Handle variable sized types.
412 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
413 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
414
415 llvm::Value *MemCpyOps[4] = {
416 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
417 };
418
Chris Lattnera9572252007-08-01 06:24:52 +0000419 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
Chris Lattner4b009652007-07-25 00:24:17 +0000420}
421
Chris Lattner5bfdd232007-08-03 16:28:33 +0000422void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
423 QualType Ty) {
424 // This access turns into a read/modify/write of the vector. Load the input
425 // value now.
426 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
427 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000428 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000429
430 llvm::Value *SrcVal = Src.getVal();
431
Chris Lattner940966d2007-08-03 16:37:04 +0000432 if (const VectorType *VTy = Ty->getAsVectorType()) {
433 unsigned NumSrcElts = VTy->getNumElements();
434
435 // Extract/Insert each element.
436 for (unsigned i = 0; i != NumSrcElts; ++i) {
437 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
438 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
439
Chris Lattnera0d03a72007-08-03 17:31:20 +0000440 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000441 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
442 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
443 }
444 } else {
445 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000446 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000447 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
448 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000449 }
450
Chris Lattner5bfdd232007-08-03 16:28:33 +0000451 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
452}
453
Chris Lattner4b009652007-07-25 00:24:17 +0000454
455LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
456 const Decl *D = E->getDecl();
457 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
458 llvm::Value *V = LocalDeclMap[D];
459 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
460 return LValue::MakeAddr(V);
461 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
462 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
463 }
464 assert(0 && "Unimp declref");
465}
466
467LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
468 // __extension__ doesn't affect lvalue-ness.
469 if (E->getOpcode() == UnaryOperator::Extension)
470 return EmitLValue(E->getSubExpr());
471
472 assert(E->getOpcode() == UnaryOperator::Deref &&
473 "'*' is the only unary operator that produces an lvalue");
474 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
475}
476
477LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
478 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
479 const char *StrData = E->getStrData();
480 unsigned Len = E->getByteLength();
481
482 // FIXME: Can cache/reuse these within the module.
483 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
484
485 // Create a global variable for this.
486 C = new llvm::GlobalVariable(C->getType(), true,
487 llvm::GlobalValue::InternalLinkage,
488 C, ".str", CurFn->getParent());
489 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
490 llvm::Constant *Zeros[] = { Zero, Zero };
491 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
492 return LValue::MakeAddr(C);
493}
494
495LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
496 std::string FunctionName(CurFuncDecl->getName());
497 std::string GlobalVarName;
498
499 switch (E->getIdentType()) {
500 default:
501 assert(0 && "unknown pre-defined ident type");
502 case PreDefinedExpr::Func:
503 GlobalVarName = "__func__.";
504 break;
505 case PreDefinedExpr::Function:
506 GlobalVarName = "__FUNCTION__.";
507 break;
508 case PreDefinedExpr::PrettyFunction:
509 // FIXME:: Demangle C++ method names
510 GlobalVarName = "__PRETTY_FUNCTION__.";
511 break;
512 }
513
514 GlobalVarName += CurFuncDecl->getName();
515
516 // FIXME: Can cache/reuse these within the module.
517 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
518
519 // Create a global variable for this.
520 C = new llvm::GlobalVariable(C->getType(), true,
521 llvm::GlobalValue::InternalLinkage,
522 C, GlobalVarName, CurFn->getParent());
523 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
524 llvm::Constant *Zeros[] = { Zero, Zero };
525 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
526 return LValue::MakeAddr(C);
527}
528
529LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
530 // The index must always be a pointer or integer, neither of which is an
531 // aggregate. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000532 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000533
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.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000546 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000547
548 // Usually the base is the pointer type, but sometimes it is the index.
549 // Canonicalize to have the pointer as the base.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000550 QualType BaseTy = E->getBase()->getType();
551 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000552 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.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000684 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
685 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000686
687 // FIXME: Convert Idx to i32 type.
688
689 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
690}
691
692// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
693// have to handle a more broad range of conversions than explicit casts, as they
694// handle things like function to ptr-to-function decay etc.
695RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000696 RValue Src = EmitExpr(Op);
Chris Lattner4b009652007-07-25 00:24:17 +0000697
698 // If the destination is void, just evaluate the source.
699 if (DestTy->isVoidType())
700 return RValue::getAggregate(0);
701
Chris Lattner2af72ac2007-08-08 17:43:05 +0000702 return EmitConversion(Src, Op->getType(), DestTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000703}
704
705RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000706 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000707
708 // The callee type will always be a pointer to function type, get the function
709 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000710 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000711 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
712
713 // Get information about the argument types.
714 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
715
716 // Calling unprototyped functions provides no argument info.
717 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
718 ArgTyIt = FTP->arg_type_begin();
719 ArgTyEnd = FTP->arg_type_end();
720 }
721
722 llvm::SmallVector<llvm::Value*, 16> Args;
723
Chris Lattner59802042007-08-10 17:02:28 +0000724 // Handle struct-return functions by passing a pointer to the location that
725 // we would like to return into.
726 if (hasAggregateLLVMType(E->getType())) {
727 // Create a temporary alloca to hold the result of the call. :(
728 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
729 // FIXME: set the stret attribute on the argument.
730 }
731
Chris Lattner4b009652007-07-25 00:24:17 +0000732 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000733 QualType ArgTy = E->getArg(i)->getType();
734 RValue ArgVal = EmitExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000735
736 // If this argument has prototype information, convert it.
737 if (ArgTyIt != ArgTyEnd) {
738 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
739 } else {
740 // Otherwise, if passing through "..." or to a function with no prototype,
741 // perform the "default argument promotions" (C99 6.5.2.2p6), which
742 // includes the usual unary conversions, but also promotes float to
743 // double.
744 if (const BuiltinType *BT =
745 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
746 if (BT->getKind() == BuiltinType::Float)
747 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
748 llvm::Type::DoubleTy,"tmp"));
749 }
750 }
751
752
753 if (ArgVal.isScalar())
754 Args.push_back(ArgVal.getVal());
755 else // Pass by-address. FIXME: Set attribute bit on call.
756 Args.push_back(ArgVal.getAggregateAddr());
757 }
758
Chris Lattnera9572252007-08-01 06:24:52 +0000759 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000760 if (V->getType() != llvm::Type::VoidTy)
761 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000762 else if (hasAggregateLLVMType(E->getType()))
763 // Struct return.
764 return RValue::getAggregate(Args[0]);
765
Chris Lattner4b009652007-07-25 00:24:17 +0000766 return RValue::get(V);
767}
768
769
770//===----------------------------------------------------------------------===//
771// Unary Operator Emission
772//===----------------------------------------------------------------------===//
773
Chris Lattner4b009652007-07-25 00:24:17 +0000774RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
775 switch (E->getOpcode()) {
776 default:
777 printf("Unimplemented unary expr!\n");
778 E->dump();
779 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
780 case UnaryOperator::PostInc:
781 case UnaryOperator::PostDec:
782 case UnaryOperator::PreInc :
783 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
784 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
785 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
786 case UnaryOperator::Plus : return EmitUnaryPlus(E);
787 case UnaryOperator::Minus : return EmitUnaryMinus(E);
788 case UnaryOperator::Not : return EmitUnaryNot(E);
789 case UnaryOperator::LNot : return EmitUnaryLNot(E);
790 case UnaryOperator::SizeOf :
791 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
792 case UnaryOperator::AlignOf :
793 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
794 // FIXME: real/imag
795 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
796 }
797}
798
799RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
800 LValue LV = EmitLValue(E->getSubExpr());
801 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
802
803 // We know the operand is real or pointer type, so it must be an LLVM scalar.
804 assert(InVal.isScalar() && "Unknown thing to increment");
805 llvm::Value *InV = InVal.getVal();
806
807 int AmountVal = 1;
808 if (E->getOpcode() == UnaryOperator::PreDec ||
809 E->getOpcode() == UnaryOperator::PostDec)
810 AmountVal = -1;
811
812 llvm::Value *NextVal;
813 if (isa<llvm::IntegerType>(InV->getType())) {
814 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
815 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
816 } else if (InV->getType()->isFloatingPoint()) {
817 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
818 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
819 } else {
820 // FIXME: This is not right for pointers to VLA types.
821 assert(isa<llvm::PointerType>(InV->getType()));
822 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
823 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
824 }
825
826 RValue NextValToStore = RValue::get(NextVal);
827
828 // Store the updated result through the lvalue.
829 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
830
831 // If this is a postinc, return the value read from memory, otherwise use the
832 // updated value.
833 if (E->getOpcode() == UnaryOperator::PreDec ||
834 E->getOpcode() == UnaryOperator::PreInc)
835 return NextValToStore;
836 else
837 return InVal;
838}
839
840/// C99 6.5.3.2
841RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
842 // The address of the operand is just its lvalue. It cannot be a bitfield.
843 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
844}
845
846RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000847 assert(E->getType().getCanonicalType() ==
848 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
849 // Unary plus just returns its value.
850 return EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000851}
852
853RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000854 assert(E->getType().getCanonicalType() ==
855 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
856
Chris Lattner4b009652007-07-25 00:24:17 +0000857 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000858 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000859
860 if (V.isScalar())
861 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
862
863 assert(0 && "FIXME: This doesn't handle complex operands yet");
864}
865
866RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
867 // Unary not performs promotions, then complements its integer operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000868 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000869
870 if (V.isScalar())
871 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
872
873 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
874}
875
876
877/// C99 6.5.3.3
878RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
879 // Compare operand to zero.
880 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
881
882 // Invert value.
883 // TODO: Could dynamically modify easy computations here. For example, if
884 // the operand is an icmp ne, turn into icmp eq.
885 BoolVal = Builder.CreateNot(BoolVal, "lnot");
886
887 // ZExt result to int.
888 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
889}
890
891/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
892/// an integer (RetType).
893RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
894 QualType RetType, bool isSizeOf) {
895 /// FIXME: This doesn't handle VLAs yet!
896 std::pair<uint64_t, unsigned> Info =
897 getContext().getTypeInfo(TypeToSize, SourceLocation());
898
899 uint64_t Val = isSizeOf ? Info.first : Info.second;
900 Val /= 8; // Return size in bytes, not bits.
901
902 assert(RetType->isIntegerType() && "Result type must be an integer!");
903
904 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
905 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
906}
907
908
909//===--------------------------------------------------------------------===//
910// Binary Operator Emission
911//===--------------------------------------------------------------------===//
912
Chris Lattner4b009652007-07-25 00:24:17 +0000913
914/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
915/// are strange in that the result of the operation is not the same type as the
916/// intermediate computation. This function emits the LHS and RHS operands of
917/// the compound assignment, promoting them to their common computation type.
918///
919/// Since the LHS is an lvalue, and the result is stored back through it, we
920/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
921/// RHS values are both in the computation type for the operator.
922void CodeGenFunction::
923EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
924 LValue &LHSLV, RValue &LHS, RValue &RHS) {
925 LHSLV = EmitLValue(E->getLHS());
926
927 // Load the LHS and RHS operands.
928 QualType LHSTy = E->getLHS()->getType();
929 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner2af72ac2007-08-08 17:43:05 +0000930 RHS = EmitExpr(E->getRHS());
931 QualType RHSTy = E->getRHS()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000932
933 // Convert the LHS and RHS to the common evaluation type.
934 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
935 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
936}
937
938/// EmitCompoundAssignmentResult - Given a result value in the computation type,
939/// truncate it down to the actual result type, store it through the LHS lvalue,
940/// and return it.
941RValue CodeGenFunction::
942EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
943 LValue LHSLV, RValue ResV) {
944
945 // Truncate back to the destination type.
946 if (E->getComputationType() != E->getType())
947 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
948
949 // Store the result value into the LHS.
950 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
951
952 // Return the result.
953 return ResV;
954}
955
956
957RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
958 RValue LHS, RHS;
959 switch (E->getOpcode()) {
960 default:
961 fprintf(stderr, "Unimplemented binary expr!\n");
962 E->dump();
963 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
964 case BinaryOperator::Mul:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000965 LHS = EmitExpr(E->getLHS());
966 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000967 return EmitMul(LHS, RHS, E->getType());
968 case BinaryOperator::Div:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000969 LHS = EmitExpr(E->getLHS());
970 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000971 return EmitDiv(LHS, RHS, E->getType());
972 case BinaryOperator::Rem:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000973 LHS = EmitExpr(E->getLHS());
974 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000975 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerbf49e992007-08-08 17:49:18 +0000976 case BinaryOperator::Add:
977 LHS = EmitExpr(E->getLHS());
978 RHS = EmitExpr(E->getRHS());
979 if (!E->getType()->isPointerType())
980 return EmitAdd(LHS, RHS, E->getType());
981
982 return EmitPointerAdd(LHS, E->getLHS()->getType(),
983 RHS, E->getRHS()->getType(), E->getType());
984 case BinaryOperator::Sub:
985 LHS = EmitExpr(E->getLHS());
986 RHS = EmitExpr(E->getRHS());
987
988 if (!E->getLHS()->getType()->isPointerType())
989 return EmitSub(LHS, RHS, E->getType());
990
991 return EmitPointerSub(LHS, E->getLHS()->getType(),
992 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +0000993 case BinaryOperator::Shl:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000994 LHS = EmitExpr(E->getLHS());
995 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000996 return EmitShl(LHS, RHS, E->getType());
997 case BinaryOperator::Shr:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000998 LHS = EmitExpr(E->getLHS());
999 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001000 return EmitShr(LHS, RHS, E->getType());
1001 case BinaryOperator::And:
Chris Lattnerbf49e992007-08-08 17:49:18 +00001002 LHS = EmitExpr(E->getLHS());
1003 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001004 return EmitAnd(LHS, RHS, E->getType());
1005 case BinaryOperator::Xor:
Chris Lattnerbf49e992007-08-08 17:49:18 +00001006 LHS = EmitExpr(E->getLHS());
1007 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001008 return EmitXor(LHS, RHS, E->getType());
1009 case BinaryOperator::Or :
Chris Lattnerbf49e992007-08-08 17:49:18 +00001010 LHS = EmitExpr(E->getLHS());
1011 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001012 return EmitOr(LHS, RHS, E->getType());
1013 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1014 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1015 case BinaryOperator::LT:
1016 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1017 llvm::ICmpInst::ICMP_SLT,
1018 llvm::FCmpInst::FCMP_OLT);
1019 case BinaryOperator::GT:
1020 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1021 llvm::ICmpInst::ICMP_SGT,
1022 llvm::FCmpInst::FCMP_OGT);
1023 case BinaryOperator::LE:
1024 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1025 llvm::ICmpInst::ICMP_SLE,
1026 llvm::FCmpInst::FCMP_OLE);
1027 case BinaryOperator::GE:
1028 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1029 llvm::ICmpInst::ICMP_SGE,
1030 llvm::FCmpInst::FCMP_OGE);
1031 case BinaryOperator::EQ:
1032 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1033 llvm::ICmpInst::ICMP_EQ,
1034 llvm::FCmpInst::FCMP_OEQ);
1035 case BinaryOperator::NE:
1036 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1037 llvm::ICmpInst::ICMP_NE,
1038 llvm::FCmpInst::FCMP_UNE);
1039 case BinaryOperator::Assign:
1040 return EmitBinaryAssign(E);
1041
1042 case BinaryOperator::MulAssign: {
1043 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1044 LValue LHSLV;
1045 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1046 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1047 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1048 }
1049 case BinaryOperator::DivAssign: {
1050 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1051 LValue LHSLV;
1052 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1053 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1054 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1055 }
1056 case BinaryOperator::RemAssign: {
1057 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1058 LValue LHSLV;
1059 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1060 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1061 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1062 }
1063 case BinaryOperator::AddAssign: {
1064 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1065 LValue LHSLV;
1066 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1067 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1068 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1069 }
1070 case BinaryOperator::SubAssign: {
1071 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1072 LValue LHSLV;
1073 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1074 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1075 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1076 }
1077 case BinaryOperator::ShlAssign: {
1078 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1079 LValue LHSLV;
1080 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1081 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1082 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1083 }
1084 case BinaryOperator::ShrAssign: {
1085 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1086 LValue LHSLV;
1087 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1088 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1089 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1090 }
1091 case BinaryOperator::AndAssign: {
1092 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1093 LValue LHSLV;
1094 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1095 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1096 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1097 }
1098 case BinaryOperator::OrAssign: {
1099 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1100 LValue LHSLV;
1101 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1102 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1103 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1104 }
1105 case BinaryOperator::XorAssign: {
1106 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1107 LValue LHSLV;
1108 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1109 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1110 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1111 }
1112 case BinaryOperator::Comma: return EmitBinaryComma(E);
1113 }
1114}
1115
1116RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1117 if (LHS.isScalar())
1118 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1119
1120 // Otherwise, this must be a complex number.
1121 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1122
1123 EmitLoadOfComplex(LHS, LHSR, LHSI);
1124 EmitLoadOfComplex(RHS, RHSR, RHSI);
1125
1126 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1127 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1128 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1129
1130 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1131 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1132 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1133
1134 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1135 EmitStoreOfComplex(ResR, ResI, Res);
1136 return RValue::getAggregate(Res);
1137}
1138
1139RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1140 if (LHS.isScalar()) {
1141 llvm::Value *RV;
1142 if (LHS.getVal()->getType()->isFloatingPoint())
1143 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1144 else if (ResTy->isUnsignedIntegerType())
1145 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1146 else
1147 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1148 return RValue::get(RV);
1149 }
1150 assert(0 && "FIXME: This doesn't handle complex operands yet");
1151}
1152
1153RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1154 if (LHS.isScalar()) {
1155 llvm::Value *RV;
1156 // Rem in C can't be a floating point type: C99 6.5.5p2.
1157 if (ResTy->isUnsignedIntegerType())
1158 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1159 else
1160 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1161 return RValue::get(RV);
1162 }
1163
1164 assert(0 && "FIXME: This doesn't handle complex operands yet");
1165}
1166
1167RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1168 if (LHS.isScalar())
1169 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1170
1171 // Otherwise, this must be a complex number.
1172 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1173
1174 EmitLoadOfComplex(LHS, LHSR, LHSI);
1175 EmitLoadOfComplex(RHS, RHSR, RHSI);
1176
1177 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1178 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1179
1180 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1181 EmitStoreOfComplex(ResR, ResI, Res);
1182 return RValue::getAggregate(Res);
1183}
1184
1185RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1186 RValue RHS, QualType RHSTy,
1187 QualType ResTy) {
1188 llvm::Value *LHSValue = LHS.getVal();
1189 llvm::Value *RHSValue = RHS.getVal();
1190 if (LHSTy->isPointerType()) {
1191 // pointer + int
1192 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1193 } else {
1194 // int + pointer
1195 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1196 }
1197}
1198
1199RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1200 if (LHS.isScalar())
1201 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1202
1203 assert(0 && "FIXME: This doesn't handle complex operands yet");
1204}
1205
1206RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1207 RValue RHS, QualType RHSTy,
1208 QualType ResTy) {
1209 llvm::Value *LHSValue = LHS.getVal();
1210 llvm::Value *RHSValue = RHS.getVal();
1211 if (const PointerType *RHSPtrType =
1212 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1213 // pointer - pointer
1214 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1215 QualType LHSElementType = LHSPtrType->getPointeeType();
1216 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1217 "can't subtract pointers with differing element types");
1218 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1219 SourceLocation()) / 8;
1220 const llvm::Type *ResultType = ConvertType(ResTy);
1221 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1222 "sub.ptr.lhs.cast");
1223 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1224 "sub.ptr.rhs.cast");
1225 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1226 "sub.ptr.sub");
1227
1228 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1229 // remainder. As such, we handle common power-of-two cases here to generate
1230 // better code.
1231 if (llvm::isPowerOf2_64(ElementSize)) {
1232 llvm::Value *ShAmt =
1233 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1234 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1235 } else {
1236 // Otherwise, do a full sdiv.
1237 llvm::Value *BytesPerElement =
1238 llvm::ConstantInt::get(ResultType, ElementSize);
1239 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1240 "sub.ptr.div"));
1241 }
1242 } else {
1243 // pointer - int
1244 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1245 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1246 }
1247}
1248
Chris Lattner4b009652007-07-25 00:24:17 +00001249RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1250 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1251
1252 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1253 // RHS to the same size as the LHS.
1254 if (LHS->getType() != RHS->getType())
1255 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1256
1257 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1258}
1259
1260RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1261 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1262
1263 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1264 // RHS to the same size as the LHS.
1265 if (LHS->getType() != RHS->getType())
1266 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1267
1268 if (ResTy->isUnsignedIntegerType())
1269 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1270 else
1271 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1272}
1273
1274RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1275 unsigned UICmpOpc, unsigned SICmpOpc,
1276 unsigned FCmpOpc) {
Chris Lattnerbf49e992007-08-08 17:49:18 +00001277 RValue LHS = EmitExpr(E->getLHS());
1278 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001279
1280 llvm::Value *Result;
1281 if (LHS.isScalar()) {
1282 if (LHS.getVal()->getType()->isFloatingPoint()) {
1283 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1284 LHS.getVal(), RHS.getVal(), "cmp");
1285 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1286 // FIXME: This check isn't right for "unsigned short < int" where ushort
1287 // promotes to int and does a signed compare.
1288 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1289 LHS.getVal(), RHS.getVal(), "cmp");
1290 } else {
1291 // Signed integers and pointers.
1292 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1293 LHS.getVal(), RHS.getVal(), "cmp");
1294 }
1295 } else {
1296 // Struct/union/complex
1297 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1298 EmitLoadOfComplex(LHS, LHSR, LHSI);
1299 EmitLoadOfComplex(RHS, RHSR, RHSI);
1300
1301 // FIXME: need to consider _Complex over integers too!
1302
1303 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1304 LHSR, RHSR, "cmp.r");
1305 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1306 LHSI, RHSI, "cmp.i");
1307 if (BinaryOperator::EQ == E->getOpcode()) {
1308 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1309 } else if (BinaryOperator::NE == E->getOpcode()) {
1310 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1311 } else {
1312 assert(0 && "Complex comparison other than == or != ?");
1313 }
1314 }
1315
1316 // ZExt result to int.
1317 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1318}
1319
1320RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1321 if (LHS.isScalar())
1322 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1323
1324 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1325}
1326
1327RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1328 if (LHS.isScalar())
1329 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1330
1331 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1332}
1333
1334RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1335 if (LHS.isScalar())
1336 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1337
1338 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1339}
1340
1341RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1342 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1343
1344 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1345 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1346
1347 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1348 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1349
1350 EmitBlock(RHSBlock);
1351 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1352
1353 // Reaquire the RHS block, as there may be subblocks inserted.
1354 RHSBlock = Builder.GetInsertBlock();
1355 EmitBlock(ContBlock);
1356
1357 // Create a PHI node. If we just evaluted the LHS condition, the result is
1358 // false. If we evaluated both, the result is the RHS condition.
1359 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1360 PN->reserveOperandSpace(2);
1361 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1362 PN->addIncoming(RHSCond, RHSBlock);
1363
1364 // ZExt result to int.
1365 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1366}
1367
1368RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1369 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1370
1371 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1372 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1373
1374 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1375 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1376
1377 EmitBlock(RHSBlock);
1378 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1379
1380 // Reaquire the RHS block, as there may be subblocks inserted.
1381 RHSBlock = Builder.GetInsertBlock();
1382 EmitBlock(ContBlock);
1383
1384 // Create a PHI node. If we just evaluted the LHS condition, the result is
1385 // true. If we evaluated both, the result is the RHS condition.
1386 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1387 PN->reserveOperandSpace(2);
1388 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1389 PN->addIncoming(RHSCond, RHSBlock);
1390
1391 // ZExt result to int.
1392 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1393}
1394
1395RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +00001396 assert(E->getLHS()->getType().getCanonicalType() ==
1397 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner4b009652007-07-25 00:24:17 +00001398 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2af72ac2007-08-08 17:43:05 +00001399 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001400
1401 // Store the value into the LHS.
1402 EmitStoreThroughLValue(RHS, LHS, E->getType());
1403
1404 // Return the converted RHS.
1405 return RHS;
1406}
1407
1408
1409RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1410 EmitExpr(E->getLHS());
1411 return EmitExpr(E->getRHS());
1412}
1413
1414RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1415 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1416 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1417 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1418
1419 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1420 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1421
1422 // FIXME: Implement this for aggregate values.
1423
Chris Lattner4b009652007-07-25 00:24:17 +00001424 EmitBlock(LHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001425 // Handle the GNU extension for missing LHS.
1426 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner4b009652007-07-25 00:24:17 +00001427 Builder.CreateBr(ContBlock);
1428 LHSBlock = Builder.GetInsertBlock();
1429
1430 EmitBlock(RHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001431
1432 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +00001433 Builder.CreateBr(ContBlock);
1434 RHSBlock = Builder.GetInsertBlock();
1435
1436 const llvm::Type *LHSType = LHSValue->getType();
1437 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1438
1439 EmitBlock(ContBlock);
1440 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1441 PN->reserveOperandSpace(2);
1442 PN->addIncoming(LHSValue, LHSBlock);
1443 PN->addIncoming(RHSValue, RHSBlock);
1444
1445 return RValue::get(PN);
1446}