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