blob: 1a841f9d81d0fbdfb497b76fe1d973669a814a89 [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 Lattner9e751ca2007-08-02 23:37:31 +0000256 case Expr::OCUVectorComponentClass:
257 return EmitOCUVectorComponentExpr(cast<OCUVectorComponent>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000258 }
259}
260
Chris Lattner8394d792007-06-05 20:53:16 +0000261/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
262/// this method emits the address of the lvalue, then loads the result as an
263/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000264RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
265 ExprType = ExprType.getCanonicalType();
Chris Lattner8394d792007-06-05 20:53:16 +0000266
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000267 if (LV.isSimple()) {
268 llvm::Value *Ptr = LV.getAddress();
269 const llvm::Type *EltTy =
270 cast<llvm::PointerType>(Ptr->getType())->getElementType();
271
272 // Simple scalar l-value.
273 if (EltTy->isFirstClassType())
274 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
275
276 // Otherwise, we have an aggregate lvalue.
277 return RValue::getAggregate(Ptr);
278 }
Chris Lattner09153c02007-06-22 18:48:09 +0000279
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000280 if (LV.isVectorElt()) {
281 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
282 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
283 "vecext"));
284 }
Chris Lattner09153c02007-06-22 18:48:09 +0000285
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000286 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000287}
288
Chris Lattner9369a562007-06-29 16:31:29 +0000289RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
290 return EmitLoadOfLValue(EmitLValue(E), E->getType());
291}
292
293
Chris Lattner8394d792007-06-05 20:53:16 +0000294/// EmitStoreThroughLValue - Store the specified rvalue into the specified
295/// lvalue, where both are guaranteed to the have the same type, and that type
296/// is 'Ty'.
297void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
298 QualType Ty) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000299 if (Dst.isVectorElt()) {
300 // Read/modify/write the vector, inserting the new element.
301 // FIXME: Volatility.
302 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
303 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
304 Dst.getVectorIdx(), "vecins");
305 Builder.CreateStore(Vec, Dst.getVectorAddr());
306 return;
307 }
308
309 assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
Chris Lattner8394d792007-06-05 20:53:16 +0000310
Chris Lattner09153c02007-06-22 18:48:09 +0000311 llvm::Value *DstAddr = Dst.getAddress();
312 if (Src.isScalar()) {
313 // FIXME: Handle volatility etc.
314 const llvm::Type *SrcTy = Src.getVal()->getType();
315 const llvm::Type *AddrTy =
316 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
317
318 if (AddrTy != SrcTy)
319 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
320 "storetmp");
321 Builder.CreateStore(Src.getVal(), DstAddr);
322 return;
323 }
Chris Lattner8394d792007-06-05 20:53:16 +0000324
Chris Lattnere9a64532007-06-22 21:44:33 +0000325 // Don't use memcpy for complex numbers.
326 if (Ty->isComplexType()) {
327 llvm::Value *Real, *Imag;
328 EmitLoadOfComplex(Src, Real, Imag);
329 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
330 return;
331 }
332
Chris Lattner09153c02007-06-22 18:48:09 +0000333 // Aggregate assignment turns into llvm.memcpy.
334 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
335 llvm::Value *SrcAddr = Src.getAggregateAddr();
336
337 if (DstAddr->getType() != SBP)
338 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
339 if (SrcAddr->getType() != SBP)
340 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
341
342 unsigned Align = 1; // FIXME: Compute type alignments.
343 unsigned Size = 1234; // FIXME: Compute type sizes.
344
345 // FIXME: Handle variable sized types.
346 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
347 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
348
349 llvm::Value *MemCpyOps[4] = {
350 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
351 };
352
Chris Lattner7b9f04e2007-08-01 06:24:52 +0000353 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
Chris Lattner8394d792007-06-05 20:53:16 +0000354}
355
Chris Lattnerd7f58862007-06-02 05:24:33 +0000356
357LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
358 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000359 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000360 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000361 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000362 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000363 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000364 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000365 }
366 assert(0 && "Unimp declref");
367}
Chris Lattnere47e4402007-06-01 18:02:12 +0000368
Chris Lattner8394d792007-06-05 20:53:16 +0000369LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
370 // __extension__ doesn't affect lvalue-ness.
371 if (E->getOpcode() == UnaryOperator::Extension)
372 return EmitLValue(E->getSubExpr());
373
374 assert(E->getOpcode() == UnaryOperator::Deref &&
375 "'*' is the only unary operator that produces an lvalue");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000376 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
Chris Lattner8394d792007-06-05 20:53:16 +0000377}
378
Chris Lattner4347e3692007-06-06 04:54:52 +0000379LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
380 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
381 const char *StrData = E->getStrData();
382 unsigned Len = E->getByteLength();
383
384 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000385 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000386
387 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000388 C = new llvm::GlobalVariable(C->getType(), true,
389 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000390 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000391 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
392 llvm::Constant *Zeros[] = { Zero, Zero };
393 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000394 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000395}
396
Anders Carlsson625bfc82007-07-21 05:21:51 +0000397LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
398 std::string FunctionName(CurFuncDecl->getName());
399 std::string GlobalVarName;
400
401 switch (E->getIdentType()) {
402 default:
403 assert(0 && "unknown pre-defined ident type");
404 case PreDefinedExpr::Func:
405 GlobalVarName = "__func__.";
406 break;
407 case PreDefinedExpr::Function:
408 GlobalVarName = "__FUNCTION__.";
409 break;
410 case PreDefinedExpr::PrettyFunction:
411 // FIXME:: Demangle C++ method names
412 GlobalVarName = "__PRETTY_FUNCTION__.";
413 break;
414 }
415
416 GlobalVarName += CurFuncDecl->getName();
417
418 // FIXME: Can cache/reuse these within the module.
419 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
420
421 // Create a global variable for this.
422 C = new llvm::GlobalVariable(C->getType(), true,
423 llvm::GlobalValue::InternalLinkage,
424 C, GlobalVarName, CurFn->getParent());
425 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
426 llvm::Constant *Zeros[] = { Zero, Zero };
427 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
428 return LValue::MakeAddr(C);
429}
430
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000431LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000432 // The index must always be a pointer or integer, neither of which is an
433 // aggregate. Emit it.
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000434 QualType IdxTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000435 llvm::Value *Idx =
436 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000437
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000438 // If the base is a vector type, then we are forming a vector element lvalue
439 // with this subscript.
440 if (E->getBase()->getType()->isVectorType()) {
441 // Emit the vector as an lvalue to get its address.
442 LValue Base = EmitLValue(E->getBase());
443 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
444 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
445 return LValue::MakeVectorElt(Base.getAddress(), Idx);
446 }
447
448 // At this point, the base must be a pointer or integer, neither of which are
449 // aggregates. Emit it.
450 QualType BaseTy;
451 llvm::Value *Base =
452 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
453
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000454 // Usually the base is the pointer type, but sometimes it is the index.
455 // Canonicalize to have the pointer as the base.
456 if (isa<llvm::PointerType>(Idx->getType())) {
457 std::swap(Base, Idx);
458 std::swap(BaseTy, IdxTy);
459 }
460
461 // The pointer is now the base. Extend or truncate the index type to 32 or
462 // 64-bits.
463 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000464 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000465 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000466 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000467 IdxSigned, "idxprom");
468
469 // We know that the pointer points to a type of the correct size, unless the
470 // size is a VLA.
Chris Lattner0e9d6222007-07-15 23:26:56 +0000471 if (!E->getType()->isConstantSizeType(getContext()))
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000472 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000473 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000474}
475
Chris Lattner9e751ca2007-08-02 23:37:31 +0000476LValue CodeGenFunction::
477EmitOCUVectorComponentExpr(const OCUVectorComponent *E) {
478 // Emit the base vector as an l-value.
479 LValue Base = EmitLValue(E->getBase());
480 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
481
482 return LValue::MakeOCUVectorComp(Base.getAddress(),
483 E->getEncodedElementAccess());
484}
485
Chris Lattnere47e4402007-06-01 18:02:12 +0000486//===--------------------------------------------------------------------===//
487// Expression Emission
488//===--------------------------------------------------------------------===//
489
Chris Lattner8394d792007-06-05 20:53:16 +0000490RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000491 assert(E && "Null expression?");
492
493 switch (E->getStmtClass()) {
494 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000495 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000496 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000497 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000498
499 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000500 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000501 // DeclRef's of EnumConstantDecl's are simple rvalues.
502 if (const EnumConstantDecl *EC =
503 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000504 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattner8394d792007-06-05 20:53:16 +0000505 return EmitLoadOfLValue(E);
Chris Lattnera779b3d2007-07-10 21:58:36 +0000506 case Expr::ArraySubscriptExprClass:
507 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Anders Carlsson625bfc82007-07-21 05:21:51 +0000508 case Expr::PreDefinedExprClass:
Chris Lattner4347e3692007-06-06 04:54:52 +0000509 case Expr::StringLiteralClass:
510 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000511
512 // Leaf expressions.
513 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000514 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattner2ada32e2007-07-09 23:03:16 +0000515 case Expr::FloatingLiteralClass:
516 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000517 case Expr::CharacterLiteralClass:
518 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000519
Chris Lattnerd7f58862007-06-02 05:24:33 +0000520 // Operators.
521 case Expr::ParenExprClass:
522 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000523 case Expr::UnaryOperatorClass:
524 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000525 case Expr::SizeOfAlignOfTypeExprClass:
526 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
527 E->getType(),
528 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattner388cf762007-07-13 20:25:53 +0000529 case Expr::ImplicitCastExprClass:
530 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000531 case Expr::CastExprClass:
Chris Lattner388cf762007-07-13 20:25:53 +0000532 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner2b228c92007-06-15 21:34:29 +0000533 case Expr::CallExprClass:
534 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000535 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000536 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000537
538 case Expr::ConditionalOperatorClass:
539 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000540 }
541
542}
543
Chris Lattner8394d792007-06-05 20:53:16 +0000544RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000545 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000546}
Chris Lattner2ada32e2007-07-09 23:03:16 +0000547RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
548 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
549 E->getValue()));
550}
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000551RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
552 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
553 E->getValue()));
554}
Chris Lattnera779b3d2007-07-10 21:58:36 +0000555
556RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
557 // Emit subscript expressions in rvalue context's. For most cases, this just
558 // loads the lvalue formed by the subscript expr. However, we have to be
559 // careful, because the base of a vector subscript is occasionally an rvalue,
560 // so we can't get it as an lvalue.
561 if (!E->getBase()->getType()->isVectorType())
562 return EmitLoadOfLValue(E);
563
564 // Handle the vector case. The base must be a vector, the index must be an
565 // integer value.
566 QualType BaseTy, IdxTy;
567 llvm::Value *Base =
568 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
569 llvm::Value *Idx =
570 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
571
572 // FIXME: Convert Idx to i32 type.
573
574 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
575}
576
Chris Lattner388cf762007-07-13 20:25:53 +0000577// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
578// have to handle a more broad range of conversions than explicit casts, as they
579// handle things like function to ptr-to-function decay etc.
580RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner8394d792007-06-05 20:53:16 +0000581 QualType SrcTy;
Chris Lattner388cf762007-07-13 20:25:53 +0000582 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000583
584 // If the destination is void, just evaluate the source.
Chris Lattner388cf762007-07-13 20:25:53 +0000585 if (DestTy->isVoidType())
Chris Lattner8394d792007-06-05 20:53:16 +0000586 return RValue::getAggregate(0);
587
Chris Lattner388cf762007-07-13 20:25:53 +0000588 return EmitConversion(Src, SrcTy, DestTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000589}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000590
Chris Lattner2b228c92007-06-15 21:34:29 +0000591RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000592 QualType CalleeTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000593 llvm::Value *Callee =
Chris Lattnerc14236b2007-07-10 22:18:37 +0000594 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
595
596 // The callee type will always be a pointer to function type, get the function
597 // type.
598 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
599
600 // Get information about the argument types.
601 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
602
603 // Calling unprototyped functions provides no argument info.
604 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
605 ArgTyIt = FTP->arg_type_begin();
606 ArgTyEnd = FTP->arg_type_end();
607 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000608
Chris Lattner23b7eb62007-06-15 23:05:46 +0000609 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000610
611 // FIXME: Handle struct return.
612 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000613 QualType ArgTy;
614 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
615
616 // If this argument has prototype information, convert it.
617 if (ArgTyIt != ArgTyEnd) {
618 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
619 } else {
620 // Otherwise, if passing through "..." or to a function with no prototype,
621 // perform the "default argument promotions" (C99 6.5.2.2p6), which
622 // includes the usual unary conversions, but also promotes float to
623 // double.
624 if (const BuiltinType *BT =
625 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
626 if (BT->getKind() == BuiltinType::Float)
627 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
628 llvm::Type::DoubleTy,"tmp"));
629 }
630 }
631
Chris Lattner2b228c92007-06-15 21:34:29 +0000632
633 if (ArgVal.isScalar())
634 Args.push_back(ArgVal.getVal());
635 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000636 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000637 }
638
Chris Lattner7b9f04e2007-08-01 06:24:52 +0000639 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000640 if (V->getType() != llvm::Type::VoidTy)
641 V->setName("call");
642
643 // FIXME: Struct return;
644 return RValue::get(V);
645}
646
647
Chris Lattner8394d792007-06-05 20:53:16 +0000648//===----------------------------------------------------------------------===//
649// Unary Operator Emission
650//===----------------------------------------------------------------------===//
651
652RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
653 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000654 ResTy = E->getType().getCanonicalType();
655
656 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
657 // Functions are promoted to their address.
658 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000659 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000660 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
661 // C99 6.3.2.1p3
662 ResTy = getContext().getPointerType(ary->getElementType());
663
664 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
665 // will not true when we add support for VLAs.
666 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
667
668 assert(isa<llvm::PointerType>(V->getType()) &&
669 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
670 ->getElementType()) &&
671 "Doesn't support VLAs yet!");
672 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000673 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000674 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
675 // FIXME: this probably isn't right, pending clarification from Steve.
676 llvm::Value *Val = EmitExpr(E).getVal();
677
Chris Lattner6db1fb82007-06-02 22:49:07 +0000678 // If the input is a signed integer, sign extend to the destination.
679 if (ResTy->isSignedIntegerType()) {
680 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
681 } else {
682 // This handles unsigned types, including bool.
683 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
684 }
685 ResTy = getContext().IntTy;
686
Chris Lattner8394d792007-06-05 20:53:16 +0000687 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000688 }
689
690 // Otherwise, this is a float, double, int, struct, etc.
691 return EmitExpr(E);
692}
693
694
Chris Lattner8394d792007-06-05 20:53:16 +0000695RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000696 switch (E->getOpcode()) {
697 default:
698 printf("Unimplemented unary expr!\n");
699 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000700 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerdcca4872007-07-11 23:43:46 +0000701 case UnaryOperator::PostInc:
702 case UnaryOperator::PostDec:
703 case UnaryOperator::PreInc :
704 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
705 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
706 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
707 case UnaryOperator::Plus : return EmitUnaryPlus(E);
708 case UnaryOperator::Minus : return EmitUnaryMinus(E);
709 case UnaryOperator::Not : return EmitUnaryNot(E);
710 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000711 case UnaryOperator::SizeOf :
712 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
713 case UnaryOperator::AlignOf :
714 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Chris Lattner8394d792007-06-05 20:53:16 +0000715 // FIXME: real/imag
716 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000717 }
718}
719
Chris Lattnerdcca4872007-07-11 23:43:46 +0000720RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
721 LValue LV = EmitLValue(E->getSubExpr());
722 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
723
724 // We know the operand is real or pointer type, so it must be an LLVM scalar.
725 assert(InVal.isScalar() && "Unknown thing to increment");
726 llvm::Value *InV = InVal.getVal();
727
728 int AmountVal = 1;
729 if (E->getOpcode() == UnaryOperator::PreDec ||
730 E->getOpcode() == UnaryOperator::PostDec)
731 AmountVal = -1;
732
733 llvm::Value *NextVal;
734 if (isa<llvm::IntegerType>(InV->getType())) {
735 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
736 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
737 } else if (InV->getType()->isFloatingPoint()) {
738 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
739 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
740 } else {
741 // FIXME: This is not right for pointers to VLA types.
742 assert(isa<llvm::PointerType>(InV->getType()));
743 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
744 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
745 }
746
747 RValue NextValToStore = RValue::get(NextVal);
748
749 // Store the updated result through the lvalue.
750 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
751
752 // If this is a postinc, return the value read from memory, otherwise use the
753 // updated value.
754 if (E->getOpcode() == UnaryOperator::PreDec ||
755 E->getOpcode() == UnaryOperator::PreInc)
756 return NextValToStore;
757 else
758 return InVal;
759}
760
Chris Lattner8394d792007-06-05 20:53:16 +0000761/// C99 6.5.3.2
762RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
763 // The address of the operand is just its lvalue. It cannot be a bitfield.
764 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
765}
766
767RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
768 // Unary plus just performs promotions on its arithmetic operand.
769 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000770 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000771}
772
773RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
774 // Unary minus performs promotions, then negates its arithmetic operand.
775 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000776 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000777
Chris Lattner8394d792007-06-05 20:53:16 +0000778 if (V.isScalar())
779 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
780
781 assert(0 && "FIXME: This doesn't handle complex operands yet");
782}
783
784RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
785 // Unary not performs promotions, then complements its integer operand.
786 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000787 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000788
789 if (V.isScalar())
790 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
791
792 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
793}
794
795
796/// C99 6.5.3.3
797RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
798 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000799 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000800
801 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000802 // TODO: Could dynamically modify easy computations here. For example, if
803 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000804 BoolVal = Builder.CreateNot(BoolVal, "lnot");
805
806 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000807 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000808}
809
Chris Lattner3f8c6e62007-07-18 18:12:07 +0000810/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
811/// an integer (RetType).
812RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
813 QualType RetType, bool isSizeOf) {
814 /// FIXME: This doesn't handle VLAs yet!
815 std::pair<uint64_t, unsigned> Info =
816 getContext().getTypeInfo(TypeToSize, SourceLocation());
817
818 uint64_t Val = isSizeOf ? Info.first : Info.second;
819 Val /= 8; // Return size in bytes, not bits.
820
821 assert(RetType->isIntegerType() && "Result type must be an integer!");
822
823 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
824 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
825}
826
Chris Lattnere47e4402007-06-01 18:02:12 +0000827
Chris Lattnerdb91b162007-06-02 00:16:28 +0000828//===--------------------------------------------------------------------===//
829// Binary Operator Emission
830//===--------------------------------------------------------------------===//
831
832// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000833QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000834EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
835 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000836 QualType LHSType, RHSType;
837 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
838 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
839
Chris Lattnercf250242007-06-03 02:02:44 +0000840 // If both operands have the same source type, we're done already.
841 if (LHSType == RHSType) return LHSType;
842
843 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
844 // The caller can deal with this (e.g. pointer + int).
845 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
846 return LHSType;
847
848 // At this point, we have two different arithmetic types.
849
850 // Handle complex types first (C99 6.3.1.8p1).
851 if (LHSType->isComplexType() || RHSType->isComplexType()) {
852 assert(0 && "FIXME: complex types unimp");
853#if 0
854 // if we have an integer operand, the result is the complex type.
855 if (rhs->isIntegerType())
856 return lhs;
857 if (lhs->isIntegerType())
858 return rhs;
859 return Context.maxComplexType(lhs, rhs);
860#endif
861 }
862
863 // If neither operand is complex, they must be scalars.
864 llvm::Value *LHSV = LHS.getVal();
865 llvm::Value *RHSV = RHS.getVal();
866
867 // If the LLVM types are already equal, then they only differed in sign, or it
868 // was something like char/signed char or double/long double.
869 if (LHSV->getType() == RHSV->getType())
870 return LHSType;
871
872 // Now handle "real" floating types (i.e. float, double, long double).
873 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
874 // if we have an integer operand, the result is the real floating type, and
875 // the integer converts to FP.
876 if (RHSType->isIntegerType()) {
877 // Promote the RHS to an FP type of the LHS, with the sign following the
878 // RHS.
879 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000880 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000881 else
Chris Lattner8394d792007-06-05 20:53:16 +0000882 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000883 return LHSType;
884 }
885
886 if (LHSType->isIntegerType()) {
887 // Promote the LHS to an FP type of the RHS, with the sign following the
888 // LHS.
889 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000890 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000891 else
Chris Lattner8394d792007-06-05 20:53:16 +0000892 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000893 return RHSType;
894 }
895
896 // Otherwise, they are two FP types. Promote the smaller operand to the
897 // bigger result.
898 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
899
900 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000901 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000902 else
Chris Lattner8394d792007-06-05 20:53:16 +0000903 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000904 return BiggerType;
905 }
906
907 // Finally, we have two integer types that are different according to C. Do
908 // a sign or zero extension if needed.
909
910 // Otherwise, one type is smaller than the other.
911 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
912
913 if (LHSType == ResTy) {
914 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000915 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000916 else
Chris Lattner8394d792007-06-05 20:53:16 +0000917 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000918 } else {
919 assert(RHSType == ResTy && "Unknown conversion");
920 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000921 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000922 else
Chris Lattner8394d792007-06-05 20:53:16 +0000923 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000924 }
925 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000926}
927
Chris Lattnercd215f02007-06-29 16:52:55 +0000928/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
929/// are strange in that the result of the operation is not the same type as the
930/// intermediate computation. This function emits the LHS and RHS operands of
931/// the compound assignment, promoting them to their common computation type.
932///
933/// Since the LHS is an lvalue, and the result is stored back through it, we
934/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
935/// RHS values are both in the computation type for the operator.
936void CodeGenFunction::
937EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
938 LValue &LHSLV, RValue &LHS, RValue &RHS) {
939 LHSLV = EmitLValue(E->getLHS());
940
941 // Load the LHS and RHS operands.
942 QualType LHSTy = E->getLHS()->getType();
943 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
944 QualType RHSTy;
945 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
946
Chris Lattner47c247e2007-06-29 17:26:27 +0000947 // Shift operands do the usual unary conversions, but do not do the binary
948 // conversions.
949 if (E->isShiftAssignOp()) {
950 // FIXME: This is broken. Implicit conversions should be made explicit,
951 // so that this goes away. This causes us to reload the LHS.
952 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
953 }
954
Chris Lattnercd215f02007-06-29 16:52:55 +0000955 // Convert the LHS and RHS to the common evaluation type.
956 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
957 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
958}
959
960/// EmitCompoundAssignmentResult - Given a result value in the computation type,
961/// truncate it down to the actual result type, store it through the LHS lvalue,
962/// and return it.
963RValue CodeGenFunction::
964EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
965 LValue LHSLV, RValue ResV) {
966
967 // Truncate back to the destination type.
968 if (E->getComputationType() != E->getType())
969 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
970
971 // Store the result value into the LHS.
972 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
973
974 // Return the result.
975 return ResV;
976}
977
Chris Lattnerdb91b162007-06-02 00:16:28 +0000978
Chris Lattner8394d792007-06-05 20:53:16 +0000979RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000980 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000981 switch (E->getOpcode()) {
982 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000983 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000984 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000985 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerb25a9432007-06-29 17:03:06 +0000986 case BinaryOperator::Mul:
987 EmitUsualArithmeticConversions(E, LHS, RHS);
988 return EmitMul(LHS, RHS, E->getType());
989 case BinaryOperator::Div:
990 EmitUsualArithmeticConversions(E, LHS, RHS);
991 return EmitDiv(LHS, RHS, E->getType());
992 case BinaryOperator::Rem:
993 EmitUsualArithmeticConversions(E, LHS, RHS);
994 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000995 case BinaryOperator::Add: {
996 QualType ExprTy = E->getType();
997 if (ExprTy->isPointerType()) {
998 Expr *LHSExpr = E->getLHS();
999 QualType LHSTy;
1000 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1001 Expr *RHSExpr = E->getRHS();
1002 QualType RHSTy;
1003 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1004 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
1005 } else {
1006 EmitUsualArithmeticConversions(E, LHS, RHS);
1007 return EmitAdd(LHS, RHS, ExprTy);
1008 }
1009 }
1010 case BinaryOperator::Sub: {
1011 QualType ExprTy = E->getType();
1012 Expr *LHSExpr = E->getLHS();
1013 if (LHSExpr->getType()->isPointerType()) {
1014 QualType LHSTy;
1015 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1016 Expr *RHSExpr = E->getRHS();
1017 QualType RHSTy;
1018 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1019 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
1020 } else {
1021 EmitUsualArithmeticConversions(E, LHS, RHS);
1022 return EmitSub(LHS, RHS, ExprTy);
1023 }
1024 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001025 case BinaryOperator::Shl:
1026 EmitShiftOperands(E, LHS, RHS);
1027 return EmitShl(LHS, RHS, E->getType());
1028 case BinaryOperator::Shr:
1029 EmitShiftOperands(E, LHS, RHS);
1030 return EmitShr(LHS, RHS, E->getType());
Chris Lattnerb25a9432007-06-29 17:03:06 +00001031 case BinaryOperator::And:
1032 EmitUsualArithmeticConversions(E, LHS, RHS);
1033 return EmitAnd(LHS, RHS, E->getType());
1034 case BinaryOperator::Xor:
1035 EmitUsualArithmeticConversions(E, LHS, RHS);
1036 return EmitXor(LHS, RHS, E->getType());
1037 case BinaryOperator::Or :
1038 EmitUsualArithmeticConversions(E, LHS, RHS);
1039 return EmitOr(LHS, RHS, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001040 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1041 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +00001042 case BinaryOperator::LT:
1043 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1044 llvm::ICmpInst::ICMP_SLT,
1045 llvm::FCmpInst::FCMP_OLT);
1046 case BinaryOperator::GT:
1047 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1048 llvm::ICmpInst::ICMP_SGT,
1049 llvm::FCmpInst::FCMP_OGT);
1050 case BinaryOperator::LE:
1051 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1052 llvm::ICmpInst::ICMP_SLE,
1053 llvm::FCmpInst::FCMP_OLE);
1054 case BinaryOperator::GE:
1055 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1056 llvm::ICmpInst::ICMP_SGE,
1057 llvm::FCmpInst::FCMP_OGE);
1058 case BinaryOperator::EQ:
1059 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1060 llvm::ICmpInst::ICMP_EQ,
1061 llvm::FCmpInst::FCMP_OEQ);
1062 case BinaryOperator::NE:
1063 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1064 llvm::ICmpInst::ICMP_NE,
1065 llvm::FCmpInst::FCMP_UNE);
Chris Lattnercd215f02007-06-29 16:52:55 +00001066 case BinaryOperator::Assign:
1067 return EmitBinaryAssign(E);
1068
Chris Lattnerb25a9432007-06-29 17:03:06 +00001069 case BinaryOperator::MulAssign: {
1070 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1071 LValue LHSLV;
1072 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1073 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1074 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1075 }
1076 case BinaryOperator::DivAssign: {
1077 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1078 LValue LHSLV;
1079 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1080 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1081 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1082 }
1083 case BinaryOperator::RemAssign: {
1084 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1085 LValue LHSLV;
1086 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1087 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1088 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1089 }
Chris Lattnercd215f02007-06-29 16:52:55 +00001090 case BinaryOperator::AddAssign: {
1091 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1092 LValue LHSLV;
1093 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1094 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1095 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1096 }
1097 case BinaryOperator::SubAssign: {
1098 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1099 LValue LHSLV;
1100 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1101 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1102 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1103 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001104 case BinaryOperator::ShlAssign: {
1105 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1106 LValue LHSLV;
1107 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1108 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1109 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1110 }
1111 case BinaryOperator::ShrAssign: {
1112 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1113 LValue LHSLV;
1114 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1115 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1116 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1117 }
Chris Lattnerb25a9432007-06-29 17:03:06 +00001118 case BinaryOperator::AndAssign: {
1119 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1120 LValue LHSLV;
1121 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1122 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1123 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1124 }
1125 case BinaryOperator::OrAssign: {
1126 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1127 LValue LHSLV;
1128 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1129 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1130 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1131 }
1132 case BinaryOperator::XorAssign: {
1133 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1134 LValue LHSLV;
1135 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1136 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1137 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1138 }
Chris Lattner8394d792007-06-05 20:53:16 +00001139 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +00001140 }
1141}
1142
Chris Lattnerb25a9432007-06-29 17:03:06 +00001143RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001144 if (LHS.isScalar())
1145 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1146
Gabor Greifd4606aa2007-07-13 23:33:18 +00001147 // Otherwise, this must be a complex number.
1148 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1149
1150 EmitLoadOfComplex(LHS, LHSR, LHSI);
1151 EmitLoadOfComplex(RHS, RHSR, RHSI);
1152
1153 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1154 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1155 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1156
1157 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1158 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1159 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1160
1161 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1162 EmitStoreOfComplex(ResR, ResI, Res);
1163 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001164}
1165
Chris Lattnerb25a9432007-06-29 17:03:06 +00001166RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001167 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001168 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001169 if (LHS.getVal()->getType()->isFloatingPoint())
1170 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
Chris Lattnerb25a9432007-06-29 17:03:06 +00001171 else if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001172 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1173 else
1174 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1175 return RValue::get(RV);
1176 }
1177 assert(0 && "FIXME: This doesn't handle complex operands yet");
1178}
1179
Chris Lattnerb25a9432007-06-29 17:03:06 +00001180RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001181 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001182 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001183 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattnerb25a9432007-06-29 17:03:06 +00001184 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001185 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1186 else
1187 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1188 return RValue::get(RV);
1189 }
1190
1191 assert(0 && "FIXME: This doesn't handle complex operands yet");
1192}
1193
Chris Lattnercd215f02007-06-29 16:52:55 +00001194RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001195 if (LHS.isScalar())
1196 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattnercd215f02007-06-29 16:52:55 +00001197
Chris Lattnere9a64532007-06-22 21:44:33 +00001198 // Otherwise, this must be a complex number.
1199 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1200
1201 EmitLoadOfComplex(LHS, LHSR, LHSI);
1202 EmitLoadOfComplex(RHS, RHSR, RHSI);
1203
1204 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1205 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1206
Chris Lattnercd215f02007-06-29 16:52:55 +00001207 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
Chris Lattnere9a64532007-06-22 21:44:33 +00001208 EmitStoreOfComplex(ResR, ResI, Res);
1209 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001210}
1211
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001212RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1213 RValue RHS, QualType RHSTy,
1214 QualType ResTy) {
1215 llvm::Value *LHSValue = LHS.getVal();
1216 llvm::Value *RHSValue = RHS.getVal();
1217 if (LHSTy->isPointerType()) {
1218 // pointer + int
1219 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1220 } else {
1221 // int + pointer
1222 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1223 }
1224}
1225
Chris Lattnercd215f02007-06-29 16:52:55 +00001226RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001227 if (LHS.isScalar())
1228 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1229
1230 assert(0 && "FIXME: This doesn't handle complex operands yet");
Chris Lattner8394d792007-06-05 20:53:16 +00001231}
1232
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001233RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1234 RValue RHS, QualType RHSTy,
1235 QualType ResTy) {
1236 llvm::Value *LHSValue = LHS.getVal();
1237 llvm::Value *RHSValue = RHS.getVal();
1238 if (const PointerType *RHSPtrType =
1239 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1240 // pointer - pointer
1241 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1242 QualType LHSElementType = LHSPtrType->getPointeeType();
1243 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1244 "can't subtract pointers with differing element types");
Chris Lattner651f0e92007-07-16 05:43:05 +00001245 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattner4481b422007-07-14 01:29:45 +00001246 SourceLocation()) / 8;
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001247 const llvm::Type *ResultType = ConvertType(ResTy);
1248 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1249 "sub.ptr.lhs.cast");
1250 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1251 "sub.ptr.rhs.cast");
1252 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1253 "sub.ptr.sub");
Chris Lattner651f0e92007-07-16 05:43:05 +00001254
1255 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1256 // remainder. As such, we handle common power-of-two cases here to generate
1257 // better code.
1258 if (llvm::isPowerOf2_64(ElementSize)) {
1259 llvm::Value *ShAmt =
1260 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1261 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1262 } else {
1263 // Otherwise, do a full sdiv.
1264 llvm::Value *BytesPerElement =
1265 llvm::ConstantInt::get(ResultType, ElementSize);
1266 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1267 "sub.ptr.div"));
1268 }
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001269 } else {
1270 // pointer - int
1271 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1272 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1273 }
1274}
1275
Chris Lattner47c247e2007-06-29 17:26:27 +00001276void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1277 RValue &LHS, RValue &RHS) {
Chris Lattner8394d792007-06-05 20:53:16 +00001278 // For shifts, integer promotions are performed, but the usual arithmetic
1279 // conversions are not. The LHS and RHS need not have the same type.
Chris Lattner8394d792007-06-05 20:53:16 +00001280 QualType ResTy;
Chris Lattner47c247e2007-06-29 17:26:27 +00001281 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1282 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1283}
Chris Lattner8394d792007-06-05 20:53:16 +00001284
Chris Lattner47c247e2007-06-29 17:26:27 +00001285
1286RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1287 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1288
Chris Lattner8394d792007-06-05 20:53:16 +00001289 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1290 // RHS to the same size as the LHS.
1291 if (LHS->getType() != RHS->getType())
1292 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1293
1294 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1295}
1296
Chris Lattner47c247e2007-06-29 17:26:27 +00001297RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1298 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
Chris Lattner8394d792007-06-05 20:53:16 +00001299
1300 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1301 // RHS to the same size as the LHS.
1302 if (LHS->getType() != RHS->getType())
1303 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1304
Chris Lattner47c247e2007-06-29 17:26:27 +00001305 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001306 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1307 else
1308 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1309}
1310
Chris Lattner1fde0b32007-06-20 18:30:55 +00001311RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1312 unsigned UICmpOpc, unsigned SICmpOpc,
1313 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +00001314 RValue LHS, RHS;
1315 EmitUsualArithmeticConversions(E, LHS, RHS);
1316
1317 llvm::Value *Result;
1318 if (LHS.isScalar()) {
1319 if (LHS.getVal()->getType()->isFloatingPoint()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001320 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1321 LHS.getVal(), RHS.getVal(), "cmp");
1322 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1323 // FIXME: This check isn't right for "unsigned short < int" where ushort
1324 // promotes to int and does a signed compare.
1325 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1326 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001327 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001328 // Signed integers and pointers.
1329 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1330 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001331 }
1332 } else {
1333 // Struct/union/complex
Gabor Greifd4606aa2007-07-13 23:33:18 +00001334 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1335 EmitLoadOfComplex(LHS, LHSR, LHSI);
1336 EmitLoadOfComplex(RHS, RHSR, RHSI);
1337
Gabor Greife97cd7e2007-07-14 20:05:18 +00001338 // FIXME: need to consider _Complex over integers too!
1339
Gabor Greifd4606aa2007-07-13 23:33:18 +00001340 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1341 LHSR, RHSR, "cmp.r");
1342 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1343 LHSI, RHSI, "cmp.i");
1344 if (BinaryOperator::EQ == E->getOpcode()) {
1345 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1346 } else if (BinaryOperator::NE == E->getOpcode()) {
1347 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1348 } else {
1349 assert(0 && "Complex comparison other than == or != ?");
1350 }
Chris Lattner273c63d2007-06-20 18:02:30 +00001351 }
Gabor Greifd4606aa2007-07-13 23:33:18 +00001352
Chris Lattner273c63d2007-06-20 18:02:30 +00001353 // ZExt result to int.
1354 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1355}
1356
Chris Lattnerb25a9432007-06-29 17:03:06 +00001357RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001358 if (LHS.isScalar())
1359 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1360
1361 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1362}
1363
Chris Lattnerb25a9432007-06-29 17:03:06 +00001364RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001365 if (LHS.isScalar())
1366 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1367
1368 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1369}
1370
Chris Lattnerb25a9432007-06-29 17:03:06 +00001371RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001372 if (LHS.isScalar())
1373 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1374
1375 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1376}
1377
1378RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001379 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001380
Chris Lattner23b7eb62007-06-15 23:05:46 +00001381 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1382 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001383
Chris Lattner23b7eb62007-06-15 23:05:46 +00001384 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001385 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1386
1387 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001388 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001389
1390 // Reaquire the RHS block, as there may be subblocks inserted.
1391 RHSBlock = Builder.GetInsertBlock();
1392 EmitBlock(ContBlock);
1393
1394 // Create a PHI node. If we just evaluted the LHS condition, the result is
1395 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001396 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +00001397 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001398 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001399 PN->addIncoming(RHSCond, RHSBlock);
1400
1401 // ZExt result to int.
1402 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1403}
1404
1405RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001406 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001407
Chris Lattner23b7eb62007-06-15 23:05:46 +00001408 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1409 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001410
Chris Lattner23b7eb62007-06-15 23:05:46 +00001411 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001412 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1413
1414 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001415 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001416
1417 // Reaquire the RHS block, as there may be subblocks inserted.
1418 RHSBlock = Builder.GetInsertBlock();
1419 EmitBlock(ContBlock);
1420
1421 // Create a PHI node. If we just evaluted the LHS condition, the result is
1422 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001423 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +00001424 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001425 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001426 PN->addIncoming(RHSCond, RHSBlock);
1427
1428 // ZExt result to int.
1429 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1430}
1431
1432RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1433 LValue LHS = EmitLValue(E->getLHS());
1434
1435 QualType RHSTy;
1436 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1437
1438 // Convert the RHS to the type of the LHS.
Chris Lattnerf033c142007-06-22 19:05:19 +00001439 RHS = EmitConversion(RHS, RHSTy, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001440
1441 // Store the value into the LHS.
1442 EmitStoreThroughLValue(RHS, LHS, E->getType());
1443
1444 // Return the converted RHS.
1445 return RHS;
1446}
1447
Chris Lattner9369a562007-06-29 16:31:29 +00001448
Chris Lattner8394d792007-06-05 20:53:16 +00001449RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1450 EmitExpr(E->getLHS());
1451 return EmitExpr(E->getRHS());
1452}
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001453
1454RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1455 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1456 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1457 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1458
1459 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1460 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1461
Chris Lattner027f21d2007-07-14 00:01:01 +00001462 // FIXME: Implement this for aggregate values.
1463
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001464 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1465 // that's not possible with the current design.
1466
1467 EmitBlock(LHSBlock);
1468 QualType LHSTy;
1469 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1470 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1471 Cond;
1472 Builder.CreateBr(ContBlock);
1473 LHSBlock = Builder.GetInsertBlock();
1474
1475 EmitBlock(RHSBlock);
1476 QualType RHSTy;
1477 llvm::Value *RHSValue =
1478 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1479 Builder.CreateBr(ContBlock);
1480 RHSBlock = Builder.GetInsertBlock();
1481
1482 const llvm::Type *LHSType = LHSValue->getType();
1483 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1484
1485 EmitBlock(ContBlock);
1486 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1487 PN->reserveOperandSpace(2);
1488 PN->addIncoming(LHSValue, LHSBlock);
1489 PN->addIncoming(RHSValue, RHSBlock);
1490
1491 return RValue::get(PN);
1492}