blob: 6d735e0b5e138db91d3bbdde398a706321499fd0 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +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"
Chris Lattnerb6984c42007-06-20 04:44:43 +000015#include "CodeGenModule.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000016#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner4347e3692007-06-06 04:54:52 +000019#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
Chris Lattner651f0e92007-07-16 05:43:05 +000021#include "llvm/Support/MathExtras.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000022using namespace clang;
23using namespace CodeGen;
24
Chris Lattnerd7f58862007-06-02 05:24:33 +000025//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000026// Miscellaneous Helper Methods
27//===--------------------------------------------------------------------===//
28
Chris Lattnere9a64532007-06-22 21:44:33 +000029/// 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}
Chris Lattner8394d792007-06-05 20:53:16 +000035
36/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000038llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner8394d792007-06-05 20:53:16 +000039 QualType Ty;
40 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
41 return ConvertScalarValueToBool(Val, Ty);
42}
43
Chris Lattnere9a64532007-06-22 21:44:33 +000044/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
45/// load the real and imaginary pieces, returning them as Real/Imag.
46void CodeGenFunction::EmitLoadOfComplex(RValue V,
47 llvm::Value *&Real, llvm::Value *&Imag){
48 llvm::Value *Ptr = V.getAggregateAddr();
49
50 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
51 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
52 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
53 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
54
55 // FIXME: Handle volatility.
56 Real = Builder.CreateLoad(RealPtr, "real");
57 Imag = Builder.CreateLoad(ImagPtr, "imag");
58}
59
60/// EmitStoreOfComplex - Store the specified real/imag parts into the
61/// specified value pointer.
62void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
63 llvm::Value *ResPtr) {
64 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
65 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
66 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
67 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
68
69 // FIXME: Handle volatility.
70 Builder.CreateStore(Real, RealPtr);
71 Builder.CreateStore(Imag, ImagPtr);
72}
73
Chris Lattner8394d792007-06-05 20:53:16 +000074//===--------------------------------------------------------------------===//
75// Conversions
76//===--------------------------------------------------------------------===//
77
78/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
79/// the type specified by DstTy, following the rules of C99 6.3.
80RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
Chris Lattnerf033c142007-06-22 19:05:19 +000081 QualType DstTy) {
Chris Lattner8394d792007-06-05 20:53:16 +000082 ValTy = ValTy.getCanonicalType();
83 DstTy = DstTy.getCanonicalType();
84 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000085
86 // Handle conversions to bool first, they are special: comparisons against 0.
87 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
88 if (DestBT->getKind() == BuiltinType::Bool)
89 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
Chris Lattner8394d792007-06-05 20:53:16 +000090
Chris Lattner83b484b2007-06-06 04:39:08 +000091 // Handle pointer conversions next: pointers can only be converted to/from
92 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000093 if (isa<PointerType>(DstTy)) {
Chris Lattnerf033c142007-06-22 19:05:19 +000094 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000095
96 // The source value may be an integer, or a pointer.
97 assert(Val.isScalar() && "Can only convert from integer or pointer");
98 if (isa<llvm::PointerType>(Val.getVal()->getType()))
99 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
100 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Chris Lattnerfc7634f2007-07-13 03:25:53 +0000101 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +0000102 }
103
104 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +0000105 // Must be an ptr to int cast.
Chris Lattnerf033c142007-06-22 19:05:19 +0000106 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +0000107 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
108 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +0000109 }
Chris Lattner83b484b2007-06-06 04:39:08 +0000110
111 // Finally, we have the arithmetic types: real int/float and complex
112 // int/float. Handle real->real conversions first, they are the most
113 // common.
114 if (Val.isScalar() && DstTy->isRealType()) {
115 // We know that these are representable as scalars in LLVM, convert to LLVM
116 // types since they are easier to reason about.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000117 llvm::Value *SrcVal = Val.getVal();
Chris Lattnerf033c142007-06-22 19:05:19 +0000118 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattner83b484b2007-06-06 04:39:08 +0000119 if (SrcVal->getType() == DestTy) return Val;
120
Chris Lattner23b7eb62007-06-15 23:05:46 +0000121 llvm::Value *Result;
Chris Lattner83b484b2007-06-06 04:39:08 +0000122 if (isa<llvm::IntegerType>(SrcVal->getType())) {
123 bool InputSigned = ValTy->isSignedIntegerType();
124 if (isa<llvm::IntegerType>(DestTy))
125 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
126 else if (InputSigned)
127 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
128 else
129 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
130 } else {
131 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
132 if (isa<llvm::IntegerType>(DestTy)) {
133 if (DstTy->isSignedIntegerType())
134 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
135 else
136 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
137 } else {
138 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
139 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
140 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
141 else
142 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
143 }
144 }
145 return RValue::get(Result);
146 }
147
148 assert(0 && "FIXME: We don't support complex conversions yet!");
Chris Lattner8394d792007-06-05 20:53:16 +0000149}
150
151
152/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000153/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner23b7eb62007-06-15 23:05:46 +0000154llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
Chris Lattnerf0106d22007-06-02 19:33:17 +0000155 Ty = Ty.getCanonicalType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000156 llvm::Value *Result;
Chris Lattnerf0106d22007-06-02 19:33:17 +0000157 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
158 switch (BT->getKind()) {
159 default: assert(0 && "Unknown scalar value");
160 case BuiltinType::Bool:
161 Result = Val.getVal();
162 // Bool is already evaluated right.
163 assert(Result->getType() == llvm::Type::Int1Ty &&
164 "Unexpected bool value type!");
165 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000166 case BuiltinType::Char_S:
167 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000168 case BuiltinType::SChar:
169 case BuiltinType::UChar:
170 case BuiltinType::Short:
171 case BuiltinType::UShort:
172 case BuiltinType::Int:
173 case BuiltinType::UInt:
174 case BuiltinType::Long:
175 case BuiltinType::ULong:
176 case BuiltinType::LongLong:
177 case BuiltinType::ULongLong:
178 // Code below handles simple integers.
179 break;
180 case BuiltinType::Float:
181 case BuiltinType::Double:
182 case BuiltinType::LongDouble: {
183 // Compare against 0.0 for fp scalars.
184 Result = Val.getVal();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000185 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000186 // FIXME: llvm-gcc produces a une comparison: validate this is right.
187 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
188 return Result;
189 }
Chris Lattnerf0106d22007-06-02 19:33:17 +0000190 }
Chris Lattnerc6395932007-06-22 20:56:16 +0000191 } else if (isa<PointerType>(Ty) ||
192 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000193 // Code below handles this fine.
Chris Lattnerc6395932007-06-22 20:56:16 +0000194 } else {
195 assert(isa<ComplexType>(Ty) && "Unknwon type!");
196 assert(0 && "FIXME: comparisons against complex not implemented yet");
Chris Lattnerf0106d22007-06-02 19:33:17 +0000197 }
198
199 // Usual case for integers, pointers, and enums: compare against zero.
200 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000201
202 // Because of the type rules of C, we often end up computing a logical value,
203 // then zero extending it to int, then wanting it as a logical value again.
204 // Optimize this common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000205 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
Chris Lattnera45c5af2007-06-02 19:47:04 +0000206 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
207 Result = ZI->getOperand(0);
208 ZI->eraseFromParent();
209 return Result;
210 }
211 }
212
Chris Lattner23b7eb62007-06-15 23:05:46 +0000213 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000214 return Builder.CreateICmpNE(Result, Zero, "tobool");
215}
216
Chris Lattnera45c5af2007-06-02 19:47:04 +0000217//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000218// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000219//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000220
Chris Lattner8394d792007-06-05 20:53:16 +0000221/// EmitLValue - Emit code to compute a designator that specifies the location
222/// of the expression.
223///
224/// This can return one of two things: a simple address or a bitfield
225/// reference. In either case, the LLVM Value* in the LValue structure is
226/// guaranteed to be an LLVM pointer type.
227///
228/// If this returns a bitfield reference, nothing about the pointee type of
229/// the LLVM value is known: For example, it may not be a pointer to an
230/// integer.
231///
232/// If this returns a normal address, and if the lvalue's C type is fixed
233/// size, this method guarantees that the returned pointer type will point to
234/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
235/// variable length type, this is not possible.
236///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000237LValue CodeGenFunction::EmitLValue(const Expr *E) {
238 switch (E->getStmtClass()) {
239 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000240 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000241 E->dump();
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000242 return LValue::MakeAddr(llvm::UndefValue::get(
Chris Lattnerd7f58862007-06-02 05:24:33 +0000243 llvm::PointerType::get(llvm::Type::Int32Ty)));
244
245 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000246 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson625bfc82007-07-21 05:21:51 +0000247 case Expr::PreDefinedExprClass:
248 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000249 case Expr::StringLiteralClass:
250 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000251
252 case Expr::UnaryOperatorClass:
253 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000254 case Expr::ArraySubscriptExprClass:
255 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000256 }
257}
258
Chris Lattner8394d792007-06-05 20:53:16 +0000259/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
260/// this method emits the address of the lvalue, then loads the result as an
261/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000262RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
263 ExprType = ExprType.getCanonicalType();
Chris Lattner8394d792007-06-05 20:53:16 +0000264
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000265 if (LV.isSimple()) {
266 llvm::Value *Ptr = LV.getAddress();
267 const llvm::Type *EltTy =
268 cast<llvm::PointerType>(Ptr->getType())->getElementType();
269
270 // Simple scalar l-value.
271 if (EltTy->isFirstClassType())
272 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
273
274 // Otherwise, we have an aggregate lvalue.
275 return RValue::getAggregate(Ptr);
276 }
Chris Lattner09153c02007-06-22 18:48:09 +0000277
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000278 if (LV.isVectorElt()) {
279 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
280 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
281 "vecext"));
282 }
Chris Lattner09153c02007-06-22 18:48:09 +0000283
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000284 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000285}
286
Chris Lattner9369a562007-06-29 16:31:29 +0000287RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
288 return EmitLoadOfLValue(EmitLValue(E), E->getType());
289}
290
291
Chris Lattner8394d792007-06-05 20:53:16 +0000292/// EmitStoreThroughLValue - Store the specified rvalue into the specified
293/// lvalue, where both are guaranteed to the have the same type, and that type
294/// is 'Ty'.
295void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
296 QualType Ty) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000297 if (Dst.isVectorElt()) {
298 // Read/modify/write the vector, inserting the new element.
299 // FIXME: Volatility.
300 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
301 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
302 Dst.getVectorIdx(), "vecins");
303 Builder.CreateStore(Vec, Dst.getVectorAddr());
304 return;
305 }
306
307 assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
Chris Lattner8394d792007-06-05 20:53:16 +0000308
Chris Lattner09153c02007-06-22 18:48:09 +0000309 llvm::Value *DstAddr = Dst.getAddress();
310 if (Src.isScalar()) {
311 // FIXME: Handle volatility etc.
312 const llvm::Type *SrcTy = Src.getVal()->getType();
313 const llvm::Type *AddrTy =
314 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
315
316 if (AddrTy != SrcTy)
317 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
318 "storetmp");
319 Builder.CreateStore(Src.getVal(), DstAddr);
320 return;
321 }
Chris Lattner8394d792007-06-05 20:53:16 +0000322
Chris Lattnere9a64532007-06-22 21:44:33 +0000323 // Don't use memcpy for complex numbers.
324 if (Ty->isComplexType()) {
325 llvm::Value *Real, *Imag;
326 EmitLoadOfComplex(Src, Real, Imag);
327 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
328 return;
329 }
330
Chris Lattner09153c02007-06-22 18:48:09 +0000331 // Aggregate assignment turns into llvm.memcpy.
332 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
333 llvm::Value *SrcAddr = Src.getAggregateAddr();
334
335 if (DstAddr->getType() != SBP)
336 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
337 if (SrcAddr->getType() != SBP)
338 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
339
340 unsigned Align = 1; // FIXME: Compute type alignments.
341 unsigned Size = 1234; // FIXME: Compute type sizes.
342
343 // FIXME: Handle variable sized types.
344 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
345 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
346
347 llvm::Value *MemCpyOps[4] = {
348 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
349 };
350
351 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, 4);
Chris Lattner8394d792007-06-05 20:53:16 +0000352}
353
Chris Lattnerd7f58862007-06-02 05:24:33 +0000354
355LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
356 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000357 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000358 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000359 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000360 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000361 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000362 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000363 }
364 assert(0 && "Unimp declref");
365}
Chris Lattnere47e4402007-06-01 18:02:12 +0000366
Chris Lattner8394d792007-06-05 20:53:16 +0000367LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
368 // __extension__ doesn't affect lvalue-ness.
369 if (E->getOpcode() == UnaryOperator::Extension)
370 return EmitLValue(E->getSubExpr());
371
372 assert(E->getOpcode() == UnaryOperator::Deref &&
373 "'*' is the only unary operator that produces an lvalue");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000374 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
Chris Lattner8394d792007-06-05 20:53:16 +0000375}
376
Chris Lattner4347e3692007-06-06 04:54:52 +0000377LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
378 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
379 const char *StrData = E->getStrData();
380 unsigned Len = E->getByteLength();
381
382 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000383 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000384
385 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000386 C = new llvm::GlobalVariable(C->getType(), true,
387 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000388 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000389 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
390 llvm::Constant *Zeros[] = { Zero, Zero };
391 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000392 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000393}
394
Anders Carlsson625bfc82007-07-21 05:21:51 +0000395LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
396 std::string FunctionName(CurFuncDecl->getName());
397 std::string GlobalVarName;
398
399 switch (E->getIdentType()) {
400 default:
401 assert(0 && "unknown pre-defined ident type");
402 case PreDefinedExpr::Func:
403 GlobalVarName = "__func__.";
404 break;
405 case PreDefinedExpr::Function:
406 GlobalVarName = "__FUNCTION__.";
407 break;
408 case PreDefinedExpr::PrettyFunction:
409 // FIXME:: Demangle C++ method names
410 GlobalVarName = "__PRETTY_FUNCTION__.";
411 break;
412 }
413
414 GlobalVarName += CurFuncDecl->getName();
415
416 // FIXME: Can cache/reuse these within the module.
417 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
418
419 // Create a global variable for this.
420 C = new llvm::GlobalVariable(C->getType(), true,
421 llvm::GlobalValue::InternalLinkage,
422 C, GlobalVarName, CurFn->getParent());
423 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
424 llvm::Constant *Zeros[] = { Zero, Zero };
425 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
426 return LValue::MakeAddr(C);
427}
428
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000429LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000430 // The index must always be a pointer or integer, neither of which is an
431 // aggregate. Emit it.
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000432 QualType IdxTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000433 llvm::Value *Idx =
434 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000435
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000436 // If the base is a vector type, then we are forming a vector element lvalue
437 // with this subscript.
438 if (E->getBase()->getType()->isVectorType()) {
439 // Emit the vector as an lvalue to get its address.
440 LValue Base = EmitLValue(E->getBase());
441 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
442 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
443 return LValue::MakeVectorElt(Base.getAddress(), Idx);
444 }
445
446 // At this point, the base must be a pointer or integer, neither of which are
447 // aggregates. Emit it.
448 QualType BaseTy;
449 llvm::Value *Base =
450 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
451
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000452 // Usually the base is the pointer type, but sometimes it is the index.
453 // Canonicalize to have the pointer as the base.
454 if (isa<llvm::PointerType>(Idx->getType())) {
455 std::swap(Base, Idx);
456 std::swap(BaseTy, IdxTy);
457 }
458
459 // The pointer is now the base. Extend or truncate the index type to 32 or
460 // 64-bits.
461 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000462 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000463 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000464 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000465 IdxSigned, "idxprom");
466
467 // We know that the pointer points to a type of the correct size, unless the
468 // size is a VLA.
Chris Lattner0e9d6222007-07-15 23:26:56 +0000469 if (!E->getType()->isConstantSizeType(getContext()))
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000470 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000471 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000472}
473
Chris Lattnere47e4402007-06-01 18:02:12 +0000474//===--------------------------------------------------------------------===//
475// Expression Emission
476//===--------------------------------------------------------------------===//
477
Chris Lattner8394d792007-06-05 20:53:16 +0000478RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000479 assert(E && "Null expression?");
480
481 switch (E->getStmtClass()) {
482 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000483 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000484 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000485 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000486
487 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000488 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000489 // DeclRef's of EnumConstantDecl's are simple rvalues.
490 if (const EnumConstantDecl *EC =
491 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000492 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattner8394d792007-06-05 20:53:16 +0000493 return EmitLoadOfLValue(E);
Chris Lattnera779b3d2007-07-10 21:58:36 +0000494 case Expr::ArraySubscriptExprClass:
495 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Anders Carlsson625bfc82007-07-21 05:21:51 +0000496 case Expr::PreDefinedExprClass:
Chris Lattner4347e3692007-06-06 04:54:52 +0000497 case Expr::StringLiteralClass:
498 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000499
500 // Leaf expressions.
501 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000502 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattner2ada32e2007-07-09 23:03:16 +0000503 case Expr::FloatingLiteralClass:
504 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000505 case Expr::CharacterLiteralClass:
506 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000507
Chris Lattnerd7f58862007-06-02 05:24:33 +0000508 // Operators.
509 case Expr::ParenExprClass:
510 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000511 case Expr::UnaryOperatorClass:
512 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000513 case Expr::SizeOfAlignOfTypeExprClass:
514 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
515 E->getType(),
516 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattner388cf762007-07-13 20:25:53 +0000517 case Expr::ImplicitCastExprClass:
518 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000519 case Expr::CastExprClass:
Chris Lattner388cf762007-07-13 20:25:53 +0000520 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner2b228c92007-06-15 21:34:29 +0000521 case Expr::CallExprClass:
522 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000523 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000524 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000525
526 case Expr::ConditionalOperatorClass:
527 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000528 }
529
530}
531
Chris Lattner8394d792007-06-05 20:53:16 +0000532RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000533 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000534}
Chris Lattner2ada32e2007-07-09 23:03:16 +0000535RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
536 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
537 E->getValue()));
538}
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000539RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
540 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
541 E->getValue()));
542}
Chris Lattnera779b3d2007-07-10 21:58:36 +0000543
544RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
545 // Emit subscript expressions in rvalue context's. For most cases, this just
546 // loads the lvalue formed by the subscript expr. However, we have to be
547 // careful, because the base of a vector subscript is occasionally an rvalue,
548 // so we can't get it as an lvalue.
549 if (!E->getBase()->getType()->isVectorType())
550 return EmitLoadOfLValue(E);
551
552 // Handle the vector case. The base must be a vector, the index must be an
553 // integer value.
554 QualType BaseTy, IdxTy;
555 llvm::Value *Base =
556 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
557 llvm::Value *Idx =
558 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
559
560 // FIXME: Convert Idx to i32 type.
561
562 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
563}
564
Chris Lattner388cf762007-07-13 20:25:53 +0000565// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
566// have to handle a more broad range of conversions than explicit casts, as they
567// handle things like function to ptr-to-function decay etc.
568RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner8394d792007-06-05 20:53:16 +0000569 QualType SrcTy;
Chris Lattner388cf762007-07-13 20:25:53 +0000570 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000571
572 // If the destination is void, just evaluate the source.
Chris Lattner388cf762007-07-13 20:25:53 +0000573 if (DestTy->isVoidType())
Chris Lattner8394d792007-06-05 20:53:16 +0000574 return RValue::getAggregate(0);
575
Chris Lattner388cf762007-07-13 20:25:53 +0000576 return EmitConversion(Src, SrcTy, DestTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000577}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000578
Chris Lattner2b228c92007-06-15 21:34:29 +0000579RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000580 QualType CalleeTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000581 llvm::Value *Callee =
Chris Lattnerc14236b2007-07-10 22:18:37 +0000582 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
583
584 // The callee type will always be a pointer to function type, get the function
585 // type.
586 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
587
588 // Get information about the argument types.
589 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
590
591 // Calling unprototyped functions provides no argument info.
592 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
593 ArgTyIt = FTP->arg_type_begin();
594 ArgTyEnd = FTP->arg_type_end();
595 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000596
Chris Lattner23b7eb62007-06-15 23:05:46 +0000597 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000598
599 // FIXME: Handle struct return.
600 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000601 QualType ArgTy;
602 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
603
604 // If this argument has prototype information, convert it.
605 if (ArgTyIt != ArgTyEnd) {
606 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
607 } else {
608 // Otherwise, if passing through "..." or to a function with no prototype,
609 // perform the "default argument promotions" (C99 6.5.2.2p6), which
610 // includes the usual unary conversions, but also promotes float to
611 // double.
612 if (const BuiltinType *BT =
613 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
614 if (BT->getKind() == BuiltinType::Float)
615 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
616 llvm::Type::DoubleTy,"tmp"));
617 }
618 }
619
Chris Lattner2b228c92007-06-15 21:34:29 +0000620
621 if (ArgVal.isScalar())
622 Args.push_back(ArgVal.getVal());
623 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000624 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000625 }
626
Chris Lattner23b7eb62007-06-15 23:05:46 +0000627 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000628 if (V->getType() != llvm::Type::VoidTy)
629 V->setName("call");
630
631 // FIXME: Struct return;
632 return RValue::get(V);
633}
634
635
Chris Lattner8394d792007-06-05 20:53:16 +0000636//===----------------------------------------------------------------------===//
637// Unary Operator Emission
638//===----------------------------------------------------------------------===//
639
640RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
641 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000642 ResTy = E->getType().getCanonicalType();
643
644 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
645 // Functions are promoted to their address.
646 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000647 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000648 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
649 // C99 6.3.2.1p3
650 ResTy = getContext().getPointerType(ary->getElementType());
651
652 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
653 // will not true when we add support for VLAs.
654 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
655
656 assert(isa<llvm::PointerType>(V->getType()) &&
657 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
658 ->getElementType()) &&
659 "Doesn't support VLAs yet!");
660 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000661 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000662 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
663 // FIXME: this probably isn't right, pending clarification from Steve.
664 llvm::Value *Val = EmitExpr(E).getVal();
665
Chris Lattner6db1fb82007-06-02 22:49:07 +0000666 // If the input is a signed integer, sign extend to the destination.
667 if (ResTy->isSignedIntegerType()) {
668 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
669 } else {
670 // This handles unsigned types, including bool.
671 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
672 }
673 ResTy = getContext().IntTy;
674
Chris Lattner8394d792007-06-05 20:53:16 +0000675 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000676 }
677
678 // Otherwise, this is a float, double, int, struct, etc.
679 return EmitExpr(E);
680}
681
682
Chris Lattner8394d792007-06-05 20:53:16 +0000683RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000684 switch (E->getOpcode()) {
685 default:
686 printf("Unimplemented unary expr!\n");
687 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000688 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerdcca4872007-07-11 23:43:46 +0000689 case UnaryOperator::PostInc:
690 case UnaryOperator::PostDec:
691 case UnaryOperator::PreInc :
692 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
693 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
694 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
695 case UnaryOperator::Plus : return EmitUnaryPlus(E);
696 case UnaryOperator::Minus : return EmitUnaryMinus(E);
697 case UnaryOperator::Not : return EmitUnaryNot(E);
698 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000699 case UnaryOperator::SizeOf :
700 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
701 case UnaryOperator::AlignOf :
702 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Chris Lattner8394d792007-06-05 20:53:16 +0000703 // FIXME: real/imag
704 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000705 }
706}
707
Chris Lattnerdcca4872007-07-11 23:43:46 +0000708RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
709 LValue LV = EmitLValue(E->getSubExpr());
710 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
711
712 // We know the operand is real or pointer type, so it must be an LLVM scalar.
713 assert(InVal.isScalar() && "Unknown thing to increment");
714 llvm::Value *InV = InVal.getVal();
715
716 int AmountVal = 1;
717 if (E->getOpcode() == UnaryOperator::PreDec ||
718 E->getOpcode() == UnaryOperator::PostDec)
719 AmountVal = -1;
720
721 llvm::Value *NextVal;
722 if (isa<llvm::IntegerType>(InV->getType())) {
723 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
724 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
725 } else if (InV->getType()->isFloatingPoint()) {
726 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
727 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
728 } else {
729 // FIXME: This is not right for pointers to VLA types.
730 assert(isa<llvm::PointerType>(InV->getType()));
731 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
732 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
733 }
734
735 RValue NextValToStore = RValue::get(NextVal);
736
737 // Store the updated result through the lvalue.
738 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
739
740 // If this is a postinc, return the value read from memory, otherwise use the
741 // updated value.
742 if (E->getOpcode() == UnaryOperator::PreDec ||
743 E->getOpcode() == UnaryOperator::PreInc)
744 return NextValToStore;
745 else
746 return InVal;
747}
748
Chris Lattner8394d792007-06-05 20:53:16 +0000749/// C99 6.5.3.2
750RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
751 // The address of the operand is just its lvalue. It cannot be a bitfield.
752 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
753}
754
755RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
756 // Unary plus just performs promotions on its arithmetic operand.
757 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000758 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000759}
760
761RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
762 // Unary minus performs promotions, then negates its arithmetic operand.
763 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000764 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000765
Chris Lattner8394d792007-06-05 20:53:16 +0000766 if (V.isScalar())
767 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
768
769 assert(0 && "FIXME: This doesn't handle complex operands yet");
770}
771
772RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
773 // Unary not performs promotions, then complements its integer operand.
774 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000775 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000776
777 if (V.isScalar())
778 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
779
780 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
781}
782
783
784/// C99 6.5.3.3
785RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
786 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000787 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000788
789 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000790 // TODO: Could dynamically modify easy computations here. For example, if
791 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000792 BoolVal = Builder.CreateNot(BoolVal, "lnot");
793
794 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000795 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000796}
797
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000798/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
799/// an integer (RetType).
800RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
801 QualType RetType, bool isSizeOf) {
802 /// FIXME: This doesn't handle VLAs yet!
803 std::pair<uint64_t, unsigned> Info =
804 getContext().getTypeInfo(TypeToSize, SourceLocation());
805
806 uint64_t Val = isSizeOf ? Info.first : Info.second;
807 Val /= 8; // Return size in bytes, not bits.
808
809 assert(RetType->isIntegerType() && "Result type must be an integer!");
810
811 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
812 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
813}
814
Chris Lattnere47e4402007-06-01 18:02:12 +0000815
Chris Lattnerdb91b162007-06-02 00:16:28 +0000816//===--------------------------------------------------------------------===//
817// Binary Operator Emission
818//===--------------------------------------------------------------------===//
819
820// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000821QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000822EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
823 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000824 QualType LHSType, RHSType;
825 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
826 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
827
Chris Lattnercf250242007-06-03 02:02:44 +0000828 // If both operands have the same source type, we're done already.
829 if (LHSType == RHSType) return LHSType;
830
831 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
832 // The caller can deal with this (e.g. pointer + int).
833 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
834 return LHSType;
835
836 // At this point, we have two different arithmetic types.
837
838 // Handle complex types first (C99 6.3.1.8p1).
839 if (LHSType->isComplexType() || RHSType->isComplexType()) {
840 assert(0 && "FIXME: complex types unimp");
841#if 0
842 // if we have an integer operand, the result is the complex type.
843 if (rhs->isIntegerType())
844 return lhs;
845 if (lhs->isIntegerType())
846 return rhs;
847 return Context.maxComplexType(lhs, rhs);
848#endif
849 }
850
851 // If neither operand is complex, they must be scalars.
852 llvm::Value *LHSV = LHS.getVal();
853 llvm::Value *RHSV = RHS.getVal();
854
855 // If the LLVM types are already equal, then they only differed in sign, or it
856 // was something like char/signed char or double/long double.
857 if (LHSV->getType() == RHSV->getType())
858 return LHSType;
859
860 // Now handle "real" floating types (i.e. float, double, long double).
861 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
862 // if we have an integer operand, the result is the real floating type, and
863 // the integer converts to FP.
864 if (RHSType->isIntegerType()) {
865 // Promote the RHS to an FP type of the LHS, with the sign following the
866 // RHS.
867 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000868 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000869 else
Chris Lattner8394d792007-06-05 20:53:16 +0000870 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000871 return LHSType;
872 }
873
874 if (LHSType->isIntegerType()) {
875 // Promote the LHS to an FP type of the RHS, with the sign following the
876 // LHS.
877 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000878 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000879 else
Chris Lattner8394d792007-06-05 20:53:16 +0000880 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000881 return RHSType;
882 }
883
884 // Otherwise, they are two FP types. Promote the smaller operand to the
885 // bigger result.
886 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
887
888 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000889 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000890 else
Chris Lattner8394d792007-06-05 20:53:16 +0000891 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000892 return BiggerType;
893 }
894
895 // Finally, we have two integer types that are different according to C. Do
896 // a sign or zero extension if needed.
897
898 // Otherwise, one type is smaller than the other.
899 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
900
901 if (LHSType == ResTy) {
902 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000903 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000904 else
Chris Lattner8394d792007-06-05 20:53:16 +0000905 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000906 } else {
907 assert(RHSType == ResTy && "Unknown conversion");
908 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000909 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000910 else
Chris Lattner8394d792007-06-05 20:53:16 +0000911 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000912 }
913 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000914}
915
Chris Lattnercd215f02007-06-29 16:52:55 +0000916/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
917/// are strange in that the result of the operation is not the same type as the
918/// intermediate computation. This function emits the LHS and RHS operands of
919/// the compound assignment, promoting them to their common computation type.
920///
921/// Since the LHS is an lvalue, and the result is stored back through it, we
922/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
923/// RHS values are both in the computation type for the operator.
924void CodeGenFunction::
925EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
926 LValue &LHSLV, RValue &LHS, RValue &RHS) {
927 LHSLV = EmitLValue(E->getLHS());
928
929 // Load the LHS and RHS operands.
930 QualType LHSTy = E->getLHS()->getType();
931 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
932 QualType RHSTy;
933 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
934
Chris Lattner47c247e2007-06-29 17:26:27 +0000935 // Shift operands do the usual unary conversions, but do not do the binary
936 // conversions.
937 if (E->isShiftAssignOp()) {
938 // FIXME: This is broken. Implicit conversions should be made explicit,
939 // so that this goes away. This causes us to reload the LHS.
940 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
941 }
942
Chris Lattnercd215f02007-06-29 16:52:55 +0000943 // Convert the LHS and RHS to the common evaluation type.
944 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
945 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
946}
947
948/// EmitCompoundAssignmentResult - Given a result value in the computation type,
949/// truncate it down to the actual result type, store it through the LHS lvalue,
950/// and return it.
951RValue CodeGenFunction::
952EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
953 LValue LHSLV, RValue ResV) {
954
955 // Truncate back to the destination type.
956 if (E->getComputationType() != E->getType())
957 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
958
959 // Store the result value into the LHS.
960 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
961
962 // Return the result.
963 return ResV;
964}
965
Chris Lattnerdb91b162007-06-02 00:16:28 +0000966
Chris Lattner8394d792007-06-05 20:53:16 +0000967RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000968 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000969 switch (E->getOpcode()) {
970 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000971 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000972 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000973 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerb25a9432007-06-29 17:03:06 +0000974 case BinaryOperator::Mul:
975 EmitUsualArithmeticConversions(E, LHS, RHS);
976 return EmitMul(LHS, RHS, E->getType());
977 case BinaryOperator::Div:
978 EmitUsualArithmeticConversions(E, LHS, RHS);
979 return EmitDiv(LHS, RHS, E->getType());
980 case BinaryOperator::Rem:
981 EmitUsualArithmeticConversions(E, LHS, RHS);
982 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000983 case BinaryOperator::Add: {
984 QualType ExprTy = E->getType();
985 if (ExprTy->isPointerType()) {
986 Expr *LHSExpr = E->getLHS();
987 QualType LHSTy;
988 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
989 Expr *RHSExpr = E->getRHS();
990 QualType RHSTy;
991 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
992 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
993 } else {
994 EmitUsualArithmeticConversions(E, LHS, RHS);
995 return EmitAdd(LHS, RHS, ExprTy);
996 }
997 }
998 case BinaryOperator::Sub: {
999 QualType ExprTy = E->getType();
1000 Expr *LHSExpr = E->getLHS();
1001 if (LHSExpr->getType()->isPointerType()) {
1002 QualType LHSTy;
1003 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1004 Expr *RHSExpr = E->getRHS();
1005 QualType RHSTy;
1006 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1007 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
1008 } else {
1009 EmitUsualArithmeticConversions(E, LHS, RHS);
1010 return EmitSub(LHS, RHS, ExprTy);
1011 }
1012 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001013 case BinaryOperator::Shl:
1014 EmitShiftOperands(E, LHS, RHS);
1015 return EmitShl(LHS, RHS, E->getType());
1016 case BinaryOperator::Shr:
1017 EmitShiftOperands(E, LHS, RHS);
1018 return EmitShr(LHS, RHS, E->getType());
Chris Lattnerb25a9432007-06-29 17:03:06 +00001019 case BinaryOperator::And:
1020 EmitUsualArithmeticConversions(E, LHS, RHS);
1021 return EmitAnd(LHS, RHS, E->getType());
1022 case BinaryOperator::Xor:
1023 EmitUsualArithmeticConversions(E, LHS, RHS);
1024 return EmitXor(LHS, RHS, E->getType());
1025 case BinaryOperator::Or :
1026 EmitUsualArithmeticConversions(E, LHS, RHS);
1027 return EmitOr(LHS, RHS, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001028 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1029 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +00001030 case BinaryOperator::LT:
1031 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1032 llvm::ICmpInst::ICMP_SLT,
1033 llvm::FCmpInst::FCMP_OLT);
1034 case BinaryOperator::GT:
1035 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1036 llvm::ICmpInst::ICMP_SGT,
1037 llvm::FCmpInst::FCMP_OGT);
1038 case BinaryOperator::LE:
1039 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1040 llvm::ICmpInst::ICMP_SLE,
1041 llvm::FCmpInst::FCMP_OLE);
1042 case BinaryOperator::GE:
1043 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1044 llvm::ICmpInst::ICMP_SGE,
1045 llvm::FCmpInst::FCMP_OGE);
1046 case BinaryOperator::EQ:
1047 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1048 llvm::ICmpInst::ICMP_EQ,
1049 llvm::FCmpInst::FCMP_OEQ);
1050 case BinaryOperator::NE:
1051 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1052 llvm::ICmpInst::ICMP_NE,
1053 llvm::FCmpInst::FCMP_UNE);
Chris Lattnercd215f02007-06-29 16:52:55 +00001054 case BinaryOperator::Assign:
1055 return EmitBinaryAssign(E);
1056
Chris Lattnerb25a9432007-06-29 17:03:06 +00001057 case BinaryOperator::MulAssign: {
1058 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1059 LValue LHSLV;
1060 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1061 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1062 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1063 }
1064 case BinaryOperator::DivAssign: {
1065 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1066 LValue LHSLV;
1067 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1068 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1069 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1070 }
1071 case BinaryOperator::RemAssign: {
1072 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1073 LValue LHSLV;
1074 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1075 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1076 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1077 }
Chris Lattnercd215f02007-06-29 16:52:55 +00001078 case BinaryOperator::AddAssign: {
1079 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1080 LValue LHSLV;
1081 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1082 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1083 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1084 }
1085 case BinaryOperator::SubAssign: {
1086 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1087 LValue LHSLV;
1088 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1089 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1090 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1091 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001092 case BinaryOperator::ShlAssign: {
1093 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1094 LValue LHSLV;
1095 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1096 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1097 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1098 }
1099 case BinaryOperator::ShrAssign: {
1100 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1101 LValue LHSLV;
1102 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1103 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1104 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1105 }
Chris Lattnerb25a9432007-06-29 17:03:06 +00001106 case BinaryOperator::AndAssign: {
1107 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1108 LValue LHSLV;
1109 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1110 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1111 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1112 }
1113 case BinaryOperator::OrAssign: {
1114 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1115 LValue LHSLV;
1116 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1117 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1118 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1119 }
1120 case BinaryOperator::XorAssign: {
1121 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1122 LValue LHSLV;
1123 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1124 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1125 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1126 }
Chris Lattner8394d792007-06-05 20:53:16 +00001127 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +00001128 }
1129}
1130
Chris Lattnerb25a9432007-06-29 17:03:06 +00001131RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001132 if (LHS.isScalar())
1133 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1134
Gabor Greifd4606aa2007-07-13 23:33:18 +00001135 // Otherwise, this must be a complex number.
1136 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1137
1138 EmitLoadOfComplex(LHS, LHSR, LHSI);
1139 EmitLoadOfComplex(RHS, RHSR, RHSI);
1140
1141 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1142 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1143 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1144
1145 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1146 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1147 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1148
1149 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1150 EmitStoreOfComplex(ResR, ResI, Res);
1151 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001152}
1153
Chris Lattnerb25a9432007-06-29 17:03:06 +00001154RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001155 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001156 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001157 if (LHS.getVal()->getType()->isFloatingPoint())
1158 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
Chris Lattnerb25a9432007-06-29 17:03:06 +00001159 else if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001160 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1161 else
1162 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1163 return RValue::get(RV);
1164 }
1165 assert(0 && "FIXME: This doesn't handle complex operands yet");
1166}
1167
Chris Lattnerb25a9432007-06-29 17:03:06 +00001168RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001169 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001170 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001171 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattnerb25a9432007-06-29 17:03:06 +00001172 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001173 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1174 else
1175 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1176 return RValue::get(RV);
1177 }
1178
1179 assert(0 && "FIXME: This doesn't handle complex operands yet");
1180}
1181
Chris Lattnercd215f02007-06-29 16:52:55 +00001182RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001183 if (LHS.isScalar())
1184 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattnercd215f02007-06-29 16:52:55 +00001185
Chris Lattnere9a64532007-06-22 21:44:33 +00001186 // Otherwise, this must be a complex number.
1187 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1188
1189 EmitLoadOfComplex(LHS, LHSR, LHSI);
1190 EmitLoadOfComplex(RHS, RHSR, RHSI);
1191
1192 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1193 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1194
Chris Lattnercd215f02007-06-29 16:52:55 +00001195 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
Chris Lattnere9a64532007-06-22 21:44:33 +00001196 EmitStoreOfComplex(ResR, ResI, Res);
1197 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001198}
1199
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001200RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1201 RValue RHS, QualType RHSTy,
1202 QualType ResTy) {
1203 llvm::Value *LHSValue = LHS.getVal();
1204 llvm::Value *RHSValue = RHS.getVal();
1205 if (LHSTy->isPointerType()) {
1206 // pointer + int
1207 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1208 } else {
1209 // int + pointer
1210 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1211 }
1212}
1213
Chris Lattnercd215f02007-06-29 16:52:55 +00001214RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001215 if (LHS.isScalar())
1216 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1217
1218 assert(0 && "FIXME: This doesn't handle complex operands yet");
Chris Lattner8394d792007-06-05 20:53:16 +00001219}
1220
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001221RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1222 RValue RHS, QualType RHSTy,
1223 QualType ResTy) {
1224 llvm::Value *LHSValue = LHS.getVal();
1225 llvm::Value *RHSValue = RHS.getVal();
1226 if (const PointerType *RHSPtrType =
1227 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1228 // pointer - pointer
1229 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1230 QualType LHSElementType = LHSPtrType->getPointeeType();
1231 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1232 "can't subtract pointers with differing element types");
Chris Lattner651f0e92007-07-16 05:43:05 +00001233 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattner4481b422007-07-14 01:29:45 +00001234 SourceLocation()) / 8;
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001235 const llvm::Type *ResultType = ConvertType(ResTy);
1236 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1237 "sub.ptr.lhs.cast");
1238 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1239 "sub.ptr.rhs.cast");
1240 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1241 "sub.ptr.sub");
Chris Lattner651f0e92007-07-16 05:43:05 +00001242
1243 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1244 // remainder. As such, we handle common power-of-two cases here to generate
1245 // better code.
1246 if (llvm::isPowerOf2_64(ElementSize)) {
1247 llvm::Value *ShAmt =
1248 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1249 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1250 } else {
1251 // Otherwise, do a full sdiv.
1252 llvm::Value *BytesPerElement =
1253 llvm::ConstantInt::get(ResultType, ElementSize);
1254 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1255 "sub.ptr.div"));
1256 }
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001257 } else {
1258 // pointer - int
1259 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1260 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1261 }
1262}
1263
Chris Lattner47c247e2007-06-29 17:26:27 +00001264void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1265 RValue &LHS, RValue &RHS) {
Chris Lattner8394d792007-06-05 20:53:16 +00001266 // For shifts, integer promotions are performed, but the usual arithmetic
1267 // conversions are not. The LHS and RHS need not have the same type.
Chris Lattner8394d792007-06-05 20:53:16 +00001268 QualType ResTy;
Chris Lattner47c247e2007-06-29 17:26:27 +00001269 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1270 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1271}
Chris Lattner8394d792007-06-05 20:53:16 +00001272
Chris Lattner47c247e2007-06-29 17:26:27 +00001273
1274RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1275 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1276
Chris Lattner8394d792007-06-05 20:53:16 +00001277 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1278 // RHS to the same size as the LHS.
1279 if (LHS->getType() != RHS->getType())
1280 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1281
1282 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1283}
1284
Chris Lattner47c247e2007-06-29 17:26:27 +00001285RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1286 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
Chris Lattner8394d792007-06-05 20:53:16 +00001287
1288 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1289 // RHS to the same size as the LHS.
1290 if (LHS->getType() != RHS->getType())
1291 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1292
Chris Lattner47c247e2007-06-29 17:26:27 +00001293 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001294 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1295 else
1296 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1297}
1298
Chris Lattner1fde0b32007-06-20 18:30:55 +00001299RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1300 unsigned UICmpOpc, unsigned SICmpOpc,
1301 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +00001302 RValue LHS, RHS;
1303 EmitUsualArithmeticConversions(E, LHS, RHS);
1304
1305 llvm::Value *Result;
1306 if (LHS.isScalar()) {
1307 if (LHS.getVal()->getType()->isFloatingPoint()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001308 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1309 LHS.getVal(), RHS.getVal(), "cmp");
1310 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1311 // FIXME: This check isn't right for "unsigned short < int" where ushort
1312 // promotes to int and does a signed compare.
1313 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1314 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001315 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001316 // Signed integers and pointers.
1317 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1318 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001319 }
1320 } else {
1321 // Struct/union/complex
Gabor Greifd4606aa2007-07-13 23:33:18 +00001322 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1323 EmitLoadOfComplex(LHS, LHSR, LHSI);
1324 EmitLoadOfComplex(RHS, RHSR, RHSI);
1325
Gabor Greife97cd7e2007-07-14 20:05:18 +00001326 // FIXME: need to consider _Complex over integers too!
1327
Gabor Greifd4606aa2007-07-13 23:33:18 +00001328 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1329 LHSR, RHSR, "cmp.r");
1330 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1331 LHSI, RHSI, "cmp.i");
1332 if (BinaryOperator::EQ == E->getOpcode()) {
1333 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1334 } else if (BinaryOperator::NE == E->getOpcode()) {
1335 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1336 } else {
1337 assert(0 && "Complex comparison other than == or != ?");
1338 }
Chris Lattner273c63d2007-06-20 18:02:30 +00001339 }
Gabor Greifd4606aa2007-07-13 23:33:18 +00001340
Chris Lattner273c63d2007-06-20 18:02:30 +00001341 // ZExt result to int.
1342 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1343}
1344
Chris Lattnerb25a9432007-06-29 17:03:06 +00001345RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001346 if (LHS.isScalar())
1347 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1348
1349 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1350}
1351
Chris Lattnerb25a9432007-06-29 17:03:06 +00001352RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001353 if (LHS.isScalar())
1354 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1355
1356 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1357}
1358
Chris Lattnerb25a9432007-06-29 17:03:06 +00001359RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001360 if (LHS.isScalar())
1361 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1362
1363 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1364}
1365
1366RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001367 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001368
Chris Lattner23b7eb62007-06-15 23:05:46 +00001369 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1370 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001371
Chris Lattner23b7eb62007-06-15 23:05:46 +00001372 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001373 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1374
1375 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001376 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001377
1378 // Reaquire the RHS block, as there may be subblocks inserted.
1379 RHSBlock = Builder.GetInsertBlock();
1380 EmitBlock(ContBlock);
1381
1382 // Create a PHI node. If we just evaluted the LHS condition, the result is
1383 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001384 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +00001385 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001386 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001387 PN->addIncoming(RHSCond, RHSBlock);
1388
1389 // ZExt result to int.
1390 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1391}
1392
1393RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001394 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001395
Chris Lattner23b7eb62007-06-15 23:05:46 +00001396 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1397 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001398
Chris Lattner23b7eb62007-06-15 23:05:46 +00001399 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001400 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1401
1402 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001403 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001404
1405 // Reaquire the RHS block, as there may be subblocks inserted.
1406 RHSBlock = Builder.GetInsertBlock();
1407 EmitBlock(ContBlock);
1408
1409 // Create a PHI node. If we just evaluted the LHS condition, the result is
1410 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001411 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +00001412 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001413 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001414 PN->addIncoming(RHSCond, RHSBlock);
1415
1416 // ZExt result to int.
1417 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1418}
1419
1420RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1421 LValue LHS = EmitLValue(E->getLHS());
1422
1423 QualType RHSTy;
1424 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1425
1426 // Convert the RHS to the type of the LHS.
Chris Lattnerf033c142007-06-22 19:05:19 +00001427 RHS = EmitConversion(RHS, RHSTy, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001428
1429 // Store the value into the LHS.
1430 EmitStoreThroughLValue(RHS, LHS, E->getType());
1431
1432 // Return the converted RHS.
1433 return RHS;
1434}
1435
Chris Lattner9369a562007-06-29 16:31:29 +00001436
Chris Lattner8394d792007-06-05 20:53:16 +00001437RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1438 EmitExpr(E->getLHS());
1439 return EmitExpr(E->getRHS());
1440}
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001441
1442RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1443 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1444 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1445 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1446
1447 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1448 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1449
Chris Lattner027f21d2007-07-14 00:01:01 +00001450 // FIXME: Implement this for aggregate values.
1451
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001452 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1453 // that's not possible with the current design.
1454
1455 EmitBlock(LHSBlock);
1456 QualType LHSTy;
1457 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1458 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1459 Cond;
1460 Builder.CreateBr(ContBlock);
1461 LHSBlock = Builder.GetInsertBlock();
1462
1463 EmitBlock(RHSBlock);
1464 QualType RHSTy;
1465 llvm::Value *RHSValue =
1466 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1467 Builder.CreateBr(ContBlock);
1468 RHSBlock = Builder.GetInsertBlock();
1469
1470 const llvm::Type *LHSType = LHSValue->getType();
1471 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1472
1473 EmitBlock(ContBlock);
1474 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1475 PN->reserveOperandSpace(2);
1476 PN->addIncoming(LHSValue, LHSBlock);
1477 PN->addIncoming(RHSValue, RHSBlock);
1478
1479 return RValue::get(PN);
1480}