blob: 8937eaffba682f0d4abb59bcece40cc300fe6c94 [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) {
Chris Lattnerd4f08022007-08-08 17:43:05 +000039 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +000040}
41
42/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
43/// load the real and imaginary pieces, returning them as Real/Imag.
44void CodeGenFunction::EmitLoadOfComplex(RValue V,
45 llvm::Value *&Real, llvm::Value *&Imag){
46 llvm::Value *Ptr = V.getAggregateAddr();
47
48 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
49 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
50 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
51 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
52
53 // FIXME: Handle volatility.
54 Real = Builder.CreateLoad(RealPtr, "real");
55 Imag = Builder.CreateLoad(ImagPtr, "imag");
56}
57
58/// EmitStoreOfComplex - Store the specified real/imag parts into the
59/// specified value pointer.
60void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
61 llvm::Value *ResPtr) {
62 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
63 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
64 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
65 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
66
67 // FIXME: Handle volatility.
68 Builder.CreateStore(Real, RealPtr);
69 Builder.CreateStore(Imag, ImagPtr);
70}
71
72//===--------------------------------------------------------------------===//
73// Conversions
74//===--------------------------------------------------------------------===//
75
76/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
77/// the type specified by DstTy, following the rules of C99 6.3.
78RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
79 QualType DstTy) {
80 ValTy = ValTy.getCanonicalType();
81 DstTy = DstTy.getCanonicalType();
82 if (ValTy == DstTy) return Val;
83
84 // Handle conversions to bool first, they are special: comparisons against 0.
85 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
86 if (DestBT->getKind() == BuiltinType::Bool)
87 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
88
89 // Handle pointer conversions next: pointers can only be converted to/from
90 // other pointers and integers.
91 if (isa<PointerType>(DstTy)) {
92 const llvm::Type *DestTy = ConvertType(DstTy);
93
Chris Lattner461766a2007-08-10 16:33:59 +000094 if (Val.getVal()->getType() == DestTy)
95 return Val;
96
Reid Spencer5f016e22007-07-11 17:01:13 +000097 // The source value may be an integer, or a pointer.
98 assert(Val.isScalar() && "Can only convert from integer or pointer");
99 if (isa<llvm::PointerType>(Val.getVal()->getType()))
100 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
101 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Chris Lattnerfa7c6452007-07-13 03:25:53 +0000102 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 }
104
105 if (isa<PointerType>(ValTy)) {
106 // Must be an ptr to int cast.
107 const llvm::Type *DestTy = ConvertType(DstTy);
108 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
109 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
110 }
111
112 // Finally, we have the arithmetic types: real int/float and complex
113 // int/float. Handle real->real conversions first, they are the most
114 // common.
115 if (Val.isScalar() && DstTy->isRealType()) {
116 // We know that these are representable as scalars in LLVM, convert to LLVM
117 // types since they are easier to reason about.
118 llvm::Value *SrcVal = Val.getVal();
119 const llvm::Type *DestTy = ConvertType(DstTy);
120 if (SrcVal->getType() == DestTy) return Val;
121
122 llvm::Value *Result;
123 if (isa<llvm::IntegerType>(SrcVal->getType())) {
124 bool InputSigned = ValTy->isSignedIntegerType();
125 if (isa<llvm::IntegerType>(DestTy))
126 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
127 else if (InputSigned)
128 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
129 else
130 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
131 } else {
132 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
133 if (isa<llvm::IntegerType>(DestTy)) {
134 if (DstTy->isSignedIntegerType())
135 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
136 else
137 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
138 } else {
139 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
140 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
141 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
142 else
143 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
144 }
145 }
146 return RValue::get(Result);
147 }
148
149 assert(0 && "FIXME: We don't support complex conversions yet!");
150}
151
152
153/// ConvertScalarValueToBool - Convert the specified expression value to a
154/// boolean (i1) truth value. This is equivalent to "Val == 0".
155llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
156 Ty = Ty.getCanonicalType();
157 llvm::Value *Result;
158 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
159 switch (BT->getKind()) {
160 default: assert(0 && "Unknown scalar value");
161 case BuiltinType::Bool:
162 Result = Val.getVal();
163 // Bool is already evaluated right.
164 assert(Result->getType() == llvm::Type::Int1Ty &&
165 "Unexpected bool value type!");
166 return Result;
167 case BuiltinType::Char_S:
168 case BuiltinType::Char_U:
169 case BuiltinType::SChar:
170 case BuiltinType::UChar:
171 case BuiltinType::Short:
172 case BuiltinType::UShort:
173 case BuiltinType::Int:
174 case BuiltinType::UInt:
175 case BuiltinType::Long:
176 case BuiltinType::ULong:
177 case BuiltinType::LongLong:
178 case BuiltinType::ULongLong:
179 // Code below handles simple integers.
180 break;
181 case BuiltinType::Float:
182 case BuiltinType::Double:
183 case BuiltinType::LongDouble: {
184 // Compare against 0.0 for fp scalars.
185 Result = Val.getVal();
186 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
187 // FIXME: llvm-gcc produces a une comparison: validate this is right.
188 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
189 return Result;
190 }
191 }
192 } else if (isa<PointerType>(Ty) ||
193 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
194 // Code below handles this fine.
195 } else {
196 assert(isa<ComplexType>(Ty) && "Unknwon type!");
197 assert(0 && "FIXME: comparisons against complex not implemented yet");
198 }
199
200 // Usual case for integers, pointers, and enums: compare against zero.
201 Result = Val.getVal();
202
203 // Because of the type rules of C, we often end up computing a logical value,
204 // then zero extending it to int, then wanting it as a logical value again.
205 // Optimize this common case.
206 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
207 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
208 Result = ZI->getOperand(0);
209 ZI->eraseFromParent();
210 return Result;
211 }
212 }
213
214 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
215 return Builder.CreateICmpNE(Result, Zero, "tobool");
216}
217
218//===----------------------------------------------------------------------===//
219// LValue Expression Emission
220//===----------------------------------------------------------------------===//
221
222/// EmitLValue - Emit code to compute a designator that specifies the location
223/// of the expression.
224///
225/// This can return one of two things: a simple address or a bitfield
226/// reference. In either case, the LLVM Value* in the LValue structure is
227/// guaranteed to be an LLVM pointer type.
228///
229/// If this returns a bitfield reference, nothing about the pointee type of
230/// the LLVM value is known: For example, it may not be a pointer to an
231/// integer.
232///
233/// If this returns a normal address, and if the lvalue's C type is fixed
234/// size, this method guarantees that the returned pointer type will point to
235/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
236/// variable length type, this is not possible.
237///
238LValue CodeGenFunction::EmitLValue(const Expr *E) {
239 switch (E->getStmtClass()) {
240 default:
241 fprintf(stderr, "Unimplemented lvalue expr!\n");
242 E->dump();
243 return LValue::MakeAddr(llvm::UndefValue::get(
244 llvm::PointerType::get(llvm::Type::Int32Ty)));
245
246 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
247 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson22742662007-07-21 05:21:51 +0000248 case Expr::PreDefinedExprClass:
249 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 case Expr::StringLiteralClass:
251 return EmitStringLiteralLValue(cast<StringLiteral>(E));
252
253 case Expr::UnaryOperatorClass:
254 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
255 case Expr::ArraySubscriptExprClass:
256 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattner6481a572007-08-03 17:31:20 +0000257 case Expr::OCUVectorElementExprClass:
258 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 }
260}
261
262/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
263/// this method emits the address of the lvalue, then loads the result as an
264/// rvalue, returning the rvalue.
265RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 if (LV.isSimple()) {
267 llvm::Value *Ptr = LV.getAddress();
268 const llvm::Type *EltTy =
269 cast<llvm::PointerType>(Ptr->getType())->getElementType();
270
271 // Simple scalar l-value.
272 if (EltTy->isFirstClassType())
273 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
274
Chris Lattner461766a2007-08-10 16:33:59 +0000275 if (ExprType->isFunctionType())
276 return RValue::get(Ptr);
277
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 // Otherwise, we have an aggregate lvalue.
279 return RValue::getAggregate(Ptr);
280 }
281
282 if (LV.isVectorElt()) {
283 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
284 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
285 "vecext"));
286 }
Chris Lattner46ea8eb2007-08-03 00:16:29 +0000287
288 // If this is a reference to a subset of the elements of a vector, either
289 // shuffle the input or extract/insert them as appropriate.
Chris Lattner6481a572007-08-03 17:31:20 +0000290 if (LV.isOCUVectorElt())
291 return EmitLoadOfOCUElementLValue(LV, ExprType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000292
293 assert(0 && "Bitfield ref not impl!");
294}
295
Chris Lattner34cdc862007-08-03 16:18:34 +0000296// If this is a reference to a subset of the elements of a vector, either
297// shuffle the input or extract/insert them as appropriate.
Chris Lattner6481a572007-08-03 17:31:20 +0000298RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattnercf60cd22007-08-10 17:10:08 +0000299 QualType ExprType) {
Chris Lattner34cdc862007-08-03 16:18:34 +0000300 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
301
Chris Lattner6481a572007-08-03 17:31:20 +0000302 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner34cdc862007-08-03 16:18:34 +0000303
304 // If the result of the expression is a non-vector type, we must be
305 // extracting a single element. Just codegen as an extractelement.
Chris Lattnercf60cd22007-08-10 17:10:08 +0000306 const VectorType *ExprVT = ExprType->getAsVectorType();
307 if (!ExprVT) {
Chris Lattner6481a572007-08-03 17:31:20 +0000308 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner34cdc862007-08-03 16:18:34 +0000309 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
310 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
311 }
312
313 // If the source and destination have the same number of elements, use a
314 // vector shuffle instead of insert/extracts.
Chris Lattnercf60cd22007-08-10 17:10:08 +0000315 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner34cdc862007-08-03 16:18:34 +0000316 unsigned NumSourceElts =
317 cast<llvm::VectorType>(Vec->getType())->getNumElements();
318
319 if (NumResultElts == NumSourceElts) {
320 llvm::SmallVector<llvm::Constant*, 4> Mask;
321 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattner6481a572007-08-03 17:31:20 +0000322 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner34cdc862007-08-03 16:18:34 +0000323 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
324 }
325
326 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
327 Vec = Builder.CreateShuffleVector(Vec,
328 llvm::UndefValue::get(Vec->getType()),
329 MaskV, "tmp");
330 return RValue::get(Vec);
331 }
332
333 // Start out with an undef of the result type.
334 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
335
336 // Extract/Insert each element of the result.
337 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattner6481a572007-08-03 17:31:20 +0000338 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner34cdc862007-08-03 16:18:34 +0000339 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
340 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
341
342 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
343 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
344 }
345
346 return RValue::get(Result);
347}
348
349
Reid Spencer5f016e22007-07-11 17:01:13 +0000350RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
351 return EmitLoadOfLValue(EmitLValue(E), E->getType());
352}
353
354
355/// EmitStoreThroughLValue - Store the specified rvalue into the specified
356/// lvalue, where both are guaranteed to the have the same type, and that type
357/// is 'Ty'.
358void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
359 QualType Ty) {
Chris Lattner017d6aa2007-08-03 16:28:33 +0000360 if (!Dst.isSimple()) {
361 if (Dst.isVectorElt()) {
362 // Read/modify/write the vector, inserting the new element.
363 // FIXME: Volatility.
364 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
365 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
366 Dst.getVectorIdx(), "vecins");
367 Builder.CreateStore(Vec, Dst.getVectorAddr());
368 return;
369 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
Chris Lattner017d6aa2007-08-03 16:28:33 +0000371 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattner6481a572007-08-03 17:31:20 +0000372 if (Dst.isOCUVectorElt())
Chris Lattner017d6aa2007-08-03 16:28:33 +0000373 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
374
375 assert(0 && "FIXME: Don't support store to bitfield yet");
376 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000377
378 llvm::Value *DstAddr = Dst.getAddress();
379 if (Src.isScalar()) {
380 // FIXME: Handle volatility etc.
381 const llvm::Type *SrcTy = Src.getVal()->getType();
382 const llvm::Type *AddrTy =
383 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
384
385 if (AddrTy != SrcTy)
386 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
387 "storetmp");
388 Builder.CreateStore(Src.getVal(), DstAddr);
389 return;
390 }
391
392 // Don't use memcpy for complex numbers.
393 if (Ty->isComplexType()) {
394 llvm::Value *Real, *Imag;
395 EmitLoadOfComplex(Src, Real, Imag);
396 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
397 return;
398 }
399
400 // Aggregate assignment turns into llvm.memcpy.
401 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
402 llvm::Value *SrcAddr = Src.getAggregateAddr();
403
404 if (DstAddr->getType() != SBP)
405 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
406 if (SrcAddr->getType() != SBP)
407 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
408
409 unsigned Align = 1; // FIXME: Compute type alignments.
410 unsigned Size = 1234; // FIXME: Compute type sizes.
411
412 // FIXME: Handle variable sized types.
413 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
414 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
415
416 llvm::Value *MemCpyOps[4] = {
417 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
418 };
419
Chris Lattnerbf986512007-08-01 06:24:52 +0000420 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
Reid Spencer5f016e22007-07-11 17:01:13 +0000421}
422
Chris Lattner017d6aa2007-08-03 16:28:33 +0000423void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
424 QualType Ty) {
425 // This access turns into a read/modify/write of the vector. Load the input
426 // value now.
427 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
428 // FIXME: Volatility.
Chris Lattner6481a572007-08-03 17:31:20 +0000429 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner017d6aa2007-08-03 16:28:33 +0000430
431 llvm::Value *SrcVal = Src.getVal();
432
Chris Lattner7e6b51b2007-08-03 16:37:04 +0000433 if (const VectorType *VTy = Ty->getAsVectorType()) {
434 unsigned NumSrcElts = VTy->getNumElements();
435
436 // Extract/Insert each element.
437 for (unsigned i = 0; i != NumSrcElts; ++i) {
438 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
439 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
440
Chris Lattner6481a572007-08-03 17:31:20 +0000441 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner7e6b51b2007-08-03 16:37:04 +0000442 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
443 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
444 }
445 } else {
446 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattner6481a572007-08-03 17:31:20 +0000447 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner017d6aa2007-08-03 16:28:33 +0000448 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
449 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner017d6aa2007-08-03 16:28:33 +0000450 }
451
Chris Lattner017d6aa2007-08-03 16:28:33 +0000452 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
453}
454
Reid Spencer5f016e22007-07-11 17:01:13 +0000455
456LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
457 const Decl *D = E->getDecl();
458 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
459 llvm::Value *V = LocalDeclMap[D];
460 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
461 return LValue::MakeAddr(V);
462 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
463 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
464 }
465 assert(0 && "Unimp declref");
466}
467
468LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
469 // __extension__ doesn't affect lvalue-ness.
470 if (E->getOpcode() == UnaryOperator::Extension)
471 return EmitLValue(E->getSubExpr());
472
473 assert(E->getOpcode() == UnaryOperator::Deref &&
474 "'*' is the only unary operator that produces an lvalue");
475 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
476}
477
478LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
479 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
480 const char *StrData = E->getStrData();
481 unsigned Len = E->getByteLength();
482
483 // FIXME: Can cache/reuse these within the module.
484 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
485
486 // Create a global variable for this.
487 C = new llvm::GlobalVariable(C->getType(), true,
488 llvm::GlobalValue::InternalLinkage,
489 C, ".str", CurFn->getParent());
490 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
491 llvm::Constant *Zeros[] = { Zero, Zero };
492 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
493 return LValue::MakeAddr(C);
494}
495
Anders Carlsson22742662007-07-21 05:21:51 +0000496LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
497 std::string FunctionName(CurFuncDecl->getName());
498 std::string GlobalVarName;
499
500 switch (E->getIdentType()) {
501 default:
502 assert(0 && "unknown pre-defined ident type");
503 case PreDefinedExpr::Func:
504 GlobalVarName = "__func__.";
505 break;
506 case PreDefinedExpr::Function:
507 GlobalVarName = "__FUNCTION__.";
508 break;
509 case PreDefinedExpr::PrettyFunction:
510 // FIXME:: Demangle C++ method names
511 GlobalVarName = "__PRETTY_FUNCTION__.";
512 break;
513 }
514
515 GlobalVarName += CurFuncDecl->getName();
516
517 // FIXME: Can cache/reuse these within the module.
518 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
519
520 // Create a global variable for this.
521 C = new llvm::GlobalVariable(C->getType(), true,
522 llvm::GlobalValue::InternalLinkage,
523 C, GlobalVarName, CurFn->getParent());
524 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
525 llvm::Constant *Zeros[] = { Zero, Zero };
526 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
527 return LValue::MakeAddr(C);
528}
529
Reid Spencer5f016e22007-07-11 17:01:13 +0000530LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
531 // The index must always be a pointer or integer, neither of which is an
532 // aggregate. Emit it.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000533 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000534
535 // If the base is a vector type, then we are forming a vector element lvalue
536 // with this subscript.
537 if (E->getBase()->getType()->isVectorType()) {
538 // Emit the vector as an lvalue to get its address.
539 LValue Base = EmitLValue(E->getBase());
540 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
541 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
542 return LValue::MakeVectorElt(Base.getAddress(), Idx);
543 }
544
545 // At this point, the base must be a pointer or integer, neither of which are
546 // aggregates. Emit it.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000547 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000548
549 // Usually the base is the pointer type, but sometimes it is the index.
550 // Canonicalize to have the pointer as the base.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000551 QualType BaseTy = E->getBase()->getType();
552 QualType IdxTy = E->getIdx()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 if (isa<llvm::PointerType>(Idx->getType())) {
554 std::swap(Base, Idx);
555 std::swap(BaseTy, IdxTy);
556 }
557
558 // The pointer is now the base. Extend or truncate the index type to 32 or
559 // 64-bits.
560 bool IdxSigned = IdxTy->isSignedIntegerType();
561 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
562 if (IdxBitwidth != LLVMPointerWidth)
563 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
564 IdxSigned, "idxprom");
565
566 // We know that the pointer points to a type of the correct size, unless the
567 // size is a VLA.
Chris Lattner590b6642007-07-15 23:26:56 +0000568 if (!E->getType()->isConstantSizeType(getContext()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 assert(0 && "VLA idx not implemented");
570 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
571}
572
Chris Lattner349aaec2007-08-02 23:37:31 +0000573LValue CodeGenFunction::
Chris Lattner6481a572007-08-03 17:31:20 +0000574EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner349aaec2007-08-02 23:37:31 +0000575 // Emit the base vector as an l-value.
576 LValue Base = EmitLValue(E->getBase());
577 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
578
Chris Lattner6481a572007-08-03 17:31:20 +0000579 return LValue::MakeOCUVectorElt(Base.getAddress(),
580 E->getEncodedElementAccess());
Chris Lattner349aaec2007-08-02 23:37:31 +0000581}
582
Reid Spencer5f016e22007-07-11 17:01:13 +0000583//===--------------------------------------------------------------------===//
584// Expression Emission
585//===--------------------------------------------------------------------===//
586
587RValue CodeGenFunction::EmitExpr(const Expr *E) {
588 assert(E && "Null expression?");
589
590 switch (E->getStmtClass()) {
591 default:
592 fprintf(stderr, "Unimplemented expr!\n");
593 E->dump();
594 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
595
596 // l-values.
597 case Expr::DeclRefExprClass:
598 // DeclRef's of EnumConstantDecl's are simple rvalues.
599 if (const EnumConstantDecl *EC =
600 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
601 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
602 return EmitLoadOfLValue(E);
603 case Expr::ArraySubscriptExprClass:
604 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattner6481a572007-08-03 17:31:20 +0000605 case Expr::OCUVectorElementExprClass:
Chris Lattner46ea8eb2007-08-03 00:16:29 +0000606 return EmitLoadOfLValue(E);
Anders Carlsson22742662007-07-21 05:21:51 +0000607 case Expr::PreDefinedExprClass:
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 case Expr::StringLiteralClass:
609 return RValue::get(EmitLValue(E).getAddress());
610
611 // Leaf expressions.
612 case Expr::IntegerLiteralClass:
613 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
614 case Expr::FloatingLiteralClass:
615 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000616 case Expr::CharacterLiteralClass:
617 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner30bf3ae2007-08-03 17:51:03 +0000618 case Expr::TypesCompatibleExprClass:
619 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000620
621 // Operators.
622 case Expr::ParenExprClass:
623 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
624 case Expr::UnaryOperatorClass:
625 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000626 case Expr::SizeOfAlignOfTypeExprClass:
627 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
628 E->getType(),
629 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000630 case Expr::ImplicitCastExprClass:
631 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 case Expr::CastExprClass:
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000633 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 case Expr::CallExprClass:
635 return EmitCallExpr(cast<CallExpr>(E));
636 case Expr::BinaryOperatorClass:
637 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000638
639 case Expr::ConditionalOperatorClass:
640 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner94f05e32007-08-04 00:20:15 +0000641 case Expr::ChooseExprClass:
642 return EmitChooseExpr(cast<ChooseExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
644
645}
646
647RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
648 return RValue::get(llvm::ConstantInt::get(E->getValue()));
649}
650RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
651 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
652 E->getValue()));
653}
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000654RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
655 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
656 E->getValue()));
657}
Reid Spencer5f016e22007-07-11 17:01:13 +0000658
Chris Lattner30bf3ae2007-08-03 17:51:03 +0000659RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
660 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
661 E->typesAreCompatible()));
662}
663
Chris Lattner94f05e32007-08-04 00:20:15 +0000664/// EmitChooseExpr - Implement __builtin_choose_expr.
665RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
666 llvm::APSInt CondVal(32);
667 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
668 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
669
670 // Emit the LHS or RHS as appropriate.
671 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
672}
673
Chris Lattner30bf3ae2007-08-03 17:51:03 +0000674
Reid Spencer5f016e22007-07-11 17:01:13 +0000675RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
676 // Emit subscript expressions in rvalue context's. For most cases, this just
677 // loads the lvalue formed by the subscript expr. However, we have to be
678 // careful, because the base of a vector subscript is occasionally an rvalue,
679 // so we can't get it as an lvalue.
680 if (!E->getBase()->getType()->isVectorType())
681 return EmitLoadOfLValue(E);
682
683 // Handle the vector case. The base must be a vector, the index must be an
684 // integer value.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000685 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
686 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000687
688 // FIXME: Convert Idx to i32 type.
689
690 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
691}
692
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000693// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
694// have to handle a more broad range of conversions than explicit casts, as they
695// handle things like function to ptr-to-function decay etc.
696RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000697 RValue Src = EmitExpr(Op);
Reid Spencer5f016e22007-07-11 17:01:13 +0000698
699 // If the destination is void, just evaluate the source.
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000700 if (DestTy->isVoidType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 return RValue::getAggregate(0);
702
Chris Lattnerd4f08022007-08-08 17:43:05 +0000703 return EmitConversion(Src, Op->getType(), DestTy);
Reid Spencer5f016e22007-07-11 17:01:13 +0000704}
705
706RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000707 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Reid Spencer5f016e22007-07-11 17:01:13 +0000708
709 // The callee type will always be a pointer to function type, get the function
710 // type.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000711 QualType CalleeTy = E->getCallee()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
713
714 // Get information about the argument types.
715 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
716
717 // Calling unprototyped functions provides no argument info.
718 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
719 ArgTyIt = FTP->arg_type_begin();
720 ArgTyEnd = FTP->arg_type_end();
721 }
722
723 llvm::SmallVector<llvm::Value*, 16> Args;
724
Chris Lattnercc666af2007-08-10 17:02:28 +0000725 // Handle struct-return functions by passing a pointer to the location that
726 // we would like to return into.
727 if (hasAggregateLLVMType(E->getType())) {
728 // Create a temporary alloca to hold the result of the call. :(
729 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
730 // FIXME: set the stret attribute on the argument.
731 }
732
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000734 QualType ArgTy = E->getArg(i)->getType();
735 RValue ArgVal = EmitExpr(E->getArg(i));
Reid Spencer5f016e22007-07-11 17:01:13 +0000736
737 // If this argument has prototype information, convert it.
738 if (ArgTyIt != ArgTyEnd) {
739 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
740 } else {
741 // Otherwise, if passing through "..." or to a function with no prototype,
742 // perform the "default argument promotions" (C99 6.5.2.2p6), which
743 // includes the usual unary conversions, but also promotes float to
744 // double.
745 if (const BuiltinType *BT =
746 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
747 if (BT->getKind() == BuiltinType::Float)
748 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
749 llvm::Type::DoubleTy,"tmp"));
750 }
751 }
752
753
754 if (ArgVal.isScalar())
755 Args.push_back(ArgVal.getVal());
756 else // Pass by-address. FIXME: Set attribute bit on call.
757 Args.push_back(ArgVal.getAggregateAddr());
758 }
759
Chris Lattnerbf986512007-08-01 06:24:52 +0000760 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 if (V->getType() != llvm::Type::VoidTy)
762 V->setName("call");
Chris Lattnercc666af2007-08-10 17:02:28 +0000763 else if (hasAggregateLLVMType(E->getType()))
764 // Struct return.
765 return RValue::getAggregate(Args[0]);
766
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 return RValue::get(V);
768}
769
770
771//===----------------------------------------------------------------------===//
772// Unary Operator Emission
773//===----------------------------------------------------------------------===//
774
Reid Spencer5f016e22007-07-11 17:01:13 +0000775RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
776 switch (E->getOpcode()) {
777 default:
778 printf("Unimplemented unary expr!\n");
779 E->dump();
780 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattner57274792007-07-11 23:43:46 +0000781 case UnaryOperator::PostInc:
782 case UnaryOperator::PostDec:
783 case UnaryOperator::PreInc :
784 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
785 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
786 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
787 case UnaryOperator::Plus : return EmitUnaryPlus(E);
788 case UnaryOperator::Minus : return EmitUnaryMinus(E);
789 case UnaryOperator::Not : return EmitUnaryNot(E);
790 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000791 case UnaryOperator::SizeOf :
792 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
793 case UnaryOperator::AlignOf :
794 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 // FIXME: real/imag
796 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
797 }
798}
799
Chris Lattner57274792007-07-11 23:43:46 +0000800RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
801 LValue LV = EmitLValue(E->getSubExpr());
802 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
803
804 // We know the operand is real or pointer type, so it must be an LLVM scalar.
805 assert(InVal.isScalar() && "Unknown thing to increment");
806 llvm::Value *InV = InVal.getVal();
807
808 int AmountVal = 1;
809 if (E->getOpcode() == UnaryOperator::PreDec ||
810 E->getOpcode() == UnaryOperator::PostDec)
811 AmountVal = -1;
812
813 llvm::Value *NextVal;
814 if (isa<llvm::IntegerType>(InV->getType())) {
815 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
816 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
817 } else if (InV->getType()->isFloatingPoint()) {
818 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
819 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
820 } else {
821 // FIXME: This is not right for pointers to VLA types.
822 assert(isa<llvm::PointerType>(InV->getType()));
823 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
824 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
825 }
826
827 RValue NextValToStore = RValue::get(NextVal);
828
829 // Store the updated result through the lvalue.
830 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
831
832 // If this is a postinc, return the value read from memory, otherwise use the
833 // updated value.
834 if (E->getOpcode() == UnaryOperator::PreDec ||
835 E->getOpcode() == UnaryOperator::PreInc)
836 return NextValToStore;
837 else
838 return InVal;
839}
840
Reid Spencer5f016e22007-07-11 17:01:13 +0000841/// C99 6.5.3.2
842RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
843 // The address of the operand is just its lvalue. It cannot be a bitfield.
844 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
845}
846
847RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000848 assert(E->getType().getCanonicalType() ==
849 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
850 // Unary plus just returns its value.
851 return EmitExpr(E->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000852}
853
854RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +0000855 assert(E->getType().getCanonicalType() ==
856 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
857
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000859 RValue V = EmitExpr(E->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000860
861 if (V.isScalar())
862 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
863
864 assert(0 && "FIXME: This doesn't handle complex operands yet");
865}
866
867RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
868 // Unary not performs promotions, then complements its integer operand.
Chris Lattnerd4f08022007-08-08 17:43:05 +0000869 RValue V = EmitExpr(E->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000870
871 if (V.isScalar())
872 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
873
874 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
875}
876
877
878/// C99 6.5.3.3
879RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
880 // Compare operand to zero.
881 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
882
883 // Invert value.
884 // TODO: Could dynamically modify easy computations here. For example, if
885 // the operand is an icmp ne, turn into icmp eq.
886 BoolVal = Builder.CreateNot(BoolVal, "lnot");
887
888 // ZExt result to int.
889 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
890}
891
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000892/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
893/// an integer (RetType).
894RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
895 QualType RetType, bool isSizeOf) {
896 /// FIXME: This doesn't handle VLAs yet!
897 std::pair<uint64_t, unsigned> Info =
898 getContext().getTypeInfo(TypeToSize, SourceLocation());
899
900 uint64_t Val = isSizeOf ? Info.first : Info.second;
901 Val /= 8; // Return size in bytes, not bits.
902
903 assert(RetType->isIntegerType() && "Result type must be an integer!");
904
905 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
906 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
907}
908
Reid Spencer5f016e22007-07-11 17:01:13 +0000909
910//===--------------------------------------------------------------------===//
911// Binary Operator Emission
912//===--------------------------------------------------------------------===//
913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914
915/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
916/// are strange in that the result of the operation is not the same type as the
917/// intermediate computation. This function emits the LHS and RHS operands of
918/// the compound assignment, promoting them to their common computation type.
919///
920/// Since the LHS is an lvalue, and the result is stored back through it, we
921/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
922/// RHS values are both in the computation type for the operator.
923void CodeGenFunction::
924EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
925 LValue &LHSLV, RValue &LHS, RValue &RHS) {
926 LHSLV = EmitLValue(E->getLHS());
927
928 // Load the LHS and RHS operands.
929 QualType LHSTy = E->getLHS()->getType();
930 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattnerd4f08022007-08-08 17:43:05 +0000931 RHS = EmitExpr(E->getRHS());
932 QualType RHSTy = E->getRHS()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000933
934 // Convert the LHS and RHS to the common evaluation type.
935 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
936 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
937}
938
939/// EmitCompoundAssignmentResult - Given a result value in the computation type,
940/// truncate it down to the actual result type, store it through the LHS lvalue,
941/// and return it.
942RValue CodeGenFunction::
943EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
944 LValue LHSLV, RValue ResV) {
945
946 // Truncate back to the destination type.
947 if (E->getComputationType() != E->getType())
948 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
949
950 // Store the result value into the LHS.
951 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
952
953 // Return the result.
954 return ResV;
955}
956
957
958RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
959 RValue LHS, RHS;
960 switch (E->getOpcode()) {
961 default:
962 fprintf(stderr, "Unimplemented binary expr!\n");
963 E->dump();
964 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
965 case BinaryOperator::Mul:
Chris Lattner6c216162007-08-08 17:49:18 +0000966 LHS = EmitExpr(E->getLHS());
967 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 return EmitMul(LHS, RHS, E->getType());
969 case BinaryOperator::Div:
Chris Lattner6c216162007-08-08 17:49:18 +0000970 LHS = EmitExpr(E->getLHS());
971 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 return EmitDiv(LHS, RHS, E->getType());
973 case BinaryOperator::Rem:
Chris Lattner6c216162007-08-08 17:49:18 +0000974 LHS = EmitExpr(E->getLHS());
975 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 return EmitRem(LHS, RHS, E->getType());
Chris Lattner6c216162007-08-08 17:49:18 +0000977 case BinaryOperator::Add:
978 LHS = EmitExpr(E->getLHS());
979 RHS = EmitExpr(E->getRHS());
980 if (!E->getType()->isPointerType())
981 return EmitAdd(LHS, RHS, E->getType());
982
983 return EmitPointerAdd(LHS, E->getLHS()->getType(),
984 RHS, E->getRHS()->getType(), E->getType());
985 case BinaryOperator::Sub:
986 LHS = EmitExpr(E->getLHS());
987 RHS = EmitExpr(E->getRHS());
988
989 if (!E->getLHS()->getType()->isPointerType())
990 return EmitSub(LHS, RHS, E->getType());
991
992 return EmitPointerSub(LHS, E->getLHS()->getType(),
993 RHS, E->getRHS()->getType(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 case BinaryOperator::Shl:
Chris Lattnerd4f08022007-08-08 17:43:05 +0000995 LHS = EmitExpr(E->getLHS());
996 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 return EmitShl(LHS, RHS, E->getType());
998 case BinaryOperator::Shr:
Chris Lattnerd4f08022007-08-08 17:43:05 +0000999 LHS = EmitExpr(E->getLHS());
1000 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 return EmitShr(LHS, RHS, E->getType());
1002 case BinaryOperator::And:
Chris Lattner6c216162007-08-08 17:49:18 +00001003 LHS = EmitExpr(E->getLHS());
1004 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 return EmitAnd(LHS, RHS, E->getType());
1006 case BinaryOperator::Xor:
Chris Lattner6c216162007-08-08 17:49:18 +00001007 LHS = EmitExpr(E->getLHS());
1008 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 return EmitXor(LHS, RHS, E->getType());
1010 case BinaryOperator::Or :
Chris Lattner6c216162007-08-08 17:49:18 +00001011 LHS = EmitExpr(E->getLHS());
1012 RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 return EmitOr(LHS, RHS, E->getType());
1014 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1015 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1016 case BinaryOperator::LT:
1017 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1018 llvm::ICmpInst::ICMP_SLT,
1019 llvm::FCmpInst::FCMP_OLT);
1020 case BinaryOperator::GT:
1021 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1022 llvm::ICmpInst::ICMP_SGT,
1023 llvm::FCmpInst::FCMP_OGT);
1024 case BinaryOperator::LE:
1025 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1026 llvm::ICmpInst::ICMP_SLE,
1027 llvm::FCmpInst::FCMP_OLE);
1028 case BinaryOperator::GE:
1029 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1030 llvm::ICmpInst::ICMP_SGE,
1031 llvm::FCmpInst::FCMP_OGE);
1032 case BinaryOperator::EQ:
1033 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1034 llvm::ICmpInst::ICMP_EQ,
1035 llvm::FCmpInst::FCMP_OEQ);
1036 case BinaryOperator::NE:
1037 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1038 llvm::ICmpInst::ICMP_NE,
1039 llvm::FCmpInst::FCMP_UNE);
1040 case BinaryOperator::Assign:
1041 return EmitBinaryAssign(E);
1042
1043 case BinaryOperator::MulAssign: {
1044 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1045 LValue LHSLV;
1046 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1047 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1048 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1049 }
1050 case BinaryOperator::DivAssign: {
1051 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1052 LValue LHSLV;
1053 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1054 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1055 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1056 }
1057 case BinaryOperator::RemAssign: {
1058 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1059 LValue LHSLV;
1060 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1061 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1062 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1063 }
1064 case BinaryOperator::AddAssign: {
1065 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1066 LValue LHSLV;
1067 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1068 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1069 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1070 }
1071 case BinaryOperator::SubAssign: {
1072 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1073 LValue LHSLV;
1074 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1075 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1076 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1077 }
1078 case BinaryOperator::ShlAssign: {
1079 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1080 LValue LHSLV;
1081 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1082 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1083 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1084 }
1085 case BinaryOperator::ShrAssign: {
1086 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1087 LValue LHSLV;
1088 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1089 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1090 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1091 }
1092 case BinaryOperator::AndAssign: {
1093 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1094 LValue LHSLV;
1095 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1096 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1097 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1098 }
1099 case BinaryOperator::OrAssign: {
1100 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1101 LValue LHSLV;
1102 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1103 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1104 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1105 }
1106 case BinaryOperator::XorAssign: {
1107 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1108 LValue LHSLV;
1109 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1110 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1111 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1112 }
1113 case BinaryOperator::Comma: return EmitBinaryComma(E);
1114 }
1115}
1116
1117RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1118 if (LHS.isScalar())
1119 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1120
Gabor Greif4db18f22007-07-13 23:33:18 +00001121 // Otherwise, this must be a complex number.
1122 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1123
1124 EmitLoadOfComplex(LHS, LHSR, LHSI);
1125 EmitLoadOfComplex(RHS, RHSR, RHSI);
1126
1127 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1128 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1129 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1130
1131 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1132 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1133 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1134
1135 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1136 EmitStoreOfComplex(ResR, ResI, Res);
1137 return RValue::getAggregate(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001138}
1139
1140RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1141 if (LHS.isScalar()) {
1142 llvm::Value *RV;
1143 if (LHS.getVal()->getType()->isFloatingPoint())
1144 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1145 else if (ResTy->isUnsignedIntegerType())
1146 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1147 else
1148 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1149 return RValue::get(RV);
1150 }
1151 assert(0 && "FIXME: This doesn't handle complex operands yet");
1152}
1153
1154RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1155 if (LHS.isScalar()) {
1156 llvm::Value *RV;
1157 // Rem in C can't be a floating point type: C99 6.5.5p2.
1158 if (ResTy->isUnsignedIntegerType())
1159 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1160 else
1161 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1162 return RValue::get(RV);
1163 }
1164
1165 assert(0 && "FIXME: This doesn't handle complex operands yet");
1166}
1167
1168RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1169 if (LHS.isScalar())
1170 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1171
1172 // Otherwise, this must be a complex number.
1173 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1174
1175 EmitLoadOfComplex(LHS, LHSR, LHSI);
1176 EmitLoadOfComplex(RHS, RHSR, RHSI);
1177
1178 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1179 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1180
1181 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1182 EmitStoreOfComplex(ResR, ResI, Res);
1183 return RValue::getAggregate(Res);
1184}
1185
Chris Lattner8b9023b2007-07-13 03:05:23 +00001186RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1187 RValue RHS, QualType RHSTy,
1188 QualType ResTy) {
1189 llvm::Value *LHSValue = LHS.getVal();
1190 llvm::Value *RHSValue = RHS.getVal();
1191 if (LHSTy->isPointerType()) {
1192 // pointer + int
1193 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1194 } else {
1195 // int + pointer
1196 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1197 }
1198}
1199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1201 if (LHS.isScalar())
1202 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1203
1204 assert(0 && "FIXME: This doesn't handle complex operands yet");
1205}
1206
Chris Lattner8b9023b2007-07-13 03:05:23 +00001207RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1208 RValue RHS, QualType RHSTy,
1209 QualType ResTy) {
1210 llvm::Value *LHSValue = LHS.getVal();
1211 llvm::Value *RHSValue = RHS.getVal();
1212 if (const PointerType *RHSPtrType =
1213 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1214 // pointer - pointer
1215 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1216 QualType LHSElementType = LHSPtrType->getPointeeType();
1217 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1218 "can't subtract pointers with differing element types");
Chris Lattner99e0d792007-07-16 05:43:05 +00001219 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001220 SourceLocation()) / 8;
Chris Lattner8b9023b2007-07-13 03:05:23 +00001221 const llvm::Type *ResultType = ConvertType(ResTy);
1222 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1223 "sub.ptr.lhs.cast");
1224 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1225 "sub.ptr.rhs.cast");
1226 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1227 "sub.ptr.sub");
Chris Lattner99e0d792007-07-16 05:43:05 +00001228
1229 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1230 // remainder. As such, we handle common power-of-two cases here to generate
1231 // better code.
1232 if (llvm::isPowerOf2_64(ElementSize)) {
1233 llvm::Value *ShAmt =
1234 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1235 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1236 } else {
1237 // Otherwise, do a full sdiv.
1238 llvm::Value *BytesPerElement =
1239 llvm::ConstantInt::get(ResultType, ElementSize);
1240 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1241 "sub.ptr.div"));
1242 }
Chris Lattner8b9023b2007-07-13 03:05:23 +00001243 } else {
1244 // pointer - int
1245 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1246 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1247 }
1248}
1249
Reid Spencer5f016e22007-07-11 17:01:13 +00001250RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1251 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1252
1253 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1254 // RHS to the same size as the LHS.
1255 if (LHS->getType() != RHS->getType())
1256 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1257
1258 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1259}
1260
1261RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1262 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1263
1264 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1265 // RHS to the same size as the LHS.
1266 if (LHS->getType() != RHS->getType())
1267 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1268
1269 if (ResTy->isUnsignedIntegerType())
1270 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1271 else
1272 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1273}
1274
1275RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1276 unsigned UICmpOpc, unsigned SICmpOpc,
1277 unsigned FCmpOpc) {
Chris Lattner6c216162007-08-08 17:49:18 +00001278 RValue LHS = EmitExpr(E->getLHS());
1279 RValue RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001280
1281 llvm::Value *Result;
1282 if (LHS.isScalar()) {
1283 if (LHS.getVal()->getType()->isFloatingPoint()) {
1284 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1285 LHS.getVal(), RHS.getVal(), "cmp");
1286 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1287 // FIXME: This check isn't right for "unsigned short < int" where ushort
1288 // promotes to int and does a signed compare.
1289 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1290 LHS.getVal(), RHS.getVal(), "cmp");
1291 } else {
1292 // Signed integers and pointers.
1293 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1294 LHS.getVal(), RHS.getVal(), "cmp");
1295 }
1296 } else {
1297 // Struct/union/complex
Gabor Greif4db18f22007-07-13 23:33:18 +00001298 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1299 EmitLoadOfComplex(LHS, LHSR, LHSI);
1300 EmitLoadOfComplex(RHS, RHSR, RHSI);
1301
Gabor Greifd5e0d982007-07-14 20:05:18 +00001302 // FIXME: need to consider _Complex over integers too!
1303
Gabor Greif4db18f22007-07-13 23:33:18 +00001304 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1305 LHSR, RHSR, "cmp.r");
1306 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1307 LHSI, RHSI, "cmp.i");
1308 if (BinaryOperator::EQ == E->getOpcode()) {
1309 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1310 } else if (BinaryOperator::NE == E->getOpcode()) {
1311 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1312 } else {
1313 assert(0 && "Complex comparison other than == or != ?");
1314 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 }
Gabor Greif4db18f22007-07-13 23:33:18 +00001316
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // ZExt result to int.
1318 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1319}
1320
1321RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1322 if (LHS.isScalar())
1323 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1324
1325 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1326}
1327
1328RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1329 if (LHS.isScalar())
1330 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1331
1332 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1333}
1334
1335RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1336 if (LHS.isScalar())
1337 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1338
1339 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1340}
1341
1342RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1343 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1344
1345 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1346 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1347
1348 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1349 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1350
1351 EmitBlock(RHSBlock);
1352 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1353
1354 // Reaquire the RHS block, as there may be subblocks inserted.
1355 RHSBlock = Builder.GetInsertBlock();
1356 EmitBlock(ContBlock);
1357
1358 // Create a PHI node. If we just evaluted the LHS condition, the result is
1359 // false. If we evaluated both, the result is the RHS condition.
1360 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1361 PN->reserveOperandSpace(2);
1362 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1363 PN->addIncoming(RHSCond, RHSBlock);
1364
1365 // ZExt result to int.
1366 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1367}
1368
1369RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1370 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1371
1372 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1373 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1374
1375 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1376 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1377
1378 EmitBlock(RHSBlock);
1379 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1380
1381 // Reaquire the RHS block, as there may be subblocks inserted.
1382 RHSBlock = Builder.GetInsertBlock();
1383 EmitBlock(ContBlock);
1384
1385 // Create a PHI node. If we just evaluted the LHS condition, the result is
1386 // true. If we evaluated both, the result is the RHS condition.
1387 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1388 PN->reserveOperandSpace(2);
1389 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1390 PN->addIncoming(RHSCond, RHSBlock);
1391
1392 // ZExt result to int.
1393 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1394}
1395
1396RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattnerd4f08022007-08-08 17:43:05 +00001397 assert(E->getLHS()->getType().getCanonicalType() ==
1398 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 LValue LHS = EmitLValue(E->getLHS());
Chris Lattnerd4f08022007-08-08 17:43:05 +00001400 RValue RHS = EmitExpr(E->getRHS());
Reid Spencer5f016e22007-07-11 17:01:13 +00001401
1402 // Store the value into the LHS.
1403 EmitStoreThroughLValue(RHS, LHS, E->getType());
1404
1405 // Return the converted RHS.
1406 return RHS;
1407}
1408
1409
1410RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1411 EmitExpr(E->getLHS());
1412 return EmitExpr(E->getRHS());
1413}
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001414
1415RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1416 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1417 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1418 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1419
1420 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1421 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1422
Chris Lattner06c8d962007-07-14 00:01:01 +00001423 // FIXME: Implement this for aggregate values.
1424
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001425 EmitBlock(LHSBlock);
Chris Lattnerd4f08022007-08-08 17:43:05 +00001426 // Handle the GNU extension for missing LHS.
1427 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001428 Builder.CreateBr(ContBlock);
1429 LHSBlock = Builder.GetInsertBlock();
1430
1431 EmitBlock(RHSBlock);
Chris Lattnerd4f08022007-08-08 17:43:05 +00001432
1433 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001434 Builder.CreateBr(ContBlock);
1435 RHSBlock = Builder.GetInsertBlock();
1436
1437 const llvm::Type *LHSType = LHSValue->getType();
1438 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1439
1440 EmitBlock(ContBlock);
1441 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1442 PN->reserveOperandSpace(2);
1443 PN->addIncoming(LHSValue, LHSBlock);
1444 PN->addIncoming(RHSValue, RHSBlock);
1445
1446 return RValue::get(PN);
1447}