blob: 36ab0332cd9ab1049ff5b8f4b0ae3bb4ff7168aa [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
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 file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Expr.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/IdentifierTable.h"
18using namespace clang;
19
20//===----------------------------------------------------------------------===//
21// Primary Expressions.
22//===----------------------------------------------------------------------===//
23
24StringLiteral::StringLiteral(const char *strData, unsigned byteLength,
25 bool Wide, QualType t, SourceLocation firstLoc,
26 SourceLocation lastLoc) :
27 Expr(StringLiteralClass, t) {
28 // OPTIMIZE: could allocate this appended to the StringLiteral.
29 char *AStrData = new char[byteLength];
30 memcpy(AStrData, strData, byteLength);
31 StrData = AStrData;
32 ByteLength = byteLength;
33 IsWide = Wide;
34 firstTokLoc = firstLoc;
35 lastTokLoc = lastLoc;
36}
37
38StringLiteral::~StringLiteral() {
39 delete[] StrData;
40}
41
42bool UnaryOperator::isPostfix(Opcode Op) {
43 switch (Op) {
44 case PostInc:
45 case PostDec:
46 return true;
47 default:
48 return false;
49 }
50}
51
52/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
53/// corresponds to, e.g. "sizeof" or "[pre]++".
54const char *UnaryOperator::getOpcodeStr(Opcode Op) {
55 switch (Op) {
56 default: assert(0 && "Unknown unary operator");
57 case PostInc: return "++";
58 case PostDec: return "--";
59 case PreInc: return "++";
60 case PreDec: return "--";
61 case AddrOf: return "&";
62 case Deref: return "*";
63 case Plus: return "+";
64 case Minus: return "-";
65 case Not: return "~";
66 case LNot: return "!";
67 case Real: return "__real";
68 case Imag: return "__imag";
69 case SizeOf: return "sizeof";
70 case AlignOf: return "alignof";
71 case Extension: return "__extension__";
72 }
73}
74
75//===----------------------------------------------------------------------===//
76// Postfix Operators.
77//===----------------------------------------------------------------------===//
78
79CallExpr::CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
80 SourceLocation rparenloc)
81 : Expr(CallExprClass, t), Fn(fn), NumArgs(numargs) {
82 Args = new Expr*[numargs];
83 for (unsigned i = 0; i != numargs; ++i)
84 Args[i] = args[i];
85 RParenLoc = rparenloc;
86}
87
88/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
89/// corresponds to, e.g. "<<=".
90const char *BinaryOperator::getOpcodeStr(Opcode Op) {
91 switch (Op) {
92 default: assert(0 && "Unknown binary operator");
93 case Mul: return "*";
94 case Div: return "/";
95 case Rem: return "%";
96 case Add: return "+";
97 case Sub: return "-";
98 case Shl: return "<<";
99 case Shr: return ">>";
100 case LT: return "<";
101 case GT: return ">";
102 case LE: return "<=";
103 case GE: return ">=";
104 case EQ: return "==";
105 case NE: return "!=";
106 case And: return "&";
107 case Xor: return "^";
108 case Or: return "|";
109 case LAnd: return "&&";
110 case LOr: return "||";
111 case Assign: return "=";
112 case MulAssign: return "*=";
113 case DivAssign: return "/=";
114 case RemAssign: return "%=";
115 case AddAssign: return "+=";
116 case SubAssign: return "-=";
117 case ShlAssign: return "<<=";
118 case ShrAssign: return ">>=";
119 case AndAssign: return "&=";
120 case XorAssign: return "^=";
121 case OrAssign: return "|=";
122 case Comma: return ",";
123 }
124}
125
126
127//===----------------------------------------------------------------------===//
128// Generic Expression Routines
129//===----------------------------------------------------------------------===//
130
131/// hasLocalSideEffect - Return true if this immediate expression has side
132/// effects, not counting any sub-expressions.
133bool Expr::hasLocalSideEffect() const {
134 switch (getStmtClass()) {
135 default:
136 return false;
137 case ParenExprClass:
138 return cast<ParenExpr>(this)->getSubExpr()->hasLocalSideEffect();
139 case UnaryOperatorClass: {
140 const UnaryOperator *UO = cast<UnaryOperator>(this);
141
142 switch (UO->getOpcode()) {
143 default: return false;
144 case UnaryOperator::PostInc:
145 case UnaryOperator::PostDec:
146 case UnaryOperator::PreInc:
147 case UnaryOperator::PreDec:
148 return true; // ++/--
149
150 case UnaryOperator::Deref:
151 // Dereferencing a volatile pointer is a side-effect.
152 return getType().isVolatileQualified();
153 case UnaryOperator::Real:
154 case UnaryOperator::Imag:
155 // accessing a piece of a volatile complex is a side-effect.
156 return UO->getSubExpr()->getType().isVolatileQualified();
157
158 case UnaryOperator::Extension:
159 return UO->getSubExpr()->hasLocalSideEffect();
160 }
161 }
162 case BinaryOperatorClass:
163 return cast<BinaryOperator>(this)->isAssignmentOp();
164
165 case MemberExprClass:
166 case ArraySubscriptExprClass:
167 // If the base pointer or element is to a volatile pointer/field, accessing
168 // if is a side effect.
169 return getType().isVolatileQualified();
170
171 case CallExprClass:
172 // TODO: check attributes for pure/const. "void foo() { strlen("bar"); }"
173 // should warn.
174 return true;
175
176 case CastExprClass:
177 // If this is a cast to void, check the operand. Otherwise, the result of
178 // the cast is unused.
179 if (getType()->isVoidType())
180 return cast<CastExpr>(this)->getSubExpr()->hasLocalSideEffect();
181 return false;
182 }
183}
184
185/// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an
186/// incomplete type other than void. Nonarray expressions that can be lvalues:
187/// - name, where name must be a variable
188/// - e[i]
189/// - (e), where e must be an lvalue
190/// - e.name, where e must be an lvalue
191/// - e->name
192/// - *e, the type of e cannot be a function type
193/// - string-constant
194/// - reference type [C++ [expr]]
195///
196Expr::isLvalueResult Expr::isLvalue() const {
197 // first, check the type (C99 6.3.2.1)
198 if (TR->isFunctionType()) // from isObjectType()
199 return LV_NotObjectType;
200
201 if (TR->isVoidType())
202 return LV_IncompleteVoidType;
203
204 if (TR->isReferenceType()) // C++ [expr]
205 return LV_Valid;
206
207 // the type looks fine, now check the expression
208 switch (getStmtClass()) {
209 case StringLiteralClass: // C99 6.5.1p4
210 case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2))))
211 // For vectors, make sure base is an lvalue (i.e. not a function call).
212 if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType())
213 return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue();
214 return LV_Valid;
215 case DeclRefExprClass: // C99 6.5.1p2
216 if (isa<VarDecl>(cast<DeclRefExpr>(this)->getDecl()))
217 return LV_Valid;
218 break;
219 case MemberExprClass: { // C99 6.5.2.3p4
220 const MemberExpr *m = cast<MemberExpr>(this);
221 return m->isArrow() ? LV_Valid : m->getBase()->isLvalue();
222 }
223 case UnaryOperatorClass: // C99 6.5.3p4
224 if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref)
225 return LV_Valid;
226 break;
227 case ParenExprClass: // C99 6.5.1p5
228 return cast<ParenExpr>(this)->getSubExpr()->isLvalue();
Steve Naroffba67f692007-07-30 03:29:09 +0000229 case OCUVectorComponentClass:
230 if (cast<OCUVectorComponent>(this)->containsDuplicateComponents())
231 return LV_DuplicateVectorComponents;
232 return LV_Valid;
Chris Lattner4b009652007-07-25 00:24:17 +0000233 default:
234 break;
235 }
236 return LV_InvalidExpression;
237}
238
239/// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
240/// does not have an incomplete type, does not have a const-qualified type, and
241/// if it is a structure or union, does not have any member (including,
242/// recursively, any member or element of all contained aggregates or unions)
243/// with a const-qualified type.
244Expr::isModifiableLvalueResult Expr::isModifiableLvalue() const {
245 isLvalueResult lvalResult = isLvalue();
246
247 switch (lvalResult) {
248 case LV_Valid: break;
249 case LV_NotObjectType: return MLV_NotObjectType;
250 case LV_IncompleteVoidType: return MLV_IncompleteVoidType;
Steve Naroffba67f692007-07-30 03:29:09 +0000251 case LV_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
Chris Lattner4b009652007-07-25 00:24:17 +0000252 case LV_InvalidExpression: return MLV_InvalidExpression;
253 }
254 if (TR.isConstQualified())
255 return MLV_ConstQualified;
256 if (TR->isArrayType())
257 return MLV_ArrayType;
258 if (TR->isIncompleteType())
259 return MLV_IncompleteType;
260
261 if (const RecordType *r = dyn_cast<RecordType>(TR.getCanonicalType())) {
262 if (r->hasConstFields())
263 return MLV_ConstQualified;
264 }
265 return MLV_Valid;
266}
267
268/// isIntegerConstantExpr - this recursive routine will test if an expression is
269/// an integer constant expression. Note: With the introduction of VLA's in
270/// C99 the result of the sizeof operator is no longer always a constant
271/// expression. The generalization of the wording to include any subexpression
272/// that is not evaluated (C99 6.6p3) means that nonconstant subexpressions
273/// can appear as operands to other operators (e.g. &&, ||, ?:). For instance,
274/// "0 || f()" can be treated as a constant expression. In C90 this expression,
275/// occurring in a context requiring a constant, would have been a constraint
276/// violation. FIXME: This routine currently implements C90 semantics.
277/// To properly implement C99 semantics this routine will need to evaluate
278/// expressions involving operators previously mentioned.
279
280/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
281/// comma, etc
282///
283/// FIXME: This should ext-warn on overflow during evaluation! ISO C does not
284/// permit this.
285///
286/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
287/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
288/// cast+dereference.
289bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
290 SourceLocation *Loc, bool isEvaluated) const {
291 switch (getStmtClass()) {
292 default:
293 if (Loc) *Loc = getLocStart();
294 return false;
295 case ParenExprClass:
296 return cast<ParenExpr>(this)->getSubExpr()->
297 isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated);
298 case IntegerLiteralClass:
299 Result = cast<IntegerLiteral>(this)->getValue();
300 break;
301 case CharacterLiteralClass: {
302 const CharacterLiteral *CL = cast<CharacterLiteral>(this);
303 Result.zextOrTrunc(Ctx.getTypeSize(getType(), CL->getLoc()));
304 Result = CL->getValue();
305 Result.setIsUnsigned(!getType()->isSignedIntegerType());
306 break;
307 }
308 case DeclRefExprClass:
309 if (const EnumConstantDecl *D =
310 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(this)->getDecl())) {
311 Result = D->getInitVal();
312 break;
313 }
314 if (Loc) *Loc = getLocStart();
315 return false;
316 case UnaryOperatorClass: {
317 const UnaryOperator *Exp = cast<UnaryOperator>(this);
318
319 // Get the operand value. If this is sizeof/alignof, do not evalute the
320 // operand. This affects C99 6.6p3.
321 if (Exp->isSizeOfAlignOfOp()) isEvaluated = false;
322 if (!Exp->getSubExpr()->isIntegerConstantExpr(Result, Ctx,Loc, isEvaluated))
323 return false;
324
325 switch (Exp->getOpcode()) {
326 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
327 // See C99 6.6p3.
328 default:
329 if (Loc) *Loc = Exp->getOperatorLoc();
330 return false;
331 case UnaryOperator::Extension:
332 return true; // FIXME: this is wrong.
333 case UnaryOperator::SizeOf:
334 case UnaryOperator::AlignOf:
335 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
336 if (!Exp->getSubExpr()->getType()->isConstantSizeType(Ctx, Loc))
337 return false;
338
339 // Return the result in the right width.
340 Result.zextOrTrunc(Ctx.getTypeSize(getType(), Exp->getOperatorLoc()));
341
342 // Get information about the size or align.
343 if (Exp->getOpcode() == UnaryOperator::SizeOf)
344 Result = Ctx.getTypeSize(Exp->getSubExpr()->getType(),
345 Exp->getOperatorLoc());
346 else
347 Result = Ctx.getTypeAlign(Exp->getSubExpr()->getType(),
348 Exp->getOperatorLoc());
349 break;
350 case UnaryOperator::LNot: {
351 bool Val = Result != 0;
352 Result.zextOrTrunc(Ctx.getTypeSize(getType(), Exp->getOperatorLoc()));
353 Result = Val;
354 break;
355 }
356 case UnaryOperator::Plus:
357 break;
358 case UnaryOperator::Minus:
359 Result = -Result;
360 break;
361 case UnaryOperator::Not:
362 Result = ~Result;
363 break;
364 }
365 break;
366 }
367 case SizeOfAlignOfTypeExprClass: {
368 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(this);
369 // alignof always evaluates to a constant.
370 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType(Ctx,Loc))
371 return false;
372
373 // Return the result in the right width.
374 Result.zextOrTrunc(Ctx.getTypeSize(getType(), Exp->getOperatorLoc()));
375
376 // Get information about the size or align.
377 if (Exp->isSizeOf())
378 Result = Ctx.getTypeSize(Exp->getArgumentType(), Exp->getOperatorLoc());
379 else
380 Result = Ctx.getTypeAlign(Exp->getArgumentType(), Exp->getOperatorLoc());
381 break;
382 }
383 case BinaryOperatorClass: {
384 const BinaryOperator *Exp = cast<BinaryOperator>(this);
385
386 // The LHS of a constant expr is always evaluated and needed.
387 if (!Exp->getLHS()->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
388 return false;
389
390 llvm::APSInt RHS(Result);
391
392 // The short-circuiting &&/|| operators don't necessarily evaluate their
393 // RHS. Make sure to pass isEvaluated down correctly.
394 if (Exp->isLogicalOp()) {
395 bool RHSEval;
396 if (Exp->getOpcode() == BinaryOperator::LAnd)
397 RHSEval = Result != 0;
398 else {
399 assert(Exp->getOpcode() == BinaryOperator::LOr &&"Unexpected logical");
400 RHSEval = Result == 0;
401 }
402
403 if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Ctx, Loc,
404 isEvaluated & RHSEval))
405 return false;
406 } else {
407 if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Ctx, Loc, isEvaluated))
408 return false;
409 }
410
411 switch (Exp->getOpcode()) {
412 default:
413 if (Loc) *Loc = getLocStart();
414 return false;
415 case BinaryOperator::Mul:
416 Result *= RHS;
417 break;
418 case BinaryOperator::Div:
419 if (RHS == 0) {
420 if (!isEvaluated) break;
421 if (Loc) *Loc = getLocStart();
422 return false;
423 }
424 Result /= RHS;
425 break;
426 case BinaryOperator::Rem:
427 if (RHS == 0) {
428 if (!isEvaluated) break;
429 if (Loc) *Loc = getLocStart();
430 return false;
431 }
432 Result %= RHS;
433 break;
434 case BinaryOperator::Add: Result += RHS; break;
435 case BinaryOperator::Sub: Result -= RHS; break;
436 case BinaryOperator::Shl:
437 Result <<= RHS.getLimitedValue(Result.getBitWidth()-1);
438 break;
439 case BinaryOperator::Shr:
440 Result >>= RHS.getLimitedValue(Result.getBitWidth()-1);
441 break;
442 case BinaryOperator::LT: Result = Result < RHS; break;
443 case BinaryOperator::GT: Result = Result > RHS; break;
444 case BinaryOperator::LE: Result = Result <= RHS; break;
445 case BinaryOperator::GE: Result = Result >= RHS; break;
446 case BinaryOperator::EQ: Result = Result == RHS; break;
447 case BinaryOperator::NE: Result = Result != RHS; break;
448 case BinaryOperator::And: Result &= RHS; break;
449 case BinaryOperator::Xor: Result ^= RHS; break;
450 case BinaryOperator::Or: Result |= RHS; break;
451 case BinaryOperator::LAnd:
452 Result = Result != 0 && RHS != 0;
453 break;
454 case BinaryOperator::LOr:
455 Result = Result != 0 || RHS != 0;
456 break;
457
458 case BinaryOperator::Comma:
459 // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
460 // *except* when they are contained within a subexpression that is not
461 // evaluated". Note that Assignment can never happen due to constraints
462 // on the LHS subexpr, so we don't need to check it here.
463 if (isEvaluated) {
464 if (Loc) *Loc = getLocStart();
465 return false;
466 }
467
468 // The result of the constant expr is the RHS.
469 Result = RHS;
470 return true;
471 }
472
473 assert(!Exp->isAssignmentOp() && "LHS can't be a constant expr!");
474 break;
475 }
476 case ImplicitCastExprClass:
477 case CastExprClass: {
478 const Expr *SubExpr;
479 SourceLocation CastLoc;
480 if (const CastExpr *C = dyn_cast<CastExpr>(this)) {
481 SubExpr = C->getSubExpr();
482 CastLoc = C->getLParenLoc();
483 } else {
484 SubExpr = cast<ImplicitCastExpr>(this)->getSubExpr();
485 CastLoc = getLocStart();
486 }
487
488 // C99 6.6p6: shall only convert arithmetic types to integer types.
489 if (!SubExpr->getType()->isArithmeticType() ||
490 !getType()->isIntegerType()) {
491 if (Loc) *Loc = SubExpr->getLocStart();
492 return false;
493 }
494
495 // Handle simple integer->integer casts.
496 if (SubExpr->getType()->isIntegerType()) {
497 if (!SubExpr->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
498 return false;
499
500 // Figure out if this is a truncate, extend or noop cast.
501 unsigned DestWidth = Ctx.getTypeSize(getType(), CastLoc);
502
503 // If the input is signed, do a sign extend, noop, or truncate.
504 if (SubExpr->getType()->isSignedIntegerType())
505 Result.sextOrTrunc(DestWidth);
506 else // If the input is unsigned, do a zero extend, noop, or truncate.
507 Result.zextOrTrunc(DestWidth);
508 break;
509 }
510
511 // Allow floating constants that are the immediate operands of casts or that
512 // are parenthesized.
513 const Expr *Operand = SubExpr;
514 while (const ParenExpr *PE = dyn_cast<ParenExpr>(Operand))
515 Operand = PE->getSubExpr();
516
517 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(Operand)) {
518 // FIXME: Evaluate this correctly!
519 Result = (int)FL->getValue();
520 break;
521 }
522 if (Loc) *Loc = Operand->getLocStart();
523 return false;
524 }
525 case ConditionalOperatorClass: {
526 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
527
528 if (!Exp->getCond()->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
529 return false;
530
531 const Expr *TrueExp = Exp->getLHS();
532 const Expr *FalseExp = Exp->getRHS();
533 if (Result == 0) std::swap(TrueExp, FalseExp);
534
535 // Evaluate the false one first, discard the result.
536 if (!FalseExp->isIntegerConstantExpr(Result, Ctx, Loc, false))
537 return false;
538 // Evalute the true one, capture the result.
539 if (!TrueExp->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
540 return false;
541 break;
542 }
543 }
544
545 // Cases that are valid constant exprs fall through to here.
546 Result.setIsUnsigned(getType()->isUnsignedIntegerType());
547 return true;
548}
549
550
551/// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an
552/// integer constant expression with the value zero, or if this is one that is
553/// cast to void*.
554bool Expr::isNullPointerConstant(ASTContext &Ctx) const {
555 // Strip off a cast to void*, if it exists.
556 if (const CastExpr *CE = dyn_cast<CastExpr>(this)) {
557 // Check that it is a cast to void*.
558 if (const PointerType *PT = dyn_cast<PointerType>(CE->getType())) {
559 QualType Pointee = PT->getPointeeType();
560 if (Pointee.getQualifiers() == 0 && Pointee->isVoidType() && // to void*
561 CE->getSubExpr()->getType()->isIntegerType()) // from int.
562 return CE->getSubExpr()->isNullPointerConstant(Ctx);
563 }
564 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
565 // Accept ((void*)0) as a null pointer constant, as many other
566 // implementations do.
567 return PE->getSubExpr()->isNullPointerConstant(Ctx);
568 }
569
570 // This expression must be an integer type.
571 if (!getType()->isIntegerType())
572 return false;
573
574 // If we have an integer constant expression, we need to *evaluate* it and
575 // test for the value 0.
576 llvm::APSInt Val(32);
577 return isIntegerConstantExpr(Val, Ctx, 0, true) && Val == 0;
578}
Steve Naroffc11705f2007-07-28 23:10:27 +0000579
580OCUVectorComponent::ComponentType OCUVectorComponent::getComponentType() const {
581 // derive the component type, no need to waste space.
582 const char *compStr = Accessor.getName();
583 const OCUVectorType *VT = getType()->isOCUVectorType();
584 if (VT->isPointAccessor(*compStr)) return Point;
585 if (VT->isColorAccessor(*compStr)) return Color;
586 if (VT->isTextureAccessor(*compStr)) return Texture;
587 assert(0 && "getComponentType(): Illegal accessor");
588}
Steve Naroffba67f692007-07-30 03:29:09 +0000589
590bool OCUVectorComponent::containsDuplicateComponents() const {
591 const char *compStr = Accessor.getName();
592 unsigned length = strlen(compStr);
593
594 for (unsigned i = 0; i < length-1; i++) {
595 const char *s = compStr+i;
596 for (const char c = *s++; *s; s++)
597 if (c == *s)
598 return true;
599 }
600 return false;
601}