blob: 20d7c7f7cb217e45623179a37f181ce8400886b3 [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"
15#include "clang/AST/AST.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
Chris Lattner4347e3692007-06-06 04:54:52 +000018#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000020using namespace llvm;
21using namespace clang;
22using namespace CodeGen;
23
Chris Lattnerd7f58862007-06-02 05:24:33 +000024//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000025// Miscellaneous Helper Methods
26//===--------------------------------------------------------------------===//
27
Chris Lattner8394d792007-06-05 20:53:16 +000028
29/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
30/// expression and compare the result against zero, returning an Int1Ty value.
31Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
32 QualType Ty;
33 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
34 return ConvertScalarValueToBool(Val, Ty);
35}
36
37//===--------------------------------------------------------------------===//
38// Conversions
39//===--------------------------------------------------------------------===//
40
41/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
42/// the type specified by DstTy, following the rules of C99 6.3.
43RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
Chris Lattnercf106ab2007-06-06 04:05:39 +000044 QualType DstTy, SourceLocation Loc) {
Chris Lattner8394d792007-06-05 20:53:16 +000045 ValTy = ValTy.getCanonicalType();
46 DstTy = DstTy.getCanonicalType();
47 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000048
49 // Handle conversions to bool first, they are special: comparisons against 0.
50 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
51 if (DestBT->getKind() == BuiltinType::Bool)
52 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
Chris Lattner8394d792007-06-05 20:53:16 +000053
Chris Lattner83b484b2007-06-06 04:39:08 +000054 // Handle pointer conversions next: pointers can only be converted to/from
55 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000056 if (isa<PointerType>(DstTy)) {
57 const llvm::Type *DestTy = ConvertType(DstTy, Loc);
58
59 // The source value may be an integer, or a pointer.
60 assert(Val.isScalar() && "Can only convert from integer or pointer");
61 if (isa<llvm::PointerType>(Val.getVal()->getType()))
62 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
63 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
64 return RValue::get(Builder.CreatePtrToInt(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +000065 }
66
67 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +000068 // Must be an ptr to int cast.
69 const llvm::Type *DestTy = ConvertType(DstTy, Loc);
70 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
71 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +000072 }
Chris Lattner83b484b2007-06-06 04:39:08 +000073
74 // Finally, we have the arithmetic types: real int/float and complex
75 // int/float. Handle real->real conversions first, they are the most
76 // common.
77 if (Val.isScalar() && DstTy->isRealType()) {
78 // We know that these are representable as scalars in LLVM, convert to LLVM
79 // types since they are easier to reason about.
80 Value *SrcVal = Val.getVal();
81 const llvm::Type *DestTy = ConvertType(DstTy, Loc);
82 if (SrcVal->getType() == DestTy) return Val;
83
84 Value *Result;
85 if (isa<llvm::IntegerType>(SrcVal->getType())) {
86 bool InputSigned = ValTy->isSignedIntegerType();
87 if (isa<llvm::IntegerType>(DestTy))
88 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
89 else if (InputSigned)
90 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
91 else
92 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
93 } else {
94 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
95 if (isa<llvm::IntegerType>(DestTy)) {
96 if (DstTy->isSignedIntegerType())
97 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
98 else
99 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
100 } else {
101 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
102 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
103 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
104 else
105 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
106 }
107 }
108 return RValue::get(Result);
109 }
110
111 assert(0 && "FIXME: We don't support complex conversions yet!");
Chris Lattner8394d792007-06-05 20:53:16 +0000112}
113
114
115/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000116/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner8394d792007-06-05 20:53:16 +0000117Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000118 Ty = Ty.getCanonicalType();
119 Value *Result;
120 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
121 switch (BT->getKind()) {
122 default: assert(0 && "Unknown scalar value");
123 case BuiltinType::Bool:
124 Result = Val.getVal();
125 // Bool is already evaluated right.
126 assert(Result->getType() == llvm::Type::Int1Ty &&
127 "Unexpected bool value type!");
128 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000129 case BuiltinType::Char_S:
130 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000131 case BuiltinType::SChar:
132 case BuiltinType::UChar:
133 case BuiltinType::Short:
134 case BuiltinType::UShort:
135 case BuiltinType::Int:
136 case BuiltinType::UInt:
137 case BuiltinType::Long:
138 case BuiltinType::ULong:
139 case BuiltinType::LongLong:
140 case BuiltinType::ULongLong:
141 // Code below handles simple integers.
142 break;
143 case BuiltinType::Float:
144 case BuiltinType::Double:
145 case BuiltinType::LongDouble: {
146 // Compare against 0.0 for fp scalars.
147 Result = Val.getVal();
148 llvm::Value *Zero = Constant::getNullValue(Result->getType());
149 // FIXME: llvm-gcc produces a une comparison: validate this is right.
150 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
151 return Result;
152 }
153
154 case BuiltinType::FloatComplex:
155 case BuiltinType::DoubleComplex:
156 case BuiltinType::LongDoubleComplex:
157 assert(0 && "comparisons against complex not implemented yet");
158 }
159 } else {
160 assert((isa<PointerType>(Ty) ||
161 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) &&
162 "Unknown scalar type");
163 // Code below handles this fine.
164 }
165
166 // Usual case for integers, pointers, and enums: compare against zero.
167 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000168
169 // Because of the type rules of C, we often end up computing a logical value,
170 // then zero extending it to int, then wanting it as a logical value again.
171 // Optimize this common case.
172 if (llvm::ZExtInst *ZI = dyn_cast<ZExtInst>(Result)) {
173 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
174 Result = ZI->getOperand(0);
175 ZI->eraseFromParent();
176 return Result;
177 }
178 }
179
Chris Lattnerf0106d22007-06-02 19:33:17 +0000180 llvm::Value *Zero = Constant::getNullValue(Result->getType());
181 return Builder.CreateICmpNE(Result, Zero, "tobool");
182}
183
Chris Lattnera45c5af2007-06-02 19:47:04 +0000184//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000185// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000186//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000187
Chris Lattner8394d792007-06-05 20:53:16 +0000188/// EmitLValue - Emit code to compute a designator that specifies the location
189/// of the expression.
190///
191/// This can return one of two things: a simple address or a bitfield
192/// reference. In either case, the LLVM Value* in the LValue structure is
193/// guaranteed to be an LLVM pointer type.
194///
195/// If this returns a bitfield reference, nothing about the pointee type of
196/// the LLVM value is known: For example, it may not be a pointer to an
197/// integer.
198///
199/// If this returns a normal address, and if the lvalue's C type is fixed
200/// size, this method guarantees that the returned pointer type will point to
201/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
202/// variable length type, this is not possible.
203///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000204LValue CodeGenFunction::EmitLValue(const Expr *E) {
205 switch (E->getStmtClass()) {
206 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000207 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000208 E->dump();
209 return LValue::getAddr(UndefValue::get(
210 llvm::PointerType::get(llvm::Type::Int32Ty)));
211
212 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000213 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner4347e3692007-06-06 04:54:52 +0000214 case Expr::StringLiteralClass:
215 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000216
217 case Expr::UnaryOperatorClass:
218 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000219 case Expr::ArraySubscriptExprClass:
220 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000221 }
222}
223
Chris Lattner8394d792007-06-05 20:53:16 +0000224/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
225/// this method emits the address of the lvalue, then loads the result as an
226/// rvalue, returning the rvalue.
227RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
228 LValue LV = EmitLValue(E);
229
230 QualType ExprTy = E->getType().getCanonicalType();
231
232 // FIXME: this is silly and obviously wrong for non-scalars.
233 assert(!LV.isBitfield());
234 return RValue::get(Builder.CreateLoad(LV.getAddress(), "tmp"));
235}
236
237/// EmitStoreThroughLValue - Store the specified rvalue into the specified
238/// lvalue, where both are guaranteed to the have the same type, and that type
239/// is 'Ty'.
240void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
241 QualType Ty) {
242 // FIXME: This is obviously bogus.
243 assert(!Dst.isBitfield() && "FIXME: Don't support store to bitfield yet");
244 assert(Src.isScalar() && "FIXME: Don't support store of aggregate yet");
245
246 // TODO: Handle volatility etc.
247 Value *Addr = Dst.getAddress();
248 const llvm::Type *SrcTy = Src.getVal()->getType();
249 const llvm::Type *AddrTy =
250 cast<llvm::PointerType>(Addr->getType())->getElementType();
251
252 if (AddrTy != SrcTy)
253 Addr = Builder.CreateBitCast(Addr, llvm::PointerType::get(SrcTy),
254 "storetmp");
255 Builder.CreateStore(Src.getVal(), Addr);
256}
257
Chris Lattnerd7f58862007-06-02 05:24:33 +0000258
259LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
260 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000261 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattnerd7f58862007-06-02 05:24:33 +0000262 Value *V = LocalDeclMap[D];
263 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
264 return LValue::getAddr(V);
265 }
266 assert(0 && "Unimp declref");
267}
Chris Lattnere47e4402007-06-01 18:02:12 +0000268
Chris Lattner8394d792007-06-05 20:53:16 +0000269LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
270 // __extension__ doesn't affect lvalue-ness.
271 if (E->getOpcode() == UnaryOperator::Extension)
272 return EmitLValue(E->getSubExpr());
273
274 assert(E->getOpcode() == UnaryOperator::Deref &&
275 "'*' is the only unary operator that produces an lvalue");
276 return LValue::getAddr(EmitExpr(E->getSubExpr()).getVal());
277}
278
Chris Lattner4347e3692007-06-06 04:54:52 +0000279LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
280 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
281 const char *StrData = E->getStrData();
282 unsigned Len = E->getByteLength();
283
284 // FIXME: Can cache/reuse these within the module.
285 Constant *C = llvm::ConstantArray::get(std::string(StrData, StrData+Len));
286
287 // Create a global variable for this.
288 C = new llvm::GlobalVariable(C->getType(), true, GlobalValue::InternalLinkage,
289 C, ".str", CurFn->getParent());
290 Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
291 Constant *Zeros[] = { Zero, Zero };
292 C = ConstantExpr::getGetElementPtr(C, Zeros, 2);
293 return LValue::getAddr(C);
294}
295
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000296LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
297 // The base and index must be pointers or integers, neither of which are
298 // aggregates. Emit them.
299 QualType BaseTy;
300 Value *Base =EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
301 QualType IdxTy;
302 Value *Idx = EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
303
304 // Usually the base is the pointer type, but sometimes it is the index.
305 // Canonicalize to have the pointer as the base.
306 if (isa<llvm::PointerType>(Idx->getType())) {
307 std::swap(Base, Idx);
308 std::swap(BaseTy, IdxTy);
309 }
310
311 // The pointer is now the base. Extend or truncate the index type to 32 or
312 // 64-bits.
313 bool IdxSigned = IdxTy->isSignedIntegerType();
314 unsigned IdxBitwidth = cast<IntegerType>(Idx->getType())->getBitWidth();
315 if (IdxBitwidth != LLVMPointerWidth)
316 Idx = Builder.CreateIntCast(Idx, IntegerType::get(LLVMPointerWidth),
317 IdxSigned, "idxprom");
318
319 // We know that the pointer points to a type of the correct size, unless the
320 // size is a VLA.
321 if (!E->getType()->isConstantSizeType())
322 assert(0 && "VLA idx not implemented");
323 return LValue::getAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
324}
325
Chris Lattnere47e4402007-06-01 18:02:12 +0000326//===--------------------------------------------------------------------===//
327// Expression Emission
328//===--------------------------------------------------------------------===//
329
Chris Lattner8394d792007-06-05 20:53:16 +0000330RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000331 assert(E && "Null expression?");
332
333 switch (E->getStmtClass()) {
334 default:
335 printf("Unimplemented expr!\n");
336 E->dump();
Chris Lattner8394d792007-06-05 20:53:16 +0000337 return RValue::get(UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000338
339 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000340 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000341 // DeclRef's of EnumConstantDecl's are simple rvalues.
342 if (const EnumConstantDecl *EC =
343 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
344 return RValue::get(ConstantInt::get(EC->getInitVal()));
345
346 // FALLTHROUGH
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000347 case Expr::ArraySubscriptExprClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000348 return EmitLoadOfLValue(E);
Chris Lattner4347e3692007-06-06 04:54:52 +0000349 case Expr::StringLiteralClass:
350 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000351
352 // Leaf expressions.
353 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000354 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000355
Chris Lattnerd7f58862007-06-02 05:24:33 +0000356 // Operators.
357 case Expr::ParenExprClass:
358 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000359 case Expr::UnaryOperatorClass:
360 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000361 case Expr::CastExprClass:
362 return EmitCastExpr(cast<CastExpr>(E));
Chris Lattner2b228c92007-06-15 21:34:29 +0000363 case Expr::CallExprClass:
364 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000365 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000366 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000367 }
368
369}
370
Chris Lattner8394d792007-06-05 20:53:16 +0000371RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
372 return RValue::get(ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000373}
374
Chris Lattner8394d792007-06-05 20:53:16 +0000375RValue CodeGenFunction::EmitCastExpr(const CastExpr *E) {
376 QualType SrcTy;
377 RValue Src = EmitExprWithUsualUnaryConversions(E->getSubExpr(), SrcTy);
378
379 // If the destination is void, just evaluate the source.
380 if (E->getType()->isVoidType())
381 return RValue::getAggregate(0);
382
Chris Lattnercf106ab2007-06-06 04:05:39 +0000383 return EmitConversion(Src, SrcTy, E->getType(), E->getLParenLoc());
Chris Lattner8394d792007-06-05 20:53:16 +0000384}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000385
Chris Lattner2b228c92007-06-15 21:34:29 +0000386RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
387 QualType Ty;
388 Value *Callee =EmitExprWithUsualUnaryConversions(E->getCallee(), Ty).getVal();
389
390 SmallVector<Value*, 16> Args;
391
392 // FIXME: Handle struct return.
393 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
394 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), Ty);
395
396 if (ArgVal.isScalar())
397 Args.push_back(ArgVal.getVal());
398 else // Pass by-address. FIXME: Set attribute bit on call.
399 Args.push_back(ArgVal.getAggregateVal());
400 }
401
402 Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
403 if (V->getType() != llvm::Type::VoidTy)
404 V->setName("call");
405
406 // FIXME: Struct return;
407 return RValue::get(V);
408}
409
410
Chris Lattner8394d792007-06-05 20:53:16 +0000411//===----------------------------------------------------------------------===//
412// Unary Operator Emission
413//===----------------------------------------------------------------------===//
414
415RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
416 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000417 ResTy = E->getType().getCanonicalType();
418
419 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
420 // Functions are promoted to their address.
421 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000422 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000423 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
424 // C99 6.3.2.1p3
425 ResTy = getContext().getPointerType(ary->getElementType());
426
427 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
428 // will not true when we add support for VLAs.
429 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
430
431 assert(isa<llvm::PointerType>(V->getType()) &&
432 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
433 ->getElementType()) &&
434 "Doesn't support VLAs yet!");
435 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000436 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000437 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
438 // FIXME: this probably isn't right, pending clarification from Steve.
439 llvm::Value *Val = EmitExpr(E).getVal();
440
Chris Lattner6db1fb82007-06-02 22:49:07 +0000441 // If the input is a signed integer, sign extend to the destination.
442 if (ResTy->isSignedIntegerType()) {
443 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
444 } else {
445 // This handles unsigned types, including bool.
446 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
447 }
448 ResTy = getContext().IntTy;
449
Chris Lattner8394d792007-06-05 20:53:16 +0000450 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000451 }
452
453 // Otherwise, this is a float, double, int, struct, etc.
454 return EmitExpr(E);
455}
456
457
Chris Lattner8394d792007-06-05 20:53:16 +0000458RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000459 switch (E->getOpcode()) {
460 default:
461 printf("Unimplemented unary expr!\n");
462 E->dump();
Chris Lattner8394d792007-06-05 20:53:16 +0000463 return RValue::get(UndefValue::get(llvm::Type::Int32Ty));
464 // FIXME: pre/post inc/dec
465 case UnaryOperator::AddrOf: return EmitUnaryAddrOf(E);
466 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
467 case UnaryOperator::Plus : return EmitUnaryPlus(E);
468 case UnaryOperator::Minus : return EmitUnaryMinus(E);
469 case UnaryOperator::Not : return EmitUnaryNot(E);
470 case UnaryOperator::LNot : return EmitUnaryLNot(E);
471 // FIXME: SIZEOF/ALIGNOF(expr).
472 // FIXME: real/imag
473 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000474 }
475}
476
Chris Lattner8394d792007-06-05 20:53:16 +0000477/// C99 6.5.3.2
478RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
479 // The address of the operand is just its lvalue. It cannot be a bitfield.
480 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
481}
482
483RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
484 // Unary plus just performs promotions on its arithmetic operand.
485 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000486 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000487}
488
489RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
490 // Unary minus performs promotions, then negates its arithmetic operand.
491 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000492 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000493
Chris Lattner8394d792007-06-05 20:53:16 +0000494 if (V.isScalar())
495 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
496
497 assert(0 && "FIXME: This doesn't handle complex operands yet");
498}
499
500RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
501 // Unary not performs promotions, then complements its integer operand.
502 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000503 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000504
505 if (V.isScalar())
506 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
507
508 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
509}
510
511
512/// C99 6.5.3.3
513RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
514 // Compare operand to zero.
515 Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000516
517 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000518 // TODO: Could dynamically modify easy computations here. For example, if
519 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000520 BoolVal = Builder.CreateNot(BoolVal, "lnot");
521
522 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000523 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000524}
525
Chris Lattnere47e4402007-06-01 18:02:12 +0000526
Chris Lattnerdb91b162007-06-02 00:16:28 +0000527//===--------------------------------------------------------------------===//
528// Binary Operator Emission
529//===--------------------------------------------------------------------===//
530
531// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000532QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000533EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
534 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000535 QualType LHSType, RHSType;
536 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
537 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
538
Chris Lattnercf250242007-06-03 02:02:44 +0000539 // If both operands have the same source type, we're done already.
540 if (LHSType == RHSType) return LHSType;
541
542 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
543 // The caller can deal with this (e.g. pointer + int).
544 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
545 return LHSType;
546
547 // At this point, we have two different arithmetic types.
548
549 // Handle complex types first (C99 6.3.1.8p1).
550 if (LHSType->isComplexType() || RHSType->isComplexType()) {
551 assert(0 && "FIXME: complex types unimp");
552#if 0
553 // if we have an integer operand, the result is the complex type.
554 if (rhs->isIntegerType())
555 return lhs;
556 if (lhs->isIntegerType())
557 return rhs;
558 return Context.maxComplexType(lhs, rhs);
559#endif
560 }
561
562 // If neither operand is complex, they must be scalars.
563 llvm::Value *LHSV = LHS.getVal();
564 llvm::Value *RHSV = RHS.getVal();
565
566 // If the LLVM types are already equal, then they only differed in sign, or it
567 // was something like char/signed char or double/long double.
568 if (LHSV->getType() == RHSV->getType())
569 return LHSType;
570
571 // Now handle "real" floating types (i.e. float, double, long double).
572 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
573 // if we have an integer operand, the result is the real floating type, and
574 // the integer converts to FP.
575 if (RHSType->isIntegerType()) {
576 // Promote the RHS to an FP type of the LHS, with the sign following the
577 // RHS.
578 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000579 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000580 else
Chris Lattner8394d792007-06-05 20:53:16 +0000581 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000582 return LHSType;
583 }
584
585 if (LHSType->isIntegerType()) {
586 // Promote the LHS to an FP type of the RHS, with the sign following the
587 // LHS.
588 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000589 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000590 else
Chris Lattner8394d792007-06-05 20:53:16 +0000591 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000592 return RHSType;
593 }
594
595 // Otherwise, they are two FP types. Promote the smaller operand to the
596 // bigger result.
597 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
598
599 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000600 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000601 else
Chris Lattner8394d792007-06-05 20:53:16 +0000602 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000603 return BiggerType;
604 }
605
606 // Finally, we have two integer types that are different according to C. Do
607 // a sign or zero extension if needed.
608
609 // Otherwise, one type is smaller than the other.
610 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
611
612 if (LHSType == ResTy) {
613 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000614 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000615 else
Chris Lattner8394d792007-06-05 20:53:16 +0000616 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000617 } else {
618 assert(RHSType == ResTy && "Unknown conversion");
619 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000620 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000621 else
Chris Lattner8394d792007-06-05 20:53:16 +0000622 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000623 }
624 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000625}
626
627
Chris Lattner8394d792007-06-05 20:53:16 +0000628RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnerdb91b162007-06-02 00:16:28 +0000629 switch (E->getOpcode()) {
630 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000631 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000632 E->dump();
Chris Lattner8394d792007-06-05 20:53:16 +0000633 return RValue::get(UndefValue::get(llvm::Type::Int32Ty));
634 case BinaryOperator::Mul: return EmitBinaryMul(E);
635 case BinaryOperator::Div: return EmitBinaryDiv(E);
636 case BinaryOperator::Rem: return EmitBinaryRem(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000637 case BinaryOperator::Add: return EmitBinaryAdd(E);
Chris Lattner8394d792007-06-05 20:53:16 +0000638 case BinaryOperator::Sub: return EmitBinarySub(E);
639 case BinaryOperator::Shl: return EmitBinaryShl(E);
640 case BinaryOperator::Shr: return EmitBinaryShr(E);
641
642 // FIXME: relational
643
644 case BinaryOperator::And: return EmitBinaryAnd(E);
645 case BinaryOperator::Xor: return EmitBinaryXor(E);
646 case BinaryOperator::Or : return EmitBinaryOr(E);
647 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
648 case BinaryOperator::LOr: return EmitBinaryLOr(E);
649
650 case BinaryOperator::Assign: return EmitBinaryAssign(E);
651 // FIXME: Assignment.
652 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000653 }
654}
655
Chris Lattner8394d792007-06-05 20:53:16 +0000656RValue CodeGenFunction::EmitBinaryMul(const BinaryOperator *E) {
657 RValue LHS, RHS;
658 EmitUsualArithmeticConversions(E, LHS, RHS);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000659
Chris Lattner8394d792007-06-05 20:53:16 +0000660 if (LHS.isScalar())
661 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
662
663 assert(0 && "FIXME: This doesn't handle complex operands yet");
664}
665
666RValue CodeGenFunction::EmitBinaryDiv(const BinaryOperator *E) {
667 RValue LHS, RHS;
668 EmitUsualArithmeticConversions(E, LHS, RHS);
669
670 if (LHS.isScalar()) {
671 Value *RV;
672 if (LHS.getVal()->getType()->isFloatingPoint())
673 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
674 else if (E->getType()->isUnsignedIntegerType())
675 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
676 else
677 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
678 return RValue::get(RV);
679 }
680 assert(0 && "FIXME: This doesn't handle complex operands yet");
681}
682
683RValue CodeGenFunction::EmitBinaryRem(const BinaryOperator *E) {
684 RValue LHS, RHS;
685 EmitUsualArithmeticConversions(E, LHS, RHS);
686
687 if (LHS.isScalar()) {
688 Value *RV;
689 // Rem in C can't be a floating point type: C99 6.5.5p2.
690 if (E->getType()->isUnsignedIntegerType())
691 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
692 else
693 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
694 return RValue::get(RV);
695 }
696
697 assert(0 && "FIXME: This doesn't handle complex operands yet");
698}
699
700RValue CodeGenFunction::EmitBinaryAdd(const BinaryOperator *E) {
701 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000702 EmitUsualArithmeticConversions(E, LHS, RHS);
703
Chris Lattner8394d792007-06-05 20:53:16 +0000704 // FIXME: This doesn't handle ptr+int etc yet.
705
706 if (LHS.isScalar())
707 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
708
709 assert(0 && "FIXME: This doesn't handle complex operands yet");
710
711}
712
713RValue CodeGenFunction::EmitBinarySub(const BinaryOperator *E) {
714 RValue LHS, RHS;
715 EmitUsualArithmeticConversions(E, LHS, RHS);
716
717 // FIXME: This doesn't handle ptr-int or ptr-ptr, etc yet.
718
719 if (LHS.isScalar())
720 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
721
722 assert(0 && "FIXME: This doesn't handle complex operands yet");
723
724}
725
726RValue CodeGenFunction::EmitBinaryShl(const BinaryOperator *E) {
727 // For shifts, integer promotions are performed, but the usual arithmetic
728 // conversions are not. The LHS and RHS need not have the same type.
729
730 QualType ResTy;
731 Value *LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy).getVal();
732 Value *RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy).getVal();
733
734 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
735 // RHS to the same size as the LHS.
736 if (LHS->getType() != RHS->getType())
737 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
738
739 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
740}
741
742RValue CodeGenFunction::EmitBinaryShr(const BinaryOperator *E) {
743 // For shifts, integer promotions are performed, but the usual arithmetic
744 // conversions are not. The LHS and RHS need not have the same type.
745
746 QualType ResTy;
747 Value *LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy).getVal();
748 Value *RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy).getVal();
749
750 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
751 // RHS to the same size as the LHS.
752 if (LHS->getType() != RHS->getType())
753 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
754
755 if (E->getType()->isUnsignedIntegerType())
756 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
757 else
758 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
759}
760
761RValue CodeGenFunction::EmitBinaryAnd(const BinaryOperator *E) {
762 RValue LHS, RHS;
763 EmitUsualArithmeticConversions(E, LHS, RHS);
764
765 if (LHS.isScalar())
766 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
767
768 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
769}
770
771RValue CodeGenFunction::EmitBinaryXor(const BinaryOperator *E) {
772 RValue LHS, RHS;
773 EmitUsualArithmeticConversions(E, LHS, RHS);
774
775 if (LHS.isScalar())
776 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
777
778 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
779}
780
781RValue CodeGenFunction::EmitBinaryOr(const BinaryOperator *E) {
782 RValue LHS, RHS;
783 EmitUsualArithmeticConversions(E, LHS, RHS);
784
785 if (LHS.isScalar())
786 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
787
788 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
789}
790
791RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
792 Value *LHSCond = EvaluateExprAsBool(E->getLHS());
793
794 BasicBlock *ContBlock = new BasicBlock("land_cont");
795 BasicBlock *RHSBlock = new BasicBlock("land_rhs");
796
797 BasicBlock *OrigBlock = Builder.GetInsertBlock();
798 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
799
800 EmitBlock(RHSBlock);
801 Value *RHSCond = EvaluateExprAsBool(E->getRHS());
802
803 // Reaquire the RHS block, as there may be subblocks inserted.
804 RHSBlock = Builder.GetInsertBlock();
805 EmitBlock(ContBlock);
806
807 // Create a PHI node. If we just evaluted the LHS condition, the result is
808 // false. If we evaluated both, the result is the RHS condition.
809 PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
810 PN->reserveOperandSpace(2);
811 PN->addIncoming(ConstantInt::getFalse(), OrigBlock);
812 PN->addIncoming(RHSCond, RHSBlock);
813
814 // ZExt result to int.
815 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
816}
817
818RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
819 Value *LHSCond = EvaluateExprAsBool(E->getLHS());
820
821 BasicBlock *ContBlock = new BasicBlock("lor_cont");
822 BasicBlock *RHSBlock = new BasicBlock("lor_rhs");
823
824 BasicBlock *OrigBlock = Builder.GetInsertBlock();
825 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
826
827 EmitBlock(RHSBlock);
828 Value *RHSCond = EvaluateExprAsBool(E->getRHS());
829
830 // Reaquire the RHS block, as there may be subblocks inserted.
831 RHSBlock = Builder.GetInsertBlock();
832 EmitBlock(ContBlock);
833
834 // Create a PHI node. If we just evaluted the LHS condition, the result is
835 // true. If we evaluated both, the result is the RHS condition.
836 PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
837 PN->reserveOperandSpace(2);
838 PN->addIncoming(ConstantInt::getTrue(), OrigBlock);
839 PN->addIncoming(RHSCond, RHSBlock);
840
841 // ZExt result to int.
842 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
843}
844
845RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
846 LValue LHS = EmitLValue(E->getLHS());
847
848 QualType RHSTy;
849 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
850
851 // Convert the RHS to the type of the LHS.
Chris Lattnercf106ab2007-06-06 04:05:39 +0000852 // FIXME: I'm not thrilled about having to call getLocStart() here... :(
853 RHS = EmitConversion(RHS, RHSTy, E->getType(), E->getLocStart());
Chris Lattner8394d792007-06-05 20:53:16 +0000854
855 // Store the value into the LHS.
856 EmitStoreThroughLValue(RHS, LHS, E->getType());
857
858 // Return the converted RHS.
859 return RHS;
860}
861
862
863RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
864 EmitExpr(E->getLHS());
865 return EmitExpr(E->getRHS());
866}