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