Expr.cpp revision 45b6b9d080ac56917337d73d8f1cd6374b27b05d
1//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/APValue.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Basic/TargetInfo.h"
21using namespace clang;
22
23//===----------------------------------------------------------------------===//
24// Primary Expressions.
25//===----------------------------------------------------------------------===//
26
27/// getValueAsApproximateDouble - This returns the value as an inaccurate
28/// double.  Note that this may cause loss of precision, but is useful for
29/// debugging dumps, etc.
30double FloatingLiteral::getValueAsApproximateDouble() const {
31  llvm::APFloat V = getValue();
32  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven);
33  return V.convertToDouble();
34}
35
36
37StringLiteral::StringLiteral(const char *strData, unsigned byteLength,
38                             bool Wide, QualType t, SourceLocation firstLoc,
39                             SourceLocation lastLoc) :
40  Expr(StringLiteralClass, t) {
41  // OPTIMIZE: could allocate this appended to the StringLiteral.
42  char *AStrData = new char[byteLength];
43  memcpy(AStrData, strData, byteLength);
44  StrData = AStrData;
45  ByteLength = byteLength;
46  IsWide = Wide;
47  firstTokLoc = firstLoc;
48  lastTokLoc = lastLoc;
49}
50
51StringLiteral::~StringLiteral() {
52  delete[] StrData;
53}
54
55bool UnaryOperator::isPostfix(Opcode Op) {
56  switch (Op) {
57  case PostInc:
58  case PostDec:
59    return true;
60  default:
61    return false;
62  }
63}
64
65bool UnaryOperator::isPrefix(Opcode Op) {
66  switch (Op) {
67    case PreInc:
68    case PreDec:
69      return true;
70    default:
71      return false;
72  }
73}
74
75/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
76/// corresponds to, e.g. "sizeof" or "[pre]++".
77const char *UnaryOperator::getOpcodeStr(Opcode Op) {
78  switch (Op) {
79  default: assert(0 && "Unknown unary operator");
80  case PostInc: return "++";
81  case PostDec: return "--";
82  case PreInc:  return "++";
83  case PreDec:  return "--";
84  case AddrOf:  return "&";
85  case Deref:   return "*";
86  case Plus:    return "+";
87  case Minus:   return "-";
88  case Not:     return "~";
89  case LNot:    return "!";
90  case Real:    return "__real";
91  case Imag:    return "__imag";
92  case SizeOf:  return "sizeof";
93  case AlignOf: return "alignof";
94  case Extension: return "__extension__";
95  case OffsetOf: return "__builtin_offsetof";
96  }
97}
98
99//===----------------------------------------------------------------------===//
100// Postfix Operators.
101//===----------------------------------------------------------------------===//
102
103
104CallExpr::CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
105                   SourceLocation rparenloc)
106  : Expr(CallExprClass, t), NumArgs(numargs) {
107  SubExprs = new Stmt*[numargs+1];
108  SubExprs[FN] = fn;
109  for (unsigned i = 0; i != numargs; ++i)
110    SubExprs[i+ARGS_START] = args[i];
111  RParenLoc = rparenloc;
112}
113
114/// setNumArgs - This changes the number of arguments present in this call.
115/// Any orphaned expressions are deleted by this, and any new operands are set
116/// to null.
117void CallExpr::setNumArgs(unsigned NumArgs) {
118  // No change, just return.
119  if (NumArgs == getNumArgs()) return;
120
121  // If shrinking # arguments, just delete the extras and forgot them.
122  if (NumArgs < getNumArgs()) {
123    for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i)
124      delete getArg(i);
125    this->NumArgs = NumArgs;
126    return;
127  }
128
129  // Otherwise, we are growing the # arguments.  New an bigger argument array.
130  Stmt **NewSubExprs = new Stmt*[NumArgs+1];
131  // Copy over args.
132  for (unsigned i = 0; i != getNumArgs()+ARGS_START; ++i)
133    NewSubExprs[i] = SubExprs[i];
134  // Null out new args.
135  for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i)
136    NewSubExprs[i] = 0;
137
138  delete[] SubExprs;
139  SubExprs = NewSubExprs;
140  this->NumArgs = NumArgs;
141}
142
143/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
144/// not, return 0.
145unsigned CallExpr::isBuiltinCall() const {
146  // All simple function calls (e.g. func()) are implicitly cast to pointer to
147  // function. As a result, we try and obtain the DeclRefExpr from the
148  // ImplicitCastExpr.
149  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
150  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
151    return 0;
152
153  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
154  if (!DRE)
155    return 0;
156
157  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
158  if (!FDecl)
159    return 0;
160
161  return FDecl->getIdentifier()->getBuiltinID();
162}
163
164
165/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
166/// corresponds to, e.g. "<<=".
167const char *BinaryOperator::getOpcodeStr(Opcode Op) {
168  switch (Op) {
169  default: assert(0 && "Unknown binary operator");
170  case Mul:       return "*";
171  case Div:       return "/";
172  case Rem:       return "%";
173  case Add:       return "+";
174  case Sub:       return "-";
175  case Shl:       return "<<";
176  case Shr:       return ">>";
177  case LT:        return "<";
178  case GT:        return ">";
179  case LE:        return "<=";
180  case GE:        return ">=";
181  case EQ:        return "==";
182  case NE:        return "!=";
183  case And:       return "&";
184  case Xor:       return "^";
185  case Or:        return "|";
186  case LAnd:      return "&&";
187  case LOr:       return "||";
188  case Assign:    return "=";
189  case MulAssign: return "*=";
190  case DivAssign: return "/=";
191  case RemAssign: return "%=";
192  case AddAssign: return "+=";
193  case SubAssign: return "-=";
194  case ShlAssign: return "<<=";
195  case ShrAssign: return ">>=";
196  case AndAssign: return "&=";
197  case XorAssign: return "^=";
198  case OrAssign:  return "|=";
199  case Comma:     return ",";
200  }
201}
202
203InitListExpr::InitListExpr(SourceLocation lbraceloc,
204                           Expr **initexprs, unsigned numinits,
205                           SourceLocation rbraceloc)
206  : Expr(InitListExprClass, QualType()),
207    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc)
208{
209  for (unsigned i = 0; i != numinits; i++)
210    InitExprs.push_back(initexprs[i]);
211}
212
213/// getFunctionType - Return the underlying function type for this block.
214///
215const FunctionType *BlockExpr::getFunctionType() const {
216  return getType()->getAsBlockPointerType()->
217                    getPointeeType()->getAsFunctionType();
218}
219
220//===----------------------------------------------------------------------===//
221// Generic Expression Routines
222//===----------------------------------------------------------------------===//
223
224/// hasLocalSideEffect - Return true if this immediate expression has side
225/// effects, not counting any sub-expressions.
226bool Expr::hasLocalSideEffect() const {
227  switch (getStmtClass()) {
228  default:
229    return false;
230  case ParenExprClass:
231    return cast<ParenExpr>(this)->getSubExpr()->hasLocalSideEffect();
232  case UnaryOperatorClass: {
233    const UnaryOperator *UO = cast<UnaryOperator>(this);
234
235    switch (UO->getOpcode()) {
236    default: return false;
237    case UnaryOperator::PostInc:
238    case UnaryOperator::PostDec:
239    case UnaryOperator::PreInc:
240    case UnaryOperator::PreDec:
241      return true;                     // ++/--
242
243    case UnaryOperator::Deref:
244      // Dereferencing a volatile pointer is a side-effect.
245      return getType().isVolatileQualified();
246    case UnaryOperator::Real:
247    case UnaryOperator::Imag:
248      // accessing a piece of a volatile complex is a side-effect.
249      return UO->getSubExpr()->getType().isVolatileQualified();
250
251    case UnaryOperator::Extension:
252      return UO->getSubExpr()->hasLocalSideEffect();
253    }
254  }
255  case BinaryOperatorClass: {
256    const BinaryOperator *BinOp = cast<BinaryOperator>(this);
257    // Consider comma to have side effects if the LHS and RHS both do.
258    if (BinOp->getOpcode() == BinaryOperator::Comma)
259      return BinOp->getLHS()->hasLocalSideEffect() &&
260             BinOp->getRHS()->hasLocalSideEffect();
261
262    return BinOp->isAssignmentOp();
263  }
264  case CompoundAssignOperatorClass:
265    return true;
266
267  case ConditionalOperatorClass: {
268    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
269    return Exp->getCond()->hasLocalSideEffect()
270           || (Exp->getLHS() && Exp->getLHS()->hasLocalSideEffect())
271           || (Exp->getRHS() && Exp->getRHS()->hasLocalSideEffect());
272  }
273
274  case MemberExprClass:
275  case ArraySubscriptExprClass:
276    // If the base pointer or element is to a volatile pointer/field, accessing
277    // if is a side effect.
278    return getType().isVolatileQualified();
279
280  case CallExprClass:
281    // TODO: check attributes for pure/const.   "void foo() { strlen("bar"); }"
282    // should warn.
283    return true;
284  case ObjCMessageExprClass:
285    return true;
286  case StmtExprClass: {
287    // Statement exprs don't logically have side effects themselves, but are
288    // sometimes used in macros in ways that give them a type that is unused.
289    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
290    // however, if the result of the stmt expr is dead, we don't want to emit a
291    // warning.
292    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
293    if (!CS->body_empty())
294      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
295        return E->hasLocalSideEffect();
296    return false;
297  }
298  case ExplicitCastExprClass:
299  case CXXFunctionalCastExprClass:
300    // If this is a cast to void, check the operand.  Otherwise, the result of
301    // the cast is unused.
302    if (getType()->isVoidType())
303      return cast<CastExpr>(this)->getSubExpr()->hasLocalSideEffect();
304    return false;
305
306  case ImplicitCastExprClass:
307    // Check the operand, since implicit casts are inserted by Sema
308    return cast<ImplicitCastExpr>(this)->getSubExpr()->hasLocalSideEffect();
309
310  case CXXDefaultArgExprClass:
311    return cast<CXXDefaultArgExpr>(this)->getExpr()->hasLocalSideEffect();
312  }
313}
314
315/// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an
316/// incomplete type other than void. Nonarray expressions that can be lvalues:
317///  - name, where name must be a variable
318///  - e[i]
319///  - (e), where e must be an lvalue
320///  - e.name, where e must be an lvalue
321///  - e->name
322///  - *e, the type of e cannot be a function type
323///  - string-constant
324///  - (__real__ e) and (__imag__ e) where e is an lvalue  [GNU extension]
325///  - reference type [C++ [expr]]
326///
327Expr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const {
328  // first, check the type (C99 6.3.2.1)
329  if (TR->isFunctionType()) // from isObjectType()
330    return LV_NotObjectType;
331
332  // Allow qualified void which is an incomplete type other than void (yuck).
333  if (TR->isVoidType() && !Ctx.getCanonicalType(TR).getCVRQualifiers())
334    return LV_IncompleteVoidType;
335
336  if (TR->isReferenceType()) // C++ [expr]
337    return LV_Valid;
338
339  // the type looks fine, now check the expression
340  switch (getStmtClass()) {
341  case StringLiteralClass: // C99 6.5.1p4
342    return LV_Valid;
343  case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2))))
344    // For vectors, make sure base is an lvalue (i.e. not a function call).
345    if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType())
346      return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue(Ctx);
347    return LV_Valid;
348  case DeclRefExprClass: { // C99 6.5.1p2
349    const Decl *RefdDecl = cast<DeclRefExpr>(this)->getDecl();
350    if (isa<VarDecl>(RefdDecl) || isa<ImplicitParamDecl>(RefdDecl))
351      return LV_Valid;
352    break;
353  }
354  case BlockDeclRefExprClass: {
355    const BlockDeclRefExpr *BDR = cast<BlockDeclRefExpr>(this);
356    if (isa<VarDecl>(BDR->getDecl()))
357      return LV_Valid;
358    break;
359  }
360  case MemberExprClass: { // C99 6.5.2.3p4
361    const MemberExpr *m = cast<MemberExpr>(this);
362    return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx);
363  }
364  case UnaryOperatorClass:
365    if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref)
366      return LV_Valid; // C99 6.5.3p4
367
368    if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Real ||
369        cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Imag ||
370        cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Extension)
371      return cast<UnaryOperator>(this)->getSubExpr()->isLvalue(Ctx);  // GNU.
372    break;
373  case ParenExprClass: // C99 6.5.1p5
374    return cast<ParenExpr>(this)->getSubExpr()->isLvalue(Ctx);
375  case CompoundLiteralExprClass: // C99 6.5.2.5p5
376    return LV_Valid;
377  case ExtVectorElementExprClass:
378    if (cast<ExtVectorElementExpr>(this)->containsDuplicateElements())
379      return LV_DuplicateVectorComponents;
380    return LV_Valid;
381  case ObjCIvarRefExprClass: // ObjC instance variables are lvalues.
382    return LV_Valid;
383  case ObjCPropertyRefExprClass: // FIXME: check if read-only property.
384    return LV_Valid;
385  case PredefinedExprClass:
386    return (cast<PredefinedExpr>(this)->getIdentType()
387               == PredefinedExpr::CXXThis
388            ? LV_InvalidExpression : LV_Valid);
389  case CXXDefaultArgExprClass:
390    return cast<CXXDefaultArgExpr>(this)->getExpr()->isLvalue(Ctx);
391  case CXXConditionDeclExprClass:
392    return LV_Valid;
393  default:
394    break;
395  }
396  return LV_InvalidExpression;
397}
398
399/// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
400/// does not have an incomplete type, does not have a const-qualified type, and
401/// if it is a structure or union, does not have any member (including,
402/// recursively, any member or element of all contained aggregates or unions)
403/// with a const-qualified type.
404Expr::isModifiableLvalueResult Expr::isModifiableLvalue(ASTContext &Ctx) const {
405  isLvalueResult lvalResult = isLvalue(Ctx);
406
407  switch (lvalResult) {
408  case LV_Valid: break;
409  case LV_NotObjectType: return MLV_NotObjectType;
410  case LV_IncompleteVoidType: return MLV_IncompleteVoidType;
411  case LV_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
412  case LV_InvalidExpression: return MLV_InvalidExpression;
413  }
414
415  QualType CT = Ctx.getCanonicalType(getType());
416
417  if (CT.isConstQualified())
418    return MLV_ConstQualified;
419  if (CT->isArrayType())
420    return MLV_ArrayType;
421  if (CT->isIncompleteType())
422    return MLV_IncompleteType;
423
424  if (const RecordType *r = CT->getAsRecordType()) {
425    if (r->hasConstFields())
426      return MLV_ConstQualified;
427  }
428  // The following is illegal:
429  //   void takeclosure(void (^C)(void));
430  //   void func() { int x = 1; takeclosure(^{ x = 7 }); }
431  //
432  if (getStmtClass() == BlockDeclRefExprClass) {
433    const BlockDeclRefExpr *BDR = cast<BlockDeclRefExpr>(this);
434    if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
435      return MLV_NotBlockQualified;
436  }
437  return MLV_Valid;
438}
439
440/// hasGlobalStorage - Return true if this expression has static storage
441/// duration.  This means that the address of this expression is a link-time
442/// constant.
443bool Expr::hasGlobalStorage() const {
444  switch (getStmtClass()) {
445  default:
446    return false;
447  case ParenExprClass:
448    return cast<ParenExpr>(this)->getSubExpr()->hasGlobalStorage();
449  case ImplicitCastExprClass:
450    return cast<ImplicitCastExpr>(this)->getSubExpr()->hasGlobalStorage();
451  case CompoundLiteralExprClass:
452    return cast<CompoundLiteralExpr>(this)->isFileScope();
453  case DeclRefExprClass: {
454    const Decl *D = cast<DeclRefExpr>(this)->getDecl();
455    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
456      return VD->hasGlobalStorage();
457    if (isa<FunctionDecl>(D))
458      return true;
459    return false;
460  }
461  case MemberExprClass: {
462    const MemberExpr *M = cast<MemberExpr>(this);
463    return !M->isArrow() && M->getBase()->hasGlobalStorage();
464  }
465  case ArraySubscriptExprClass:
466    return cast<ArraySubscriptExpr>(this)->getBase()->hasGlobalStorage();
467  case PredefinedExprClass:
468    return true;
469  case CXXDefaultArgExprClass:
470    return cast<CXXDefaultArgExpr>(this)->getExpr()->hasGlobalStorage();
471  }
472}
473
474Expr* Expr::IgnoreParens() {
475  Expr* E = this;
476  while (ParenExpr* P = dyn_cast<ParenExpr>(E))
477    E = P->getSubExpr();
478
479  return E;
480}
481
482/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
483/// or CastExprs or ImplicitCastExprs, returning their operand.
484Expr *Expr::IgnoreParenCasts() {
485  Expr *E = this;
486  while (true) {
487    if (ParenExpr *P = dyn_cast<ParenExpr>(E))
488      E = P->getSubExpr();
489    else if (CastExpr *P = dyn_cast<CastExpr>(E))
490      E = P->getSubExpr();
491    else
492      return E;
493  }
494}
495
496
497bool Expr::isConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
498  switch (getStmtClass()) {
499  default:
500    if (Loc) *Loc = getLocStart();
501    return false;
502  case ParenExprClass:
503    return cast<ParenExpr>(this)->getSubExpr()->isConstantExpr(Ctx, Loc);
504  case StringLiteralClass:
505  case ObjCStringLiteralClass:
506  case FloatingLiteralClass:
507  case IntegerLiteralClass:
508  case CharacterLiteralClass:
509  case ImaginaryLiteralClass:
510  case TypesCompatibleExprClass:
511  case CXXBoolLiteralExprClass:
512  case AddrLabelExprClass:
513    return true;
514  case CallExprClass: {
515    const CallExpr *CE = cast<CallExpr>(this);
516
517    // Allow any constant foldable calls to builtins.
518    if (CE->isBuiltinCall() && CE->isEvaluatable(Ctx))
519      return true;
520
521    if (Loc) *Loc = getLocStart();
522    return false;
523  }
524  case DeclRefExprClass: {
525    const Decl *D = cast<DeclRefExpr>(this)->getDecl();
526    // Accept address of function.
527    if (isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D))
528      return true;
529    if (Loc) *Loc = getLocStart();
530    if (isa<VarDecl>(D))
531      return TR->isArrayType();
532    return false;
533  }
534  case CompoundLiteralExprClass:
535    if (Loc) *Loc = getLocStart();
536    // Allow "(int []){2,4}", since the array will be converted to a pointer.
537    // Allow "(vector type){2,4}" since the elements are all constant.
538    return TR->isArrayType() || TR->isVectorType();
539  case UnaryOperatorClass: {
540    const UnaryOperator *Exp = cast<UnaryOperator>(this);
541
542    // C99 6.6p9
543    if (Exp->getOpcode() == UnaryOperator::AddrOf) {
544      if (!Exp->getSubExpr()->hasGlobalStorage()) {
545        if (Loc) *Loc = getLocStart();
546        return false;
547      }
548      return true;
549    }
550
551    // Get the operand value.  If this is sizeof/alignof, do not evalute the
552    // operand.  This affects C99 6.6p3.
553    if (!Exp->isSizeOfAlignOfOp() &&
554        Exp->getOpcode() != UnaryOperator::OffsetOf &&
555        !Exp->getSubExpr()->isConstantExpr(Ctx, Loc))
556      return false;
557
558    switch (Exp->getOpcode()) {
559    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
560    // See C99 6.6p3.
561    default:
562      if (Loc) *Loc = Exp->getOperatorLoc();
563      return false;
564    case UnaryOperator::Extension:
565      return true;  // FIXME: this is wrong.
566    case UnaryOperator::SizeOf:
567    case UnaryOperator::AlignOf:
568    case UnaryOperator::OffsetOf:
569      // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
570      if (!Exp->getSubExpr()->getType()->isConstantSizeType()) {
571        if (Loc) *Loc = Exp->getOperatorLoc();
572        return false;
573      }
574      return true;
575    case UnaryOperator::LNot:
576    case UnaryOperator::Plus:
577    case UnaryOperator::Minus:
578    case UnaryOperator::Not:
579      return true;
580    }
581  }
582  case SizeOfAlignOfTypeExprClass: {
583    const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(this);
584    // alignof always evaluates to a constant.
585    if (Exp->isSizeOf() && !Exp->getArgumentType()->isVoidType() &&
586        !Exp->getArgumentType()->isConstantSizeType()) {
587      if (Loc) *Loc = Exp->getOperatorLoc();
588      return false;
589    }
590    return true;
591  }
592  case BinaryOperatorClass: {
593    const BinaryOperator *Exp = cast<BinaryOperator>(this);
594
595    // The LHS of a constant expr is always evaluated and needed.
596    if (!Exp->getLHS()->isConstantExpr(Ctx, Loc))
597      return false;
598
599    if (!Exp->getRHS()->isConstantExpr(Ctx, Loc))
600      return false;
601    return true;
602  }
603  case ImplicitCastExprClass:
604  case ExplicitCastExprClass:
605  case CXXFunctionalCastExprClass: {
606    const Expr *SubExpr = cast<CastExpr>(this)->getSubExpr();
607    SourceLocation CastLoc = getLocStart();
608    if (!SubExpr->isConstantExpr(Ctx, Loc)) {
609      if (Loc) *Loc = SubExpr->getLocStart();
610      return false;
611    }
612    return true;
613  }
614  case ConditionalOperatorClass: {
615    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
616    if (!Exp->getCond()->isConstantExpr(Ctx, Loc) ||
617        // Handle the GNU extension for missing LHS.
618        !(Exp->getLHS() && Exp->getLHS()->isConstantExpr(Ctx, Loc)) ||
619        !Exp->getRHS()->isConstantExpr(Ctx, Loc))
620      return false;
621    return true;
622  }
623  case InitListExprClass: {
624    const InitListExpr *Exp = cast<InitListExpr>(this);
625    unsigned numInits = Exp->getNumInits();
626    for (unsigned i = 0; i < numInits; i++) {
627      if (!Exp->getInit(i)->isConstantExpr(Ctx, Loc)) {
628        if (Loc) *Loc = Exp->getInit(i)->getLocStart();
629        return false;
630      }
631    }
632    return true;
633  }
634  case CXXDefaultArgExprClass:
635    return cast<CXXDefaultArgExpr>(this)->getExpr()->isConstantExpr(Ctx, Loc);
636  }
637}
638
639/// isIntegerConstantExpr - this recursive routine will test if an expression is
640/// an integer constant expression. Note: With the introduction of VLA's in
641/// C99 the result of the sizeof operator is no longer always a constant
642/// expression. The generalization of the wording to include any subexpression
643/// that is not evaluated (C99 6.6p3) means that nonconstant subexpressions
644/// can appear as operands to other operators (e.g. &&, ||, ?:). For instance,
645/// "0 || f()" can be treated as a constant expression. In C90 this expression,
646/// occurring in a context requiring a constant, would have been a constraint
647/// violation. FIXME: This routine currently implements C90 semantics.
648/// To properly implement C99 semantics this routine will need to evaluate
649/// expressions involving operators previously mentioned.
650
651/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
652/// comma, etc
653///
654/// FIXME: This should ext-warn on overflow during evaluation!  ISO C does not
655/// permit this.  This includes things like (int)1e1000
656///
657/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
658/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
659/// cast+dereference.
660bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
661                                 SourceLocation *Loc, bool isEvaluated) const {
662  switch (getStmtClass()) {
663  default:
664    if (Loc) *Loc = getLocStart();
665    return false;
666  case ParenExprClass:
667    return cast<ParenExpr>(this)->getSubExpr()->
668                     isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated);
669  case IntegerLiteralClass:
670    Result = cast<IntegerLiteral>(this)->getValue();
671    break;
672  case CharacterLiteralClass: {
673    const CharacterLiteral *CL = cast<CharacterLiteral>(this);
674    Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
675    Result = CL->getValue();
676    Result.setIsUnsigned(!getType()->isSignedIntegerType());
677    break;
678  }
679  case CXXBoolLiteralExprClass: {
680    const CXXBoolLiteralExpr *BL = cast<CXXBoolLiteralExpr>(this);
681    Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
682    Result = BL->getValue();
683    Result.setIsUnsigned(!getType()->isSignedIntegerType());
684    break;
685  }
686  case CXXZeroInitValueExprClass:
687    Result.clear();
688    break;
689  case TypesCompatibleExprClass: {
690    const TypesCompatibleExpr *TCE = cast<TypesCompatibleExpr>(this);
691    Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
692    Result = Ctx.typesAreCompatible(TCE->getArgType1(), TCE->getArgType2());
693    break;
694  }
695  case CallExprClass: {
696    const CallExpr *CE = cast<CallExpr>(this);
697    Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
698
699    // If this is a call to a builtin function, constant fold it otherwise
700    // reject it.
701    if (CE->isBuiltinCall()) {
702      APValue ResultAP;
703      if (CE->tryEvaluate(ResultAP, Ctx)) {
704        Result = ResultAP.getInt();
705        break;  // It is a constant, expand it.
706      }
707    }
708
709    if (Loc) *Loc = getLocStart();
710    return false;
711  }
712  case DeclRefExprClass:
713    if (const EnumConstantDecl *D =
714          dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(this)->getDecl())) {
715      Result = D->getInitVal();
716      break;
717    }
718    if (Loc) *Loc = getLocStart();
719    return false;
720  case UnaryOperatorClass: {
721    const UnaryOperator *Exp = cast<UnaryOperator>(this);
722
723    // Get the operand value.  If this is sizeof/alignof, do not evalute the
724    // operand.  This affects C99 6.6p3.
725    if (!Exp->isSizeOfAlignOfOp() && !Exp->isOffsetOfOp() &&
726        !Exp->getSubExpr()->isIntegerConstantExpr(Result, Ctx, Loc,isEvaluated))
727      return false;
728
729    switch (Exp->getOpcode()) {
730    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
731    // See C99 6.6p3.
732    default:
733      if (Loc) *Loc = Exp->getOperatorLoc();
734      return false;
735    case UnaryOperator::Extension:
736      return true;  // FIXME: this is wrong.
737    case UnaryOperator::SizeOf:
738    case UnaryOperator::AlignOf:
739      // Return the result in the right width.
740      Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
741
742      // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
743      if (Exp->getSubExpr()->getType()->isVoidType()) {
744        Result = 1;
745        break;
746      }
747
748      // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
749      if (!Exp->getSubExpr()->getType()->isConstantSizeType()) {
750        if (Loc) *Loc = Exp->getOperatorLoc();
751        return false;
752      }
753
754      // Get information about the size or align.
755      if (Exp->getSubExpr()->getType()->isFunctionType()) {
756        // GCC extension: sizeof(function) = 1.
757        Result = Exp->getOpcode() == UnaryOperator::AlignOf ? 4 : 1;
758      } else {
759        unsigned CharSize = Ctx.Target.getCharWidth();
760        if (Exp->getOpcode() == UnaryOperator::AlignOf)
761          Result = Ctx.getTypeAlign(Exp->getSubExpr()->getType()) / CharSize;
762        else
763          Result = Ctx.getTypeSize(Exp->getSubExpr()->getType()) / CharSize;
764      }
765      break;
766    case UnaryOperator::LNot: {
767      bool Val = Result == 0;
768      Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
769      Result = Val;
770      break;
771    }
772    case UnaryOperator::Plus:
773      break;
774    case UnaryOperator::Minus:
775      Result = -Result;
776      break;
777    case UnaryOperator::Not:
778      Result = ~Result;
779      break;
780    case UnaryOperator::OffsetOf:
781      Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
782      Result = Exp->evaluateOffsetOf(Ctx);
783    }
784    break;
785  }
786  case SizeOfAlignOfTypeExprClass: {
787    const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(this);
788
789    // Return the result in the right width.
790    Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(getType())));
791
792    // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
793    if (Exp->getArgumentType()->isVoidType()) {
794      Result = 1;
795      break;
796    }
797
798    // alignof always evaluates to a constant, sizeof does if arg is not VLA.
799    if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
800      if (Loc) *Loc = Exp->getOperatorLoc();
801      return false;
802    }
803
804    // Get information about the size or align.
805    if (Exp->getArgumentType()->isFunctionType()) {
806      // GCC extension: sizeof(function) = 1.
807      Result = Exp->isSizeOf() ? 1 : 4;
808    } else {
809      unsigned CharSize = Ctx.Target.getCharWidth();
810      if (Exp->isSizeOf())
811        Result = Ctx.getTypeSize(Exp->getArgumentType()) / CharSize;
812      else
813        Result = Ctx.getTypeAlign(Exp->getArgumentType()) / CharSize;
814    }
815    break;
816  }
817  case BinaryOperatorClass: {
818    const BinaryOperator *Exp = cast<BinaryOperator>(this);
819    llvm::APSInt LHS, RHS;
820
821    // Initialize result to have correct signedness and width.
822    Result = llvm::APSInt(static_cast<uint32_t>(Ctx.getTypeSize(getType())),
823                          !getType()->isSignedIntegerType());
824
825    // The LHS of a constant expr is always evaluated and needed.
826    if (!Exp->getLHS()->isIntegerConstantExpr(LHS, Ctx, Loc, isEvaluated))
827      return false;
828
829    // The short-circuiting &&/|| operators don't necessarily evaluate their
830    // RHS.  Make sure to pass isEvaluated down correctly.
831    if (Exp->isLogicalOp()) {
832      bool RHSEval;
833      if (Exp->getOpcode() == BinaryOperator::LAnd)
834        RHSEval = LHS != 0;
835      else {
836        assert(Exp->getOpcode() == BinaryOperator::LOr &&"Unexpected logical");
837        RHSEval = LHS == 0;
838      }
839
840      if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Ctx, Loc,
841                                                isEvaluated & RHSEval))
842        return false;
843    } else {
844      if (!Exp->getRHS()->isIntegerConstantExpr(RHS, Ctx, Loc, isEvaluated))
845        return false;
846    }
847
848    switch (Exp->getOpcode()) {
849    default:
850      if (Loc) *Loc = getLocStart();
851      return false;
852    case BinaryOperator::Mul:
853      Result = LHS * RHS;
854      break;
855    case BinaryOperator::Div:
856      if (RHS == 0) {
857        if (!isEvaluated) break;
858        if (Loc) *Loc = getLocStart();
859        return false;
860      }
861      Result = LHS / RHS;
862      break;
863    case BinaryOperator::Rem:
864      if (RHS == 0) {
865        if (!isEvaluated) break;
866        if (Loc) *Loc = getLocStart();
867        return false;
868      }
869      Result = LHS % RHS;
870      break;
871    case BinaryOperator::Add: Result = LHS + RHS; break;
872    case BinaryOperator::Sub: Result = LHS - RHS; break;
873    case BinaryOperator::Shl:
874      Result = LHS <<
875        static_cast<uint32_t>(RHS.getLimitedValue(LHS.getBitWidth()-1));
876    break;
877    case BinaryOperator::Shr:
878      Result = LHS >>
879        static_cast<uint32_t>(RHS.getLimitedValue(LHS.getBitWidth()-1));
880      break;
881    case BinaryOperator::LT:  Result = LHS < RHS; break;
882    case BinaryOperator::GT:  Result = LHS > RHS; break;
883    case BinaryOperator::LE:  Result = LHS <= RHS; break;
884    case BinaryOperator::GE:  Result = LHS >= RHS; break;
885    case BinaryOperator::EQ:  Result = LHS == RHS; break;
886    case BinaryOperator::NE:  Result = LHS != RHS; break;
887    case BinaryOperator::And: Result = LHS & RHS; break;
888    case BinaryOperator::Xor: Result = LHS ^ RHS; break;
889    case BinaryOperator::Or:  Result = LHS | RHS; break;
890    case BinaryOperator::LAnd:
891      Result = LHS != 0 && RHS != 0;
892      break;
893    case BinaryOperator::LOr:
894      Result = LHS != 0 || RHS != 0;
895      break;
896
897    case BinaryOperator::Comma:
898      // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
899      // *except* when they are contained within a subexpression that is not
900      // evaluated".  Note that Assignment can never happen due to constraints
901      // on the LHS subexpr, so we don't need to check it here.
902      if (isEvaluated) {
903        if (Loc) *Loc = getLocStart();
904        return false;
905      }
906
907      // The result of the constant expr is the RHS.
908      Result = RHS;
909      return true;
910    }
911
912    assert(!Exp->isAssignmentOp() && "LHS can't be a constant expr!");
913    break;
914  }
915  case ImplicitCastExprClass:
916  case ExplicitCastExprClass:
917  case CXXFunctionalCastExprClass: {
918    const Expr *SubExpr = cast<CastExpr>(this)->getSubExpr();
919    SourceLocation CastLoc = getLocStart();
920
921    // C99 6.6p6: shall only convert arithmetic types to integer types.
922    if (!SubExpr->getType()->isArithmeticType() ||
923        !getType()->isIntegerType()) {
924      if (Loc) *Loc = SubExpr->getLocStart();
925      return false;
926    }
927
928    uint32_t DestWidth = static_cast<uint32_t>(Ctx.getTypeSize(getType()));
929
930    // Handle simple integer->integer casts.
931    if (SubExpr->getType()->isIntegerType()) {
932      if (!SubExpr->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
933        return false;
934
935      // Figure out if this is a truncate, extend or noop cast.
936      // If the input is signed, do a sign extend, noop, or truncate.
937      if (getType()->isBooleanType()) {
938        // Conversion to bool compares against zero.
939        Result = Result != 0;
940        Result.zextOrTrunc(DestWidth);
941      } else if (SubExpr->getType()->isSignedIntegerType())
942        Result.sextOrTrunc(DestWidth);
943      else  // If the input is unsigned, do a zero extend, noop, or truncate.
944        Result.zextOrTrunc(DestWidth);
945      break;
946    }
947
948    // Allow floating constants that are the immediate operands of casts or that
949    // are parenthesized.
950    const Expr *Operand = SubExpr;
951    while (const ParenExpr *PE = dyn_cast<ParenExpr>(Operand))
952      Operand = PE->getSubExpr();
953
954    // If this isn't a floating literal, we can't handle it.
955    const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(Operand);
956    if (!FL) {
957      if (Loc) *Loc = Operand->getLocStart();
958      return false;
959    }
960
961    // If the destination is boolean, compare against zero.
962    if (getType()->isBooleanType()) {
963      Result = !FL->getValue().isZero();
964      Result.zextOrTrunc(DestWidth);
965      break;
966    }
967
968    // Determine whether we are converting to unsigned or signed.
969    bool DestSigned = getType()->isSignedIntegerType();
970
971    // TODO: Warn on overflow, but probably not here: isIntegerConstantExpr can
972    // be called multiple times per AST.
973    uint64_t Space[4];
974    (void)FL->getValue().convertToInteger(Space, DestWidth, DestSigned,
975                                          llvm::APFloat::rmTowardZero);
976    Result = llvm::APInt(DestWidth, 4, Space);
977    break;
978  }
979  case ConditionalOperatorClass: {
980    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
981
982    if (!Exp->getCond()->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
983      return false;
984
985    const Expr *TrueExp  = Exp->getLHS();
986    const Expr *FalseExp = Exp->getRHS();
987    if (Result == 0) std::swap(TrueExp, FalseExp);
988
989    // Evaluate the false one first, discard the result.
990    if (FalseExp && !FalseExp->isIntegerConstantExpr(Result, Ctx, Loc, false))
991      return false;
992    // Evalute the true one, capture the result.
993    if (TrueExp &&
994        !TrueExp->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated))
995      return false;
996    break;
997  }
998  case CXXDefaultArgExprClass:
999    return cast<CXXDefaultArgExpr>(this)
1000             ->isIntegerConstantExpr(Result, Ctx, Loc, isEvaluated);
1001  }
1002
1003  // Cases that are valid constant exprs fall through to here.
1004  Result.setIsUnsigned(getType()->isUnsignedIntegerType());
1005  return true;
1006}
1007
1008/// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
1009/// integer constant expression with the value zero, or if this is one that is
1010/// cast to void*.
1011bool Expr::isNullPointerConstant(ASTContext &Ctx) const {
1012  // Strip off a cast to void*, if it exists.
1013  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
1014    // Check that it is a cast to void*.
1015    if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1016      QualType Pointee = PT->getPointeeType();
1017      if (Pointee.getCVRQualifiers() == 0 &&
1018          Pointee->isVoidType() &&                                 // to void*
1019          CE->getSubExpr()->getType()->isIntegerType())            // from int.
1020        return CE->getSubExpr()->isNullPointerConstant(Ctx);
1021    }
1022  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
1023    // Ignore the ImplicitCastExpr type entirely.
1024    return ICE->getSubExpr()->isNullPointerConstant(Ctx);
1025  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
1026    // Accept ((void*)0) as a null pointer constant, as many other
1027    // implementations do.
1028    return PE->getSubExpr()->isNullPointerConstant(Ctx);
1029  } else if (const CXXDefaultArgExpr *DefaultArg
1030               = dyn_cast<CXXDefaultArgExpr>(this)) {
1031    // See through default argument expressions
1032    return DefaultArg->getExpr()->isNullPointerConstant(Ctx);
1033  }
1034
1035  // This expression must be an integer type.
1036  if (!getType()->isIntegerType())
1037    return false;
1038
1039  // If we have an integer constant expression, we need to *evaluate* it and
1040  // test for the value 0.
1041  llvm::APSInt Val(32);
1042  return isIntegerConstantExpr(Val, Ctx, 0, true) && Val == 0;
1043}
1044
1045unsigned ExtVectorElementExpr::getNumElements() const {
1046  if (const VectorType *VT = getType()->getAsVectorType())
1047    return VT->getNumElements();
1048  return 1;
1049}
1050
1051/// containsDuplicateElements - Return true if any element access is repeated.
1052bool ExtVectorElementExpr::containsDuplicateElements() const {
1053  const char *compStr = Accessor.getName();
1054  unsigned length = strlen(compStr);
1055
1056  for (unsigned i = 0; i < length-1; i++) {
1057    const char *s = compStr+i;
1058    for (const char c = *s++; *s; s++)
1059      if (c == *s)
1060        return true;
1061  }
1062  return false;
1063}
1064
1065/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
1066void ExtVectorElementExpr::getEncodedElementAccess(
1067                                  llvm::SmallVectorImpl<unsigned> &Elts) const {
1068  const char *compStr = Accessor.getName();
1069
1070  bool isHi =   !strcmp(compStr, "hi");
1071  bool isLo =   !strcmp(compStr, "lo");
1072  bool isEven = !strcmp(compStr, "e");
1073  bool isOdd  = !strcmp(compStr, "o");
1074
1075  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
1076    uint64_t Index;
1077
1078    if (isHi)
1079      Index = e + i;
1080    else if (isLo)
1081      Index = i;
1082    else if (isEven)
1083      Index = 2 * i;
1084    else if (isOdd)
1085      Index = 2 * i + 1;
1086    else
1087      Index = ExtVectorType::getAccessorIdx(compStr[i]);
1088
1089    Elts.push_back(Index);
1090  }
1091}
1092
1093// constructor for instance messages.
1094ObjCMessageExpr::ObjCMessageExpr(Expr *receiver, Selector selInfo,
1095                QualType retType, ObjCMethodDecl *mproto,
1096                SourceLocation LBrac, SourceLocation RBrac,
1097                Expr **ArgExprs, unsigned nargs)
1098  : Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1099    MethodProto(mproto) {
1100  NumArgs = nargs;
1101  SubExprs = new Stmt*[NumArgs+1];
1102  SubExprs[RECEIVER] = receiver;
1103  if (NumArgs) {
1104    for (unsigned i = 0; i != NumArgs; ++i)
1105      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1106  }
1107  LBracloc = LBrac;
1108  RBracloc = RBrac;
1109}
1110
1111// constructor for class messages.
1112// FIXME: clsName should be typed to ObjCInterfaceType
1113ObjCMessageExpr::ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo,
1114                QualType retType, ObjCMethodDecl *mproto,
1115                SourceLocation LBrac, SourceLocation RBrac,
1116                Expr **ArgExprs, unsigned nargs)
1117  : Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1118    MethodProto(mproto) {
1119  NumArgs = nargs;
1120  SubExprs = new Stmt*[NumArgs+1];
1121  SubExprs[RECEIVER] = (Expr*) ((uintptr_t) clsName | IsClsMethDeclUnknown);
1122  if (NumArgs) {
1123    for (unsigned i = 0; i != NumArgs; ++i)
1124      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1125  }
1126  LBracloc = LBrac;
1127  RBracloc = RBrac;
1128}
1129
1130// constructor for class messages.
1131ObjCMessageExpr::ObjCMessageExpr(ObjCInterfaceDecl *cls, Selector selInfo,
1132                                 QualType retType, ObjCMethodDecl *mproto,
1133                                 SourceLocation LBrac, SourceLocation RBrac,
1134                                 Expr **ArgExprs, unsigned nargs)
1135: Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1136MethodProto(mproto) {
1137  NumArgs = nargs;
1138  SubExprs = new Stmt*[NumArgs+1];
1139  SubExprs[RECEIVER] = (Expr*) ((uintptr_t) cls | IsClsMethDeclKnown);
1140  if (NumArgs) {
1141    for (unsigned i = 0; i != NumArgs; ++i)
1142      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1143  }
1144  LBracloc = LBrac;
1145  RBracloc = RBrac;
1146}
1147
1148ObjCMessageExpr::ClassInfo ObjCMessageExpr::getClassInfo() const {
1149  uintptr_t x = (uintptr_t) SubExprs[RECEIVER];
1150  switch (x & Flags) {
1151    default:
1152      assert(false && "Invalid ObjCMessageExpr.");
1153    case IsInstMeth:
1154      return ClassInfo(0, 0);
1155    case IsClsMethDeclUnknown:
1156      return ClassInfo(0, (IdentifierInfo*) (x & ~Flags));
1157    case IsClsMethDeclKnown: {
1158      ObjCInterfaceDecl* D = (ObjCInterfaceDecl*) (x & ~Flags);
1159      return ClassInfo(D, D->getIdentifier());
1160    }
1161  }
1162}
1163
1164bool ChooseExpr::isConditionTrue(ASTContext &C) const {
1165  return getCond()->getIntegerConstantExprValue(C) != 0;
1166}
1167
1168static int64_t evaluateOffsetOf(ASTContext& C, const Expr *E)
1169{
1170  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1171    QualType Ty = ME->getBase()->getType();
1172
1173    RecordDecl *RD = Ty->getAsRecordType()->getDecl();
1174    const ASTRecordLayout &RL = C.getASTRecordLayout(RD);
1175    FieldDecl *FD = ME->getMemberDecl();
1176
1177    // FIXME: This is linear time.
1178    unsigned i = 0, e = 0;
1179    for (i = 0, e = RD->getNumMembers(); i != e; i++) {
1180      if (RD->getMember(i) == FD)
1181        break;
1182    }
1183
1184    return RL.getFieldOffset(i) + evaluateOffsetOf(C, ME->getBase());
1185  } else if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
1186    const Expr *Base = ASE->getBase();
1187
1188    int64_t size = C.getTypeSize(ASE->getType());
1189    size *= ASE->getIdx()->getIntegerConstantExprValue(C).getSExtValue();
1190
1191    return size + evaluateOffsetOf(C, Base);
1192  } else if (isa<CompoundLiteralExpr>(E))
1193    return 0;
1194
1195  assert(0 && "Unknown offsetof subexpression!");
1196  return 0;
1197}
1198
1199int64_t UnaryOperator::evaluateOffsetOf(ASTContext& C) const
1200{
1201  assert(Opc == OffsetOf && "Unary operator not offsetof!");
1202
1203  unsigned CharSize = C.Target.getCharWidth();
1204  return ::evaluateOffsetOf(C, cast<Expr>(Val)) / CharSize;
1205}
1206
1207void SizeOfAlignOfTypeExpr::Destroy(ASTContext& C) {
1208  // Override default behavior of traversing children. We do not want
1209  // to delete the type.
1210}
1211
1212//===----------------------------------------------------------------------===//
1213//  Child Iterators for iterating over subexpressions/substatements
1214//===----------------------------------------------------------------------===//
1215
1216// DeclRefExpr
1217Stmt::child_iterator DeclRefExpr::child_begin() { return child_iterator(); }
1218Stmt::child_iterator DeclRefExpr::child_end() { return child_iterator(); }
1219
1220// ObjCIvarRefExpr
1221Stmt::child_iterator ObjCIvarRefExpr::child_begin() { return &Base; }
1222Stmt::child_iterator ObjCIvarRefExpr::child_end() { return &Base+1; }
1223
1224// ObjCPropertyRefExpr
1225Stmt::child_iterator ObjCPropertyRefExpr::child_begin() { return &Base; }
1226Stmt::child_iterator ObjCPropertyRefExpr::child_end() { return &Base+1; }
1227
1228// PredefinedExpr
1229Stmt::child_iterator PredefinedExpr::child_begin() { return child_iterator(); }
1230Stmt::child_iterator PredefinedExpr::child_end() { return child_iterator(); }
1231
1232// IntegerLiteral
1233Stmt::child_iterator IntegerLiteral::child_begin() { return child_iterator(); }
1234Stmt::child_iterator IntegerLiteral::child_end() { return child_iterator(); }
1235
1236// CharacterLiteral
1237Stmt::child_iterator CharacterLiteral::child_begin() { return child_iterator(); }
1238Stmt::child_iterator CharacterLiteral::child_end() { return child_iterator(); }
1239
1240// FloatingLiteral
1241Stmt::child_iterator FloatingLiteral::child_begin() { return child_iterator(); }
1242Stmt::child_iterator FloatingLiteral::child_end() { return child_iterator(); }
1243
1244// ImaginaryLiteral
1245Stmt::child_iterator ImaginaryLiteral::child_begin() { return &Val; }
1246Stmt::child_iterator ImaginaryLiteral::child_end() { return &Val+1; }
1247
1248// StringLiteral
1249Stmt::child_iterator StringLiteral::child_begin() { return child_iterator(); }
1250Stmt::child_iterator StringLiteral::child_end() { return child_iterator(); }
1251
1252// ParenExpr
1253Stmt::child_iterator ParenExpr::child_begin() { return &Val; }
1254Stmt::child_iterator ParenExpr::child_end() { return &Val+1; }
1255
1256// UnaryOperator
1257Stmt::child_iterator UnaryOperator::child_begin() { return &Val; }
1258Stmt::child_iterator UnaryOperator::child_end() { return &Val+1; }
1259
1260// SizeOfAlignOfTypeExpr
1261Stmt::child_iterator SizeOfAlignOfTypeExpr::child_begin() {
1262  // If the type is a VLA type (and not a typedef), the size expression of the
1263  // VLA needs to be treated as an executable expression.
1264  if (VariableArrayType* T = dyn_cast<VariableArrayType>(Ty.getTypePtr()))
1265    return child_iterator(T);
1266  else
1267    return child_iterator();
1268}
1269Stmt::child_iterator SizeOfAlignOfTypeExpr::child_end() {
1270  return child_iterator();
1271}
1272
1273// ArraySubscriptExpr
1274Stmt::child_iterator ArraySubscriptExpr::child_begin() {
1275  return &SubExprs[0];
1276}
1277Stmt::child_iterator ArraySubscriptExpr::child_end() {
1278  return &SubExprs[0]+END_EXPR;
1279}
1280
1281// CallExpr
1282Stmt::child_iterator CallExpr::child_begin() {
1283  return &SubExprs[0];
1284}
1285Stmt::child_iterator CallExpr::child_end() {
1286  return &SubExprs[0]+NumArgs+ARGS_START;
1287}
1288
1289// MemberExpr
1290Stmt::child_iterator MemberExpr::child_begin() { return &Base; }
1291Stmt::child_iterator MemberExpr::child_end() { return &Base+1; }
1292
1293// ExtVectorElementExpr
1294Stmt::child_iterator ExtVectorElementExpr::child_begin() { return &Base; }
1295Stmt::child_iterator ExtVectorElementExpr::child_end() { return &Base+1; }
1296
1297// CompoundLiteralExpr
1298Stmt::child_iterator CompoundLiteralExpr::child_begin() { return &Init; }
1299Stmt::child_iterator CompoundLiteralExpr::child_end() { return &Init+1; }
1300
1301// CastExpr
1302Stmt::child_iterator CastExpr::child_begin() { return &Op; }
1303Stmt::child_iterator CastExpr::child_end() { return &Op+1; }
1304
1305// BinaryOperator
1306Stmt::child_iterator BinaryOperator::child_begin() {
1307  return &SubExprs[0];
1308}
1309Stmt::child_iterator BinaryOperator::child_end() {
1310  return &SubExprs[0]+END_EXPR;
1311}
1312
1313// ConditionalOperator
1314Stmt::child_iterator ConditionalOperator::child_begin() {
1315  return &SubExprs[0];
1316}
1317Stmt::child_iterator ConditionalOperator::child_end() {
1318  return &SubExprs[0]+END_EXPR;
1319}
1320
1321// AddrLabelExpr
1322Stmt::child_iterator AddrLabelExpr::child_begin() { return child_iterator(); }
1323Stmt::child_iterator AddrLabelExpr::child_end() { return child_iterator(); }
1324
1325// StmtExpr
1326Stmt::child_iterator StmtExpr::child_begin() { return &SubStmt; }
1327Stmt::child_iterator StmtExpr::child_end() { return &SubStmt+1; }
1328
1329// TypesCompatibleExpr
1330Stmt::child_iterator TypesCompatibleExpr::child_begin() {
1331  return child_iterator();
1332}
1333
1334Stmt::child_iterator TypesCompatibleExpr::child_end() {
1335  return child_iterator();
1336}
1337
1338// ChooseExpr
1339Stmt::child_iterator ChooseExpr::child_begin() { return &SubExprs[0]; }
1340Stmt::child_iterator ChooseExpr::child_end() { return &SubExprs[0]+END_EXPR; }
1341
1342// OverloadExpr
1343Stmt::child_iterator OverloadExpr::child_begin() { return &SubExprs[0]; }
1344Stmt::child_iterator OverloadExpr::child_end() { return &SubExprs[0]+NumExprs; }
1345
1346// ShuffleVectorExpr
1347Stmt::child_iterator ShuffleVectorExpr::child_begin() {
1348  return &SubExprs[0];
1349}
1350Stmt::child_iterator ShuffleVectorExpr::child_end() {
1351  return &SubExprs[0]+NumExprs;
1352}
1353
1354// VAArgExpr
1355Stmt::child_iterator VAArgExpr::child_begin() { return &Val; }
1356Stmt::child_iterator VAArgExpr::child_end() { return &Val+1; }
1357
1358// InitListExpr
1359Stmt::child_iterator InitListExpr::child_begin() {
1360  return InitExprs.size() ? &InitExprs[0] : 0;
1361}
1362Stmt::child_iterator InitListExpr::child_end() {
1363  return InitExprs.size() ? &InitExprs[0] + InitExprs.size() : 0;
1364}
1365
1366// ObjCStringLiteral
1367Stmt::child_iterator ObjCStringLiteral::child_begin() {
1368  return child_iterator();
1369}
1370Stmt::child_iterator ObjCStringLiteral::child_end() {
1371  return child_iterator();
1372}
1373
1374// ObjCEncodeExpr
1375Stmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); }
1376Stmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); }
1377
1378// ObjCSelectorExpr
1379Stmt::child_iterator ObjCSelectorExpr::child_begin() {
1380  return child_iterator();
1381}
1382Stmt::child_iterator ObjCSelectorExpr::child_end() {
1383  return child_iterator();
1384}
1385
1386// ObjCProtocolExpr
1387Stmt::child_iterator ObjCProtocolExpr::child_begin() {
1388  return child_iterator();
1389}
1390Stmt::child_iterator ObjCProtocolExpr::child_end() {
1391  return child_iterator();
1392}
1393
1394// ObjCMessageExpr
1395Stmt::child_iterator ObjCMessageExpr::child_begin() {
1396  return getReceiver() ? &SubExprs[0] : &SubExprs[0] + ARGS_START;
1397}
1398Stmt::child_iterator ObjCMessageExpr::child_end() {
1399  return &SubExprs[0]+ARGS_START+getNumArgs();
1400}
1401
1402// Blocks
1403Stmt::child_iterator BlockExpr::child_begin() { return &Body; }
1404Stmt::child_iterator BlockExpr::child_end() { return &Body+1; }
1405
1406Stmt::child_iterator BlockDeclRefExpr::child_begin() { return child_iterator();}
1407Stmt::child_iterator BlockDeclRefExpr::child_end() { return child_iterator(); }
1408