blob: 65d03c2d1ea89b01ee7ac8569016edd1942c7a1b [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
724 // FIXME: Handle struct return.
725 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000726 QualType ArgTy = E->getArg(i)->getType();
727 RValue ArgVal = EmitExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000728
729 // If this argument has prototype information, convert it.
730 if (ArgTyIt != ArgTyEnd) {
731 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
732 } else {
733 // Otherwise, if passing through "..." or to a function with no prototype,
734 // perform the "default argument promotions" (C99 6.5.2.2p6), which
735 // includes the usual unary conversions, but also promotes float to
736 // double.
737 if (const BuiltinType *BT =
738 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
739 if (BT->getKind() == BuiltinType::Float)
740 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
741 llvm::Type::DoubleTy,"tmp"));
742 }
743 }
744
745
746 if (ArgVal.isScalar())
747 Args.push_back(ArgVal.getVal());
748 else // Pass by-address. FIXME: Set attribute bit on call.
749 Args.push_back(ArgVal.getAggregateAddr());
750 }
751
Chris Lattnera9572252007-08-01 06:24:52 +0000752 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000753 if (V->getType() != llvm::Type::VoidTy)
754 V->setName("call");
755
756 // FIXME: Struct return;
757 return RValue::get(V);
758}
759
760
761//===----------------------------------------------------------------------===//
762// Unary Operator Emission
763//===----------------------------------------------------------------------===//
764
Chris Lattner4b009652007-07-25 00:24:17 +0000765RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
766 switch (E->getOpcode()) {
767 default:
768 printf("Unimplemented unary expr!\n");
769 E->dump();
770 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
771 case UnaryOperator::PostInc:
772 case UnaryOperator::PostDec:
773 case UnaryOperator::PreInc :
774 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
775 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
776 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
777 case UnaryOperator::Plus : return EmitUnaryPlus(E);
778 case UnaryOperator::Minus : return EmitUnaryMinus(E);
779 case UnaryOperator::Not : return EmitUnaryNot(E);
780 case UnaryOperator::LNot : return EmitUnaryLNot(E);
781 case UnaryOperator::SizeOf :
782 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
783 case UnaryOperator::AlignOf :
784 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
785 // FIXME: real/imag
786 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
787 }
788}
789
790RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
791 LValue LV = EmitLValue(E->getSubExpr());
792 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
793
794 // We know the operand is real or pointer type, so it must be an LLVM scalar.
795 assert(InVal.isScalar() && "Unknown thing to increment");
796 llvm::Value *InV = InVal.getVal();
797
798 int AmountVal = 1;
799 if (E->getOpcode() == UnaryOperator::PreDec ||
800 E->getOpcode() == UnaryOperator::PostDec)
801 AmountVal = -1;
802
803 llvm::Value *NextVal;
804 if (isa<llvm::IntegerType>(InV->getType())) {
805 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
806 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
807 } else if (InV->getType()->isFloatingPoint()) {
808 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
809 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
810 } else {
811 // FIXME: This is not right for pointers to VLA types.
812 assert(isa<llvm::PointerType>(InV->getType()));
813 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
814 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
815 }
816
817 RValue NextValToStore = RValue::get(NextVal);
818
819 // Store the updated result through the lvalue.
820 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
821
822 // If this is a postinc, return the value read from memory, otherwise use the
823 // updated value.
824 if (E->getOpcode() == UnaryOperator::PreDec ||
825 E->getOpcode() == UnaryOperator::PreInc)
826 return NextValToStore;
827 else
828 return InVal;
829}
830
831/// C99 6.5.3.2
832RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
833 // The address of the operand is just its lvalue. It cannot be a bitfield.
834 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
835}
836
837RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000838 assert(E->getType().getCanonicalType() ==
839 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
840 // Unary plus just returns its value.
841 return EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000842}
843
844RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000845 assert(E->getType().getCanonicalType() ==
846 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
847
Chris Lattner4b009652007-07-25 00:24:17 +0000848 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000849 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000850
851 if (V.isScalar())
852 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
853
854 assert(0 && "FIXME: This doesn't handle complex operands yet");
855}
856
857RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
858 // Unary not performs promotions, then complements its integer operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000859 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000860
861 if (V.isScalar())
862 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
863
864 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
865}
866
867
868/// C99 6.5.3.3
869RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
870 // Compare operand to zero.
871 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
872
873 // Invert value.
874 // TODO: Could dynamically modify easy computations here. For example, if
875 // the operand is an icmp ne, turn into icmp eq.
876 BoolVal = Builder.CreateNot(BoolVal, "lnot");
877
878 // ZExt result to int.
879 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
880}
881
882/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
883/// an integer (RetType).
884RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
885 QualType RetType, bool isSizeOf) {
886 /// FIXME: This doesn't handle VLAs yet!
887 std::pair<uint64_t, unsigned> Info =
888 getContext().getTypeInfo(TypeToSize, SourceLocation());
889
890 uint64_t Val = isSizeOf ? Info.first : Info.second;
891 Val /= 8; // Return size in bytes, not bits.
892
893 assert(RetType->isIntegerType() && "Result type must be an integer!");
894
895 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
896 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
897}
898
899
900//===--------------------------------------------------------------------===//
901// Binary Operator Emission
902//===--------------------------------------------------------------------===//
903
Chris Lattner4b009652007-07-25 00:24:17 +0000904
905/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
906/// are strange in that the result of the operation is not the same type as the
907/// intermediate computation. This function emits the LHS and RHS operands of
908/// the compound assignment, promoting them to their common computation type.
909///
910/// Since the LHS is an lvalue, and the result is stored back through it, we
911/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
912/// RHS values are both in the computation type for the operator.
913void CodeGenFunction::
914EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
915 LValue &LHSLV, RValue &LHS, RValue &RHS) {
916 LHSLV = EmitLValue(E->getLHS());
917
918 // Load the LHS and RHS operands.
919 QualType LHSTy = E->getLHS()->getType();
920 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner2af72ac2007-08-08 17:43:05 +0000921 RHS = EmitExpr(E->getRHS());
922 QualType RHSTy = E->getRHS()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000923
924 // Convert the LHS and RHS to the common evaluation type.
925 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
926 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
927}
928
929/// EmitCompoundAssignmentResult - Given a result value in the computation type,
930/// truncate it down to the actual result type, store it through the LHS lvalue,
931/// and return it.
932RValue CodeGenFunction::
933EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
934 LValue LHSLV, RValue ResV) {
935
936 // Truncate back to the destination type.
937 if (E->getComputationType() != E->getType())
938 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
939
940 // Store the result value into the LHS.
941 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
942
943 // Return the result.
944 return ResV;
945}
946
947
948RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
949 RValue LHS, RHS;
950 switch (E->getOpcode()) {
951 default:
952 fprintf(stderr, "Unimplemented binary expr!\n");
953 E->dump();
954 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
955 case BinaryOperator::Mul:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000956 LHS = EmitExpr(E->getLHS());
957 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000958 return EmitMul(LHS, RHS, E->getType());
959 case BinaryOperator::Div:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000960 LHS = EmitExpr(E->getLHS());
961 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000962 return EmitDiv(LHS, RHS, E->getType());
963 case BinaryOperator::Rem:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000964 LHS = EmitExpr(E->getLHS());
965 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000966 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerbf49e992007-08-08 17:49:18 +0000967 case BinaryOperator::Add:
968 LHS = EmitExpr(E->getLHS());
969 RHS = EmitExpr(E->getRHS());
970 if (!E->getType()->isPointerType())
971 return EmitAdd(LHS, RHS, E->getType());
972
973 return EmitPointerAdd(LHS, E->getLHS()->getType(),
974 RHS, E->getRHS()->getType(), E->getType());
975 case BinaryOperator::Sub:
976 LHS = EmitExpr(E->getLHS());
977 RHS = EmitExpr(E->getRHS());
978
979 if (!E->getLHS()->getType()->isPointerType())
980 return EmitSub(LHS, RHS, E->getType());
981
982 return EmitPointerSub(LHS, E->getLHS()->getType(),
983 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +0000984 case BinaryOperator::Shl:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000985 LHS = EmitExpr(E->getLHS());
986 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000987 return EmitShl(LHS, RHS, E->getType());
988 case BinaryOperator::Shr:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000989 LHS = EmitExpr(E->getLHS());
990 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000991 return EmitShr(LHS, RHS, E->getType());
992 case BinaryOperator::And:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000993 LHS = EmitExpr(E->getLHS());
994 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000995 return EmitAnd(LHS, RHS, E->getType());
996 case BinaryOperator::Xor:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000997 LHS = EmitExpr(E->getLHS());
998 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000999 return EmitXor(LHS, RHS, E->getType());
1000 case BinaryOperator::Or :
Chris Lattnerbf49e992007-08-08 17:49:18 +00001001 LHS = EmitExpr(E->getLHS());
1002 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001003 return EmitOr(LHS, RHS, E->getType());
1004 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1005 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1006 case BinaryOperator::LT:
1007 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1008 llvm::ICmpInst::ICMP_SLT,
1009 llvm::FCmpInst::FCMP_OLT);
1010 case BinaryOperator::GT:
1011 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1012 llvm::ICmpInst::ICMP_SGT,
1013 llvm::FCmpInst::FCMP_OGT);
1014 case BinaryOperator::LE:
1015 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1016 llvm::ICmpInst::ICMP_SLE,
1017 llvm::FCmpInst::FCMP_OLE);
1018 case BinaryOperator::GE:
1019 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1020 llvm::ICmpInst::ICMP_SGE,
1021 llvm::FCmpInst::FCMP_OGE);
1022 case BinaryOperator::EQ:
1023 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1024 llvm::ICmpInst::ICMP_EQ,
1025 llvm::FCmpInst::FCMP_OEQ);
1026 case BinaryOperator::NE:
1027 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1028 llvm::ICmpInst::ICMP_NE,
1029 llvm::FCmpInst::FCMP_UNE);
1030 case BinaryOperator::Assign:
1031 return EmitBinaryAssign(E);
1032
1033 case BinaryOperator::MulAssign: {
1034 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1035 LValue LHSLV;
1036 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1037 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1038 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1039 }
1040 case BinaryOperator::DivAssign: {
1041 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1042 LValue LHSLV;
1043 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1044 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1045 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1046 }
1047 case BinaryOperator::RemAssign: {
1048 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1049 LValue LHSLV;
1050 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1051 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1052 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1053 }
1054 case BinaryOperator::AddAssign: {
1055 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1056 LValue LHSLV;
1057 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1058 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1059 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1060 }
1061 case BinaryOperator::SubAssign: {
1062 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1063 LValue LHSLV;
1064 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1065 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1066 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1067 }
1068 case BinaryOperator::ShlAssign: {
1069 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1070 LValue LHSLV;
1071 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1072 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1073 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1074 }
1075 case BinaryOperator::ShrAssign: {
1076 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1077 LValue LHSLV;
1078 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1079 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1080 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1081 }
1082 case BinaryOperator::AndAssign: {
1083 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1084 LValue LHSLV;
1085 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1086 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1087 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1088 }
1089 case BinaryOperator::OrAssign: {
1090 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1091 LValue LHSLV;
1092 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1093 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1094 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1095 }
1096 case BinaryOperator::XorAssign: {
1097 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1098 LValue LHSLV;
1099 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1100 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1101 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1102 }
1103 case BinaryOperator::Comma: return EmitBinaryComma(E);
1104 }
1105}
1106
1107RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1108 if (LHS.isScalar())
1109 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1110
1111 // Otherwise, this must be a complex number.
1112 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1113
1114 EmitLoadOfComplex(LHS, LHSR, LHSI);
1115 EmitLoadOfComplex(RHS, RHSR, RHSI);
1116
1117 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1118 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1119 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1120
1121 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1122 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1123 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1124
1125 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1126 EmitStoreOfComplex(ResR, ResI, Res);
1127 return RValue::getAggregate(Res);
1128}
1129
1130RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1131 if (LHS.isScalar()) {
1132 llvm::Value *RV;
1133 if (LHS.getVal()->getType()->isFloatingPoint())
1134 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1135 else if (ResTy->isUnsignedIntegerType())
1136 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1137 else
1138 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1139 return RValue::get(RV);
1140 }
1141 assert(0 && "FIXME: This doesn't handle complex operands yet");
1142}
1143
1144RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1145 if (LHS.isScalar()) {
1146 llvm::Value *RV;
1147 // Rem in C can't be a floating point type: C99 6.5.5p2.
1148 if (ResTy->isUnsignedIntegerType())
1149 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1150 else
1151 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1152 return RValue::get(RV);
1153 }
1154
1155 assert(0 && "FIXME: This doesn't handle complex operands yet");
1156}
1157
1158RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1159 if (LHS.isScalar())
1160 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1161
1162 // Otherwise, this must be a complex number.
1163 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1164
1165 EmitLoadOfComplex(LHS, LHSR, LHSI);
1166 EmitLoadOfComplex(RHS, RHSR, RHSI);
1167
1168 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1169 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1170
1171 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1172 EmitStoreOfComplex(ResR, ResI, Res);
1173 return RValue::getAggregate(Res);
1174}
1175
1176RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1177 RValue RHS, QualType RHSTy,
1178 QualType ResTy) {
1179 llvm::Value *LHSValue = LHS.getVal();
1180 llvm::Value *RHSValue = RHS.getVal();
1181 if (LHSTy->isPointerType()) {
1182 // pointer + int
1183 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1184 } else {
1185 // int + pointer
1186 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1187 }
1188}
1189
1190RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1191 if (LHS.isScalar())
1192 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1193
1194 assert(0 && "FIXME: This doesn't handle complex operands yet");
1195}
1196
1197RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1198 RValue RHS, QualType RHSTy,
1199 QualType ResTy) {
1200 llvm::Value *LHSValue = LHS.getVal();
1201 llvm::Value *RHSValue = RHS.getVal();
1202 if (const PointerType *RHSPtrType =
1203 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1204 // pointer - pointer
1205 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1206 QualType LHSElementType = LHSPtrType->getPointeeType();
1207 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1208 "can't subtract pointers with differing element types");
1209 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1210 SourceLocation()) / 8;
1211 const llvm::Type *ResultType = ConvertType(ResTy);
1212 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1213 "sub.ptr.lhs.cast");
1214 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1215 "sub.ptr.rhs.cast");
1216 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1217 "sub.ptr.sub");
1218
1219 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1220 // remainder. As such, we handle common power-of-two cases here to generate
1221 // better code.
1222 if (llvm::isPowerOf2_64(ElementSize)) {
1223 llvm::Value *ShAmt =
1224 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1225 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1226 } else {
1227 // Otherwise, do a full sdiv.
1228 llvm::Value *BytesPerElement =
1229 llvm::ConstantInt::get(ResultType, ElementSize);
1230 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1231 "sub.ptr.div"));
1232 }
1233 } else {
1234 // pointer - int
1235 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1236 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1237 }
1238}
1239
Chris Lattner4b009652007-07-25 00:24:17 +00001240RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1241 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1242
1243 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1244 // RHS to the same size as the LHS.
1245 if (LHS->getType() != RHS->getType())
1246 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1247
1248 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1249}
1250
1251RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1252 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1253
1254 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1255 // RHS to the same size as the LHS.
1256 if (LHS->getType() != RHS->getType())
1257 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1258
1259 if (ResTy->isUnsignedIntegerType())
1260 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1261 else
1262 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1263}
1264
1265RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1266 unsigned UICmpOpc, unsigned SICmpOpc,
1267 unsigned FCmpOpc) {
Chris Lattnerbf49e992007-08-08 17:49:18 +00001268 RValue LHS = EmitExpr(E->getLHS());
1269 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001270
1271 llvm::Value *Result;
1272 if (LHS.isScalar()) {
1273 if (LHS.getVal()->getType()->isFloatingPoint()) {
1274 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1275 LHS.getVal(), RHS.getVal(), "cmp");
1276 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1277 // FIXME: This check isn't right for "unsigned short < int" where ushort
1278 // promotes to int and does a signed compare.
1279 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1280 LHS.getVal(), RHS.getVal(), "cmp");
1281 } else {
1282 // Signed integers and pointers.
1283 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1284 LHS.getVal(), RHS.getVal(), "cmp");
1285 }
1286 } else {
1287 // Struct/union/complex
1288 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1289 EmitLoadOfComplex(LHS, LHSR, LHSI);
1290 EmitLoadOfComplex(RHS, RHSR, RHSI);
1291
1292 // FIXME: need to consider _Complex over integers too!
1293
1294 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1295 LHSR, RHSR, "cmp.r");
1296 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1297 LHSI, RHSI, "cmp.i");
1298 if (BinaryOperator::EQ == E->getOpcode()) {
1299 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1300 } else if (BinaryOperator::NE == E->getOpcode()) {
1301 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1302 } else {
1303 assert(0 && "Complex comparison other than == or != ?");
1304 }
1305 }
1306
1307 // ZExt result to int.
1308 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1309}
1310
1311RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1312 if (LHS.isScalar())
1313 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1314
1315 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1316}
1317
1318RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1319 if (LHS.isScalar())
1320 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1321
1322 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1323}
1324
1325RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1326 if (LHS.isScalar())
1327 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1328
1329 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1330}
1331
1332RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1333 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1334
1335 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1336 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1337
1338 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1339 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1340
1341 EmitBlock(RHSBlock);
1342 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1343
1344 // Reaquire the RHS block, as there may be subblocks inserted.
1345 RHSBlock = Builder.GetInsertBlock();
1346 EmitBlock(ContBlock);
1347
1348 // Create a PHI node. If we just evaluted the LHS condition, the result is
1349 // false. If we evaluated both, the result is the RHS condition.
1350 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1351 PN->reserveOperandSpace(2);
1352 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1353 PN->addIncoming(RHSCond, RHSBlock);
1354
1355 // ZExt result to int.
1356 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1357}
1358
1359RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1360 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1361
1362 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1363 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1364
1365 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1366 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1367
1368 EmitBlock(RHSBlock);
1369 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1370
1371 // Reaquire the RHS block, as there may be subblocks inserted.
1372 RHSBlock = Builder.GetInsertBlock();
1373 EmitBlock(ContBlock);
1374
1375 // Create a PHI node. If we just evaluted the LHS condition, the result is
1376 // true. If we evaluated both, the result is the RHS condition.
1377 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1378 PN->reserveOperandSpace(2);
1379 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1380 PN->addIncoming(RHSCond, RHSBlock);
1381
1382 // ZExt result to int.
1383 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1384}
1385
1386RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +00001387 assert(E->getLHS()->getType().getCanonicalType() ==
1388 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner4b009652007-07-25 00:24:17 +00001389 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2af72ac2007-08-08 17:43:05 +00001390 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001391
1392 // Store the value into the LHS.
1393 EmitStoreThroughLValue(RHS, LHS, E->getType());
1394
1395 // Return the converted RHS.
1396 return RHS;
1397}
1398
1399
1400RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1401 EmitExpr(E->getLHS());
1402 return EmitExpr(E->getRHS());
1403}
1404
1405RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1406 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1407 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1408 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1409
1410 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1411 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1412
1413 // FIXME: Implement this for aggregate values.
1414
Chris Lattner4b009652007-07-25 00:24:17 +00001415 EmitBlock(LHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001416 // Handle the GNU extension for missing LHS.
1417 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner4b009652007-07-25 00:24:17 +00001418 Builder.CreateBr(ContBlock);
1419 LHSBlock = Builder.GetInsertBlock();
1420
1421 EmitBlock(RHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001422
1423 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +00001424 Builder.CreateBr(ContBlock);
1425 RHSBlock = Builder.GetInsertBlock();
1426
1427 const llvm::Type *LHSType = LHSValue->getType();
1428 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1429
1430 EmitBlock(ContBlock);
1431 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1432 PN->reserveOperandSpace(2);
1433 PN->addIncoming(LHSValue, LHSBlock);
1434 PN->addIncoming(RHSValue, RHSBlock);
1435
1436 return RValue::get(PN);
1437}