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