Expr.cpp revision ce94049b69f75b44c18584fe79cd238978b6b0d5
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/ExprCXX.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/AST/StmtVisitor.h"
23#include "clang/Basic/Builtins.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/Support/raw_ostream.h"
26#include <algorithm>
27using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Primary Expressions.
31//===----------------------------------------------------------------------===//
32
33// FIXME: Maybe this should use DeclPrinter with a special "print predefined
34// expr" policy instead.
35std::string PredefinedExpr::ComputeName(ASTContext &Context, IdentType IT,
36                                        const Decl *CurrentDecl) {
37  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
38    if (IT != PrettyFunction)
39      return FD->getNameAsString();
40
41    llvm::SmallString<256> Name;
42    llvm::raw_svector_ostream Out(Name);
43
44    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
45      if (MD->isVirtual())
46        Out << "virtual ";
47    }
48
49    PrintingPolicy Policy(Context.getLangOptions());
50    Policy.SuppressTagKind = true;
51
52    std::string Proto = FD->getQualifiedNameAsString(Policy);
53
54    const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
55    const FunctionProtoType *FT = 0;
56    if (FD->hasWrittenPrototype())
57      FT = dyn_cast<FunctionProtoType>(AFT);
58
59    Proto += "(";
60    if (FT) {
61      llvm::raw_string_ostream POut(Proto);
62      for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
63        if (i) POut << ", ";
64        std::string Param;
65        FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
66        POut << Param;
67      }
68
69      if (FT->isVariadic()) {
70        if (FD->getNumParams()) POut << ", ";
71        POut << "...";
72      }
73    }
74    Proto += ")";
75
76    AFT->getResultType().getAsStringInternal(Proto, Policy);
77
78    Out << Proto;
79
80    Out.flush();
81    return Name.str().str();
82  }
83  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
84    llvm::SmallString<256> Name;
85    llvm::raw_svector_ostream Out(Name);
86    Out << (MD->isInstanceMethod() ? '-' : '+');
87    Out << '[';
88    Out << MD->getClassInterface()->getNameAsString();
89    if (const ObjCCategoryImplDecl *CID =
90        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext())) {
91      Out << '(';
92      Out <<  CID->getNameAsString();
93      Out <<  ')';
94    }
95    Out <<  ' ';
96    Out << MD->getSelector().getAsString();
97    Out <<  ']';
98
99    Out.flush();
100    return Name.str().str();
101  }
102  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
103    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
104    return "top level";
105  }
106  return "";
107}
108
109/// getValueAsApproximateDouble - This returns the value as an inaccurate
110/// double.  Note that this may cause loss of precision, but is useful for
111/// debugging dumps, etc.
112double FloatingLiteral::getValueAsApproximateDouble() const {
113  llvm::APFloat V = getValue();
114  bool ignored;
115  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
116            &ignored);
117  return V.convertToDouble();
118}
119
120StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
121                                     unsigned ByteLength, bool Wide,
122                                     QualType Ty,
123                                     const SourceLocation *Loc,
124                                     unsigned NumStrs) {
125  // Allocate enough space for the StringLiteral plus an array of locations for
126  // any concatenated string tokens.
127  void *Mem = C.Allocate(sizeof(StringLiteral)+
128                         sizeof(SourceLocation)*(NumStrs-1),
129                         llvm::alignof<StringLiteral>());
130  StringLiteral *SL = new (Mem) StringLiteral(Ty);
131
132  // OPTIMIZE: could allocate this appended to the StringLiteral.
133  char *AStrData = new (C, 1) char[ByteLength];
134  memcpy(AStrData, StrData, ByteLength);
135  SL->StrData = AStrData;
136  SL->ByteLength = ByteLength;
137  SL->IsWide = Wide;
138  SL->TokLocs[0] = Loc[0];
139  SL->NumConcatenated = NumStrs;
140
141  if (NumStrs != 1)
142    memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
143  return SL;
144}
145
146StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
147  void *Mem = C.Allocate(sizeof(StringLiteral)+
148                         sizeof(SourceLocation)*(NumStrs-1),
149                         llvm::alignof<StringLiteral>());
150  StringLiteral *SL = new (Mem) StringLiteral(QualType());
151  SL->StrData = 0;
152  SL->ByteLength = 0;
153  SL->NumConcatenated = NumStrs;
154  return SL;
155}
156
157void StringLiteral::DoDestroy(ASTContext &C) {
158  C.Deallocate(const_cast<char*>(StrData));
159  Expr::DoDestroy(C);
160}
161
162void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
163  if (StrData)
164    C.Deallocate(const_cast<char*>(StrData));
165
166  char *AStrData = new (C, 1) char[Str.size()];
167  memcpy(AStrData, Str.data(), Str.size());
168  StrData = AStrData;
169  ByteLength = Str.size();
170}
171
172/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
173/// corresponds to, e.g. "sizeof" or "[pre]++".
174const char *UnaryOperator::getOpcodeStr(Opcode Op) {
175  switch (Op) {
176  default: assert(0 && "Unknown unary operator");
177  case PostInc: return "++";
178  case PostDec: return "--";
179  case PreInc:  return "++";
180  case PreDec:  return "--";
181  case AddrOf:  return "&";
182  case Deref:   return "*";
183  case Plus:    return "+";
184  case Minus:   return "-";
185  case Not:     return "~";
186  case LNot:    return "!";
187  case Real:    return "__real";
188  case Imag:    return "__imag";
189  case Extension: return "__extension__";
190  case OffsetOf: return "__builtin_offsetof";
191  }
192}
193
194UnaryOperator::Opcode
195UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
196  switch (OO) {
197  default: assert(false && "No unary operator for overloaded function");
198  case OO_PlusPlus:   return Postfix ? PostInc : PreInc;
199  case OO_MinusMinus: return Postfix ? PostDec : PreDec;
200  case OO_Amp:        return AddrOf;
201  case OO_Star:       return Deref;
202  case OO_Plus:       return Plus;
203  case OO_Minus:      return Minus;
204  case OO_Tilde:      return Not;
205  case OO_Exclaim:    return LNot;
206  }
207}
208
209OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
210  switch (Opc) {
211  case PostInc: case PreInc: return OO_PlusPlus;
212  case PostDec: case PreDec: return OO_MinusMinus;
213  case AddrOf: return OO_Amp;
214  case Deref: return OO_Star;
215  case Plus: return OO_Plus;
216  case Minus: return OO_Minus;
217  case Not: return OO_Tilde;
218  case LNot: return OO_Exclaim;
219  default: return OO_None;
220  }
221}
222
223
224//===----------------------------------------------------------------------===//
225// Postfix Operators.
226//===----------------------------------------------------------------------===//
227
228CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args,
229                   unsigned numargs, QualType t, SourceLocation rparenloc)
230  : Expr(SC, t,
231         fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
232         fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)),
233    NumArgs(numargs) {
234
235  SubExprs = new (C) Stmt*[numargs+1];
236  SubExprs[FN] = fn;
237  for (unsigned i = 0; i != numargs; ++i)
238    SubExprs[i+ARGS_START] = args[i];
239
240  RParenLoc = rparenloc;
241}
242
243CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
244                   QualType t, SourceLocation rparenloc)
245  : Expr(CallExprClass, t,
246         fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
247         fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)),
248    NumArgs(numargs) {
249
250  SubExprs = new (C) Stmt*[numargs+1];
251  SubExprs[FN] = fn;
252  for (unsigned i = 0; i != numargs; ++i)
253    SubExprs[i+ARGS_START] = args[i];
254
255  RParenLoc = rparenloc;
256}
257
258CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
259  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
260  SubExprs = new (C) Stmt*[1];
261}
262
263void CallExpr::DoDestroy(ASTContext& C) {
264  DestroyChildren(C);
265  if (SubExprs) C.Deallocate(SubExprs);
266  this->~CallExpr();
267  C.Deallocate(this);
268}
269
270FunctionDecl *CallExpr::getDirectCallee() {
271  Expr *CEE = getCallee()->IgnoreParenCasts();
272  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
273    return dyn_cast<FunctionDecl>(DRE->getDecl());
274
275  return 0;
276}
277
278/// setNumArgs - This changes the number of arguments present in this call.
279/// Any orphaned expressions are deleted by this, and any new operands are set
280/// to null.
281void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
282  // No change, just return.
283  if (NumArgs == getNumArgs()) return;
284
285  // If shrinking # arguments, just delete the extras and forgot them.
286  if (NumArgs < getNumArgs()) {
287    for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i)
288      getArg(i)->Destroy(C);
289    this->NumArgs = NumArgs;
290    return;
291  }
292
293  // Otherwise, we are growing the # arguments.  New an bigger argument array.
294  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+1];
295  // Copy over args.
296  for (unsigned i = 0; i != getNumArgs()+ARGS_START; ++i)
297    NewSubExprs[i] = SubExprs[i];
298  // Null out new args.
299  for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i)
300    NewSubExprs[i] = 0;
301
302  if (SubExprs) C.Deallocate(SubExprs);
303  SubExprs = NewSubExprs;
304  this->NumArgs = NumArgs;
305}
306
307/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
308/// not, return 0.
309unsigned CallExpr::isBuiltinCall(ASTContext &Context) const {
310  // All simple function calls (e.g. func()) are implicitly cast to pointer to
311  // function. As a result, we try and obtain the DeclRefExpr from the
312  // ImplicitCastExpr.
313  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
314  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
315    return 0;
316
317  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
318  if (!DRE)
319    return 0;
320
321  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
322  if (!FDecl)
323    return 0;
324
325  if (!FDecl->getIdentifier())
326    return 0;
327
328  return FDecl->getBuiltinID();
329}
330
331QualType CallExpr::getCallReturnType() const {
332  QualType CalleeType = getCallee()->getType();
333  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
334    CalleeType = FnTypePtr->getPointeeType();
335  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
336    CalleeType = BPT->getPointeeType();
337
338  const FunctionType *FnType = CalleeType->getAs<FunctionType>();
339  return FnType->getResultType();
340}
341
342MemberExpr::MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual,
343                       SourceRange qualrange, NamedDecl *memberdecl,
344                       SourceLocation l, bool has_explicit,
345                       SourceLocation langle,
346                       const TemplateArgument *targs, unsigned numtargs,
347                       SourceLocation rangle, QualType ty)
348  : Expr(MemberExprClass, ty,
349         base->isTypeDependent() || (qual && qual->isDependent()),
350         base->isValueDependent() || (qual && qual->isDependent())),
351    Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow),
352    HasQualifier(qual != 0), HasExplicitTemplateArgumentList(has_explicit) {
353  // Initialize the qualifier, if any.
354  if (HasQualifier) {
355    NameQualifier *NQ = getMemberQualifier();
356    NQ->NNS = qual;
357    NQ->Range = qualrange;
358  }
359
360  // Initialize the explicit template argument list, if any.
361  if (HasExplicitTemplateArgumentList) {
362    ExplicitTemplateArgumentList *ETemplateArgs
363      = getExplicitTemplateArgumentList();
364    ETemplateArgs->LAngleLoc = langle;
365    ETemplateArgs->RAngleLoc = rangle;
366    ETemplateArgs->NumTemplateArgs = numtargs;
367
368    TemplateArgument *TemplateArgs = ETemplateArgs->getTemplateArgs();
369    for (unsigned I = 0; I < numtargs; ++I)
370      new (TemplateArgs + I) TemplateArgument(targs[I]);
371  }
372}
373
374MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
375                               NestedNameSpecifier *qual,
376                               SourceRange qualrange,
377                               NamedDecl *memberdecl,
378                               SourceLocation l,
379                               bool has_explicit,
380                               SourceLocation langle,
381                               const TemplateArgument *targs,
382                               unsigned numtargs,
383                               SourceLocation rangle,
384                               QualType ty) {
385  std::size_t Size = sizeof(MemberExpr);
386  if (qual != 0)
387    Size += sizeof(NameQualifier);
388
389  if (has_explicit)
390    Size += sizeof(ExplicitTemplateArgumentList) +
391    sizeof(TemplateArgument) * numtargs;
392
393  void *Mem = C.Allocate(Size, llvm::alignof<MemberExpr>());
394  return new (Mem) MemberExpr(base, isarrow, qual, qualrange, memberdecl, l,
395                              has_explicit, langle, targs, numtargs, rangle,
396                              ty);
397}
398
399const char *CastExpr::getCastKindName() const {
400  switch (getCastKind()) {
401  case CastExpr::CK_Unknown:
402    return "Unknown";
403  case CastExpr::CK_BitCast:
404    return "BitCast";
405  case CastExpr::CK_NoOp:
406    return "NoOp";
407  case CastExpr::CK_DerivedToBase:
408    return "DerivedToBase";
409  case CastExpr::CK_Dynamic:
410    return "Dynamic";
411  case CastExpr::CK_ToUnion:
412    return "ToUnion";
413  case CastExpr::CK_ArrayToPointerDecay:
414    return "ArrayToPointerDecay";
415  case CastExpr::CK_FunctionToPointerDecay:
416    return "FunctionToPointerDecay";
417  case CastExpr::CK_NullToMemberPointer:
418    return "NullToMemberPointer";
419  case CastExpr::CK_BaseToDerivedMemberPointer:
420    return "BaseToDerivedMemberPointer";
421  case CastExpr::CK_UserDefinedConversion:
422    return "UserDefinedConversion";
423  case CastExpr::CK_ConstructorConversion:
424    return "ConstructorConversion";
425  case CastExpr::CK_IntegralToPointer:
426    return "IntegralToPointer";
427  case CastExpr::CK_PointerToIntegral:
428    return "PointerToIntegral";
429  }
430
431  assert(0 && "Unhandled cast kind!");
432  return 0;
433}
434
435/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
436/// corresponds to, e.g. "<<=".
437const char *BinaryOperator::getOpcodeStr(Opcode Op) {
438  switch (Op) {
439  case PtrMemD:   return ".*";
440  case PtrMemI:   return "->*";
441  case Mul:       return "*";
442  case Div:       return "/";
443  case Rem:       return "%";
444  case Add:       return "+";
445  case Sub:       return "-";
446  case Shl:       return "<<";
447  case Shr:       return ">>";
448  case LT:        return "<";
449  case GT:        return ">";
450  case LE:        return "<=";
451  case GE:        return ">=";
452  case EQ:        return "==";
453  case NE:        return "!=";
454  case And:       return "&";
455  case Xor:       return "^";
456  case Or:        return "|";
457  case LAnd:      return "&&";
458  case LOr:       return "||";
459  case Assign:    return "=";
460  case MulAssign: return "*=";
461  case DivAssign: return "/=";
462  case RemAssign: return "%=";
463  case AddAssign: return "+=";
464  case SubAssign: return "-=";
465  case ShlAssign: return "<<=";
466  case ShrAssign: return ">>=";
467  case AndAssign: return "&=";
468  case XorAssign: return "^=";
469  case OrAssign:  return "|=";
470  case Comma:     return ",";
471  }
472
473  return "";
474}
475
476BinaryOperator::Opcode
477BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
478  switch (OO) {
479  default: assert(false && "Not an overloadable binary operator");
480  case OO_Plus: return Add;
481  case OO_Minus: return Sub;
482  case OO_Star: return Mul;
483  case OO_Slash: return Div;
484  case OO_Percent: return Rem;
485  case OO_Caret: return Xor;
486  case OO_Amp: return And;
487  case OO_Pipe: return Or;
488  case OO_Equal: return Assign;
489  case OO_Less: return LT;
490  case OO_Greater: return GT;
491  case OO_PlusEqual: return AddAssign;
492  case OO_MinusEqual: return SubAssign;
493  case OO_StarEqual: return MulAssign;
494  case OO_SlashEqual: return DivAssign;
495  case OO_PercentEqual: return RemAssign;
496  case OO_CaretEqual: return XorAssign;
497  case OO_AmpEqual: return AndAssign;
498  case OO_PipeEqual: return OrAssign;
499  case OO_LessLess: return Shl;
500  case OO_GreaterGreater: return Shr;
501  case OO_LessLessEqual: return ShlAssign;
502  case OO_GreaterGreaterEqual: return ShrAssign;
503  case OO_EqualEqual: return EQ;
504  case OO_ExclaimEqual: return NE;
505  case OO_LessEqual: return LE;
506  case OO_GreaterEqual: return GE;
507  case OO_AmpAmp: return LAnd;
508  case OO_PipePipe: return LOr;
509  case OO_Comma: return Comma;
510  case OO_ArrowStar: return PtrMemI;
511  }
512}
513
514OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
515  static const OverloadedOperatorKind OverOps[] = {
516    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
517    OO_Star, OO_Slash, OO_Percent,
518    OO_Plus, OO_Minus,
519    OO_LessLess, OO_GreaterGreater,
520    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
521    OO_EqualEqual, OO_ExclaimEqual,
522    OO_Amp,
523    OO_Caret,
524    OO_Pipe,
525    OO_AmpAmp,
526    OO_PipePipe,
527    OO_Equal, OO_StarEqual,
528    OO_SlashEqual, OO_PercentEqual,
529    OO_PlusEqual, OO_MinusEqual,
530    OO_LessLessEqual, OO_GreaterGreaterEqual,
531    OO_AmpEqual, OO_CaretEqual,
532    OO_PipeEqual,
533    OO_Comma
534  };
535  return OverOps[Opc];
536}
537
538InitListExpr::InitListExpr(SourceLocation lbraceloc,
539                           Expr **initExprs, unsigned numInits,
540                           SourceLocation rbraceloc)
541  : Expr(InitListExprClass, QualType(),
542         hasAnyTypeDependentArguments(initExprs, numInits),
543         hasAnyValueDependentArguments(initExprs, numInits)),
544    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
545    UnionFieldInit(0), HadArrayRangeDesignator(false) {
546
547  InitExprs.insert(InitExprs.end(), initExprs, initExprs+numInits);
548}
549
550void InitListExpr::reserveInits(unsigned NumInits) {
551  if (NumInits > InitExprs.size())
552    InitExprs.reserve(NumInits);
553}
554
555void InitListExpr::resizeInits(ASTContext &Context, unsigned NumInits) {
556  for (unsigned Idx = NumInits, LastIdx = InitExprs.size();
557       Idx < LastIdx; ++Idx)
558    InitExprs[Idx]->Destroy(Context);
559  InitExprs.resize(NumInits, 0);
560}
561
562Expr *InitListExpr::updateInit(unsigned Init, Expr *expr) {
563  if (Init >= InitExprs.size()) {
564    InitExprs.insert(InitExprs.end(), Init - InitExprs.size() + 1, 0);
565    InitExprs.back() = expr;
566    return 0;
567  }
568
569  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
570  InitExprs[Init] = expr;
571  return Result;
572}
573
574/// getFunctionType - Return the underlying function type for this block.
575///
576const FunctionType *BlockExpr::getFunctionType() const {
577  return getType()->getAs<BlockPointerType>()->
578                    getPointeeType()->getAs<FunctionType>();
579}
580
581SourceLocation BlockExpr::getCaretLocation() const {
582  return TheBlock->getCaretLocation();
583}
584const Stmt *BlockExpr::getBody() const {
585  return TheBlock->getBody();
586}
587Stmt *BlockExpr::getBody() {
588  return TheBlock->getBody();
589}
590
591
592//===----------------------------------------------------------------------===//
593// Generic Expression Routines
594//===----------------------------------------------------------------------===//
595
596/// isUnusedResultAWarning - Return true if this immediate expression should
597/// be warned about if the result is unused.  If so, fill in Loc and Ranges
598/// with location to warn on and the source range[s] to report with the
599/// warning.
600bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
601                                  SourceRange &R2) const {
602  // Don't warn if the expr is type dependent. The type could end up
603  // instantiating to void.
604  if (isTypeDependent())
605    return false;
606
607  switch (getStmtClass()) {
608  default:
609    Loc = getExprLoc();
610    R1 = getSourceRange();
611    return true;
612  case ParenExprClass:
613    return cast<ParenExpr>(this)->getSubExpr()->
614      isUnusedResultAWarning(Loc, R1, R2);
615  case UnaryOperatorClass: {
616    const UnaryOperator *UO = cast<UnaryOperator>(this);
617
618    switch (UO->getOpcode()) {
619    default: break;
620    case UnaryOperator::PostInc:
621    case UnaryOperator::PostDec:
622    case UnaryOperator::PreInc:
623    case UnaryOperator::PreDec:                 // ++/--
624      return false;  // Not a warning.
625    case UnaryOperator::Deref:
626      // Dereferencing a volatile pointer is a side-effect.
627      if (getType().isVolatileQualified())
628        return false;
629      break;
630    case UnaryOperator::Real:
631    case UnaryOperator::Imag:
632      // accessing a piece of a volatile complex is a side-effect.
633      if (UO->getSubExpr()->getType().isVolatileQualified())
634        return false;
635      break;
636    case UnaryOperator::Extension:
637      return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
638    }
639    Loc = UO->getOperatorLoc();
640    R1 = UO->getSubExpr()->getSourceRange();
641    return true;
642  }
643  case BinaryOperatorClass: {
644    const BinaryOperator *BO = cast<BinaryOperator>(this);
645    // Consider comma to have side effects if the LHS or RHS does.
646    if (BO->getOpcode() == BinaryOperator::Comma)
647      return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2) ||
648             BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2);
649
650    if (BO->isAssignmentOp())
651      return false;
652    Loc = BO->getOperatorLoc();
653    R1 = BO->getLHS()->getSourceRange();
654    R2 = BO->getRHS()->getSourceRange();
655    return true;
656  }
657  case CompoundAssignOperatorClass:
658    return false;
659
660  case ConditionalOperatorClass: {
661    // The condition must be evaluated, but if either the LHS or RHS is a
662    // warning, warn about them.
663    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
664    if (Exp->getLHS() &&
665        Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2))
666      return true;
667    return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2);
668  }
669
670  case MemberExprClass:
671    // If the base pointer or element is to a volatile pointer/field, accessing
672    // it is a side effect.
673    if (getType().isVolatileQualified())
674      return false;
675    Loc = cast<MemberExpr>(this)->getMemberLoc();
676    R1 = SourceRange(Loc, Loc);
677    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
678    return true;
679
680  case ArraySubscriptExprClass:
681    // If the base pointer or element is to a volatile pointer/field, accessing
682    // it is a side effect.
683    if (getType().isVolatileQualified())
684      return false;
685    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
686    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
687    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
688    return true;
689
690  case CallExprClass:
691  case CXXOperatorCallExprClass:
692  case CXXMemberCallExprClass: {
693    // If this is a direct call, get the callee.
694    const CallExpr *CE = cast<CallExpr>(this);
695    const Expr *CalleeExpr = CE->getCallee()->IgnoreParenCasts();
696    if (const DeclRefExpr *CalleeDRE = dyn_cast<DeclRefExpr>(CalleeExpr)) {
697      // If the callee has attribute pure, const, or warn_unused_result, warn
698      // about it. void foo() { strlen("bar"); } should warn.
699      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeDRE->getDecl()))
700        if (FD->getAttr<WarnUnusedResultAttr>() ||
701            FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
702          Loc = CE->getCallee()->getLocStart();
703          R1 = CE->getCallee()->getSourceRange();
704
705          if (unsigned NumArgs = CE->getNumArgs())
706            R2 = SourceRange(CE->getArg(0)->getLocStart(),
707                             CE->getArg(NumArgs-1)->getLocEnd());
708          return true;
709        }
710    }
711    return false;
712  }
713  case ObjCMessageExprClass:
714    return false;
715
716  case ObjCImplicitSetterGetterRefExprClass: {   // Dot syntax for message send.
717#if 0
718    const ObjCImplicitSetterGetterRefExpr *Ref =
719      cast<ObjCImplicitSetterGetterRefExpr>(this);
720    // FIXME: We really want the location of the '.' here.
721    Loc = Ref->getLocation();
722    R1 = SourceRange(Ref->getLocation(), Ref->getLocation());
723    if (Ref->getBase())
724      R2 = Ref->getBase()->getSourceRange();
725#else
726    Loc = getExprLoc();
727    R1 = getSourceRange();
728#endif
729    return true;
730  }
731  case StmtExprClass: {
732    // Statement exprs don't logically have side effects themselves, but are
733    // sometimes used in macros in ways that give them a type that is unused.
734    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
735    // however, if the result of the stmt expr is dead, we don't want to emit a
736    // warning.
737    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
738    if (!CS->body_empty())
739      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
740        return E->isUnusedResultAWarning(Loc, R1, R2);
741
742    Loc = cast<StmtExpr>(this)->getLParenLoc();
743    R1 = getSourceRange();
744    return true;
745  }
746  case CStyleCastExprClass:
747    // If this is an explicit cast to void, allow it.  People do this when they
748    // think they know what they're doing :).
749    if (getType()->isVoidType())
750      return false;
751    Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
752    R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
753    return true;
754  case CXXFunctionalCastExprClass:
755    // If this is a cast to void, check the operand.  Otherwise, the result of
756    // the cast is unused.
757    if (getType()->isVoidType())
758      return cast<CastExpr>(this)->getSubExpr()
759               ->isUnusedResultAWarning(Loc, R1, R2);
760    Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
761    R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
762    return true;
763
764  case ImplicitCastExprClass:
765    // Check the operand, since implicit casts are inserted by Sema
766    return cast<ImplicitCastExpr>(this)
767      ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
768
769  case CXXDefaultArgExprClass:
770    return cast<CXXDefaultArgExpr>(this)
771      ->getExpr()->isUnusedResultAWarning(Loc, R1, R2);
772
773  case CXXNewExprClass:
774    // FIXME: In theory, there might be new expressions that don't have side
775    // effects (e.g. a placement new with an uninitialized POD).
776  case CXXDeleteExprClass:
777    return false;
778  case CXXBindTemporaryExprClass:
779    return cast<CXXBindTemporaryExpr>(this)
780      ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
781  case CXXExprWithTemporariesClass:
782    return cast<CXXExprWithTemporaries>(this)
783      ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
784  }
785}
786
787/// DeclCanBeLvalue - Determine whether the given declaration can be
788/// an lvalue. This is a helper routine for isLvalue.
789static bool DeclCanBeLvalue(const NamedDecl *Decl, ASTContext &Ctx) {
790  // C++ [temp.param]p6:
791  //   A non-type non-reference template-parameter is not an lvalue.
792  if (const NonTypeTemplateParmDecl *NTTParm
793        = dyn_cast<NonTypeTemplateParmDecl>(Decl))
794    return NTTParm->getType()->isReferenceType();
795
796  return isa<VarDecl>(Decl) || isa<FieldDecl>(Decl) ||
797    // C++ 3.10p2: An lvalue refers to an object or function.
798    (Ctx.getLangOptions().CPlusPlus &&
799     (isa<FunctionDecl>(Decl) || isa<OverloadedFunctionDecl>(Decl) ||
800      isa<FunctionTemplateDecl>(Decl)));
801}
802
803/// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an
804/// incomplete type other than void. Nonarray expressions that can be lvalues:
805///  - name, where name must be a variable
806///  - e[i]
807///  - (e), where e must be an lvalue
808///  - e.name, where e must be an lvalue
809///  - e->name
810///  - *e, the type of e cannot be a function type
811///  - string-constant
812///  - (__real__ e) and (__imag__ e) where e is an lvalue  [GNU extension]
813///  - reference type [C++ [expr]]
814///
815Expr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const {
816  assert(!TR->isReferenceType() && "Expressions can't have reference type.");
817
818  isLvalueResult Res = isLvalueInternal(Ctx);
819  if (Res != LV_Valid || Ctx.getLangOptions().CPlusPlus)
820    return Res;
821
822  // first, check the type (C99 6.3.2.1). Expressions with function
823  // type in C are not lvalues, but they can be lvalues in C++.
824  if (TR->isFunctionType() || TR == Ctx.OverloadTy)
825    return LV_NotObjectType;
826
827  // Allow qualified void which is an incomplete type other than void (yuck).
828  if (TR->isVoidType() && !Ctx.getCanonicalType(TR).hasQualifiers())
829    return LV_IncompleteVoidType;
830
831  return LV_Valid;
832}
833
834// Check whether the expression can be sanely treated like an l-value
835Expr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const {
836  switch (getStmtClass()) {
837  case StringLiteralClass:  // C99 6.5.1p4
838  case ObjCEncodeExprClass: // @encode behaves like its string in every way.
839    return LV_Valid;
840  case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2))))
841    // For vectors, make sure base is an lvalue (i.e. not a function call).
842    if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType())
843      return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue(Ctx);
844    return LV_Valid;
845  case DeclRefExprClass:
846  case QualifiedDeclRefExprClass: { // C99 6.5.1p2
847    const NamedDecl *RefdDecl = cast<DeclRefExpr>(this)->getDecl();
848    if (DeclCanBeLvalue(RefdDecl, Ctx))
849      return LV_Valid;
850    break;
851  }
852  case BlockDeclRefExprClass: {
853    const BlockDeclRefExpr *BDR = cast<BlockDeclRefExpr>(this);
854    if (isa<VarDecl>(BDR->getDecl()))
855      return LV_Valid;
856    break;
857  }
858  case MemberExprClass: {
859    const MemberExpr *m = cast<MemberExpr>(this);
860    if (Ctx.getLangOptions().CPlusPlus) { // C++ [expr.ref]p4:
861      NamedDecl *Member = m->getMemberDecl();
862      // C++ [expr.ref]p4:
863      //   If E2 is declared to have type "reference to T", then E1.E2
864      //   is an lvalue.
865      if (ValueDecl *Value = dyn_cast<ValueDecl>(Member))
866        if (Value->getType()->isReferenceType())
867          return LV_Valid;
868
869      //   -- If E2 is a static data member [...] then E1.E2 is an lvalue.
870      if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
871        return LV_Valid;
872
873      //   -- If E2 is a non-static data member [...]. If E1 is an
874      //      lvalue, then E1.E2 is an lvalue.
875      if (isa<FieldDecl>(Member))
876        return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx);
877
878      //   -- If it refers to a static member function [...], then
879      //      E1.E2 is an lvalue.
880      //   -- Otherwise, if E1.E2 refers to a non-static member
881      //      function [...], then E1.E2 is not an lvalue.
882      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member))
883        return Method->isStatic()? LV_Valid : LV_MemberFunction;
884
885      //   -- If E2 is a member enumerator [...], the expression E1.E2
886      //      is not an lvalue.
887      if (isa<EnumConstantDecl>(Member))
888        return LV_InvalidExpression;
889
890        // Not an lvalue.
891      return LV_InvalidExpression;
892    }
893
894    // C99 6.5.2.3p4
895    return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx);
896  }
897  case UnaryOperatorClass:
898    if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref)
899      return LV_Valid; // C99 6.5.3p4
900
901    if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Real ||
902        cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Imag ||
903        cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Extension)
904      return cast<UnaryOperator>(this)->getSubExpr()->isLvalue(Ctx);  // GNU.
905
906    if (Ctx.getLangOptions().CPlusPlus && // C++ [expr.pre.incr]p1
907        (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::PreInc ||
908         cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::PreDec))
909      return LV_Valid;
910    break;
911  case ImplicitCastExprClass:
912    return cast<ImplicitCastExpr>(this)->isLvalueCast()? LV_Valid
913                                                       : LV_InvalidExpression;
914  case ParenExprClass: // C99 6.5.1p5
915    return cast<ParenExpr>(this)->getSubExpr()->isLvalue(Ctx);
916  case BinaryOperatorClass:
917  case CompoundAssignOperatorClass: {
918    const BinaryOperator *BinOp = cast<BinaryOperator>(this);
919
920    if (Ctx.getLangOptions().CPlusPlus && // C++ [expr.comma]p1
921        BinOp->getOpcode() == BinaryOperator::Comma)
922      return BinOp->getRHS()->isLvalue(Ctx);
923
924    // C++ [expr.mptr.oper]p6
925    if ((BinOp->getOpcode() == BinaryOperator::PtrMemD ||
926         BinOp->getOpcode() == BinaryOperator::PtrMemI) &&
927        !BinOp->getType()->isFunctionType())
928      return BinOp->getLHS()->isLvalue(Ctx);
929
930    if (!BinOp->isAssignmentOp())
931      return LV_InvalidExpression;
932
933    if (Ctx.getLangOptions().CPlusPlus)
934      // C++ [expr.ass]p1:
935      //   The result of an assignment operation [...] is an lvalue.
936      return LV_Valid;
937
938
939    // C99 6.5.16:
940    //   An assignment expression [...] is not an lvalue.
941    return LV_InvalidExpression;
942  }
943  case CallExprClass:
944  case CXXOperatorCallExprClass:
945  case CXXMemberCallExprClass: {
946    // C++0x [expr.call]p10
947    //   A function call is an lvalue if and only if the result type
948    //   is an lvalue reference.
949    QualType ReturnType = cast<CallExpr>(this)->getCallReturnType();
950    if (ReturnType->isLValueReferenceType())
951      return LV_Valid;
952
953    break;
954  }
955  case CompoundLiteralExprClass: // C99 6.5.2.5p5
956    return LV_Valid;
957  case ChooseExprClass:
958    // __builtin_choose_expr is an lvalue if the selected operand is.
959    return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)->isLvalue(Ctx);
960  case ExtVectorElementExprClass:
961    if (cast<ExtVectorElementExpr>(this)->containsDuplicateElements())
962      return LV_DuplicateVectorComponents;
963    return LV_Valid;
964  case ObjCIvarRefExprClass: // ObjC instance variables are lvalues.
965    return LV_Valid;
966  case ObjCPropertyRefExprClass: // FIXME: check if read-only property.
967    return LV_Valid;
968  case ObjCImplicitSetterGetterRefExprClass: // FIXME: check if read-only property.
969    return LV_Valid;
970  case PredefinedExprClass:
971    return LV_Valid;
972  case CXXDefaultArgExprClass:
973    return cast<CXXDefaultArgExpr>(this)->getExpr()->isLvalue(Ctx);
974  case CXXConditionDeclExprClass:
975    return LV_Valid;
976  case CStyleCastExprClass:
977  case CXXFunctionalCastExprClass:
978  case CXXStaticCastExprClass:
979  case CXXDynamicCastExprClass:
980  case CXXReinterpretCastExprClass:
981  case CXXConstCastExprClass:
982    // The result of an explicit cast is an lvalue if the type we are
983    // casting to is an lvalue reference type. See C++ [expr.cast]p1,
984    // C++ [expr.static.cast]p2, C++ [expr.dynamic.cast]p2,
985    // C++ [expr.reinterpret.cast]p1, C++ [expr.const.cast]p1.
986    if (cast<ExplicitCastExpr>(this)->getTypeAsWritten()->
987          isLValueReferenceType())
988      return LV_Valid;
989    break;
990  case CXXTypeidExprClass:
991    // C++ 5.2.8p1: The result of a typeid expression is an lvalue of ...
992    return LV_Valid;
993  case CXXBindTemporaryExprClass:
994    return cast<CXXBindTemporaryExpr>(this)->getSubExpr()->
995      isLvalueInternal(Ctx);
996  case ConditionalOperatorClass: {
997    // Complicated handling is only for C++.
998    if (!Ctx.getLangOptions().CPlusPlus)
999      return LV_InvalidExpression;
1000
1001    // Sema should have taken care to ensure that a CXXTemporaryObjectExpr is
1002    // everywhere there's an object converted to an rvalue. Also, any other
1003    // casts should be wrapped by ImplicitCastExprs. There's just the special
1004    // case involving throws to work out.
1005    const ConditionalOperator *Cond = cast<ConditionalOperator>(this);
1006    Expr *True = Cond->getTrueExpr();
1007    Expr *False = Cond->getFalseExpr();
1008    // C++0x 5.16p2
1009    //   If either the second or the third operand has type (cv) void, [...]
1010    //   the result [...] is an rvalue.
1011    if (True->getType()->isVoidType() || False->getType()->isVoidType())
1012      return LV_InvalidExpression;
1013
1014    // Both sides must be lvalues for the result to be an lvalue.
1015    if (True->isLvalue(Ctx) != LV_Valid || False->isLvalue(Ctx) != LV_Valid)
1016      return LV_InvalidExpression;
1017
1018    // That's it.
1019    return LV_Valid;
1020  }
1021
1022  default:
1023    break;
1024  }
1025  return LV_InvalidExpression;
1026}
1027
1028/// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
1029/// does not have an incomplete type, does not have a const-qualified type, and
1030/// if it is a structure or union, does not have any member (including,
1031/// recursively, any member or element of all contained aggregates or unions)
1032/// with a const-qualified type.
1033Expr::isModifiableLvalueResult
1034Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
1035  isLvalueResult lvalResult = isLvalue(Ctx);
1036
1037  switch (lvalResult) {
1038  case LV_Valid:
1039    // C++ 3.10p11: Functions cannot be modified, but pointers to
1040    // functions can be modifiable.
1041    if (Ctx.getLangOptions().CPlusPlus && TR->isFunctionType())
1042      return MLV_NotObjectType;
1043    break;
1044
1045  case LV_NotObjectType: return MLV_NotObjectType;
1046  case LV_IncompleteVoidType: return MLV_IncompleteVoidType;
1047  case LV_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
1048  case LV_InvalidExpression:
1049    // If the top level is a C-style cast, and the subexpression is a valid
1050    // lvalue, then this is probably a use of the old-school "cast as lvalue"
1051    // GCC extension.  We don't support it, but we want to produce good
1052    // diagnostics when it happens so that the user knows why.
1053    if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(IgnoreParens())) {
1054      if (CE->getSubExpr()->isLvalue(Ctx) == LV_Valid) {
1055        if (Loc)
1056          *Loc = CE->getLParenLoc();
1057        return MLV_LValueCast;
1058      }
1059    }
1060    return MLV_InvalidExpression;
1061  case LV_MemberFunction: return MLV_MemberFunction;
1062  }
1063
1064  // The following is illegal:
1065  //   void takeclosure(void (^C)(void));
1066  //   void func() { int x = 1; takeclosure(^{ x = 7; }); }
1067  //
1068  if (const BlockDeclRefExpr *BDR = dyn_cast<BlockDeclRefExpr>(this)) {
1069    if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
1070      return MLV_NotBlockQualified;
1071  }
1072
1073  // Assigning to an 'implicit' property?
1074  if (const ObjCImplicitSetterGetterRefExpr* Expr =
1075        dyn_cast<ObjCImplicitSetterGetterRefExpr>(this)) {
1076    if (Expr->getSetterMethod() == 0)
1077      return MLV_NoSetterProperty;
1078  }
1079
1080  QualType CT = Ctx.getCanonicalType(getType());
1081
1082  if (CT.isConstQualified())
1083    return MLV_ConstQualified;
1084  if (CT->isArrayType())
1085    return MLV_ArrayType;
1086  if (CT->isIncompleteType())
1087    return MLV_IncompleteType;
1088
1089  if (const RecordType *r = CT->getAs<RecordType>()) {
1090    if (r->hasConstFields())
1091      return MLV_ConstQualified;
1092  }
1093
1094  return MLV_Valid;
1095}
1096
1097/// isOBJCGCCandidate - Check if an expression is objc gc'able.
1098/// returns true, if it is; false otherwise.
1099bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1100  switch (getStmtClass()) {
1101  default:
1102    return false;
1103  case ObjCIvarRefExprClass:
1104    return true;
1105  case Expr::UnaryOperatorClass:
1106    return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1107  case ParenExprClass:
1108    return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1109  case ImplicitCastExprClass:
1110    return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1111  case CStyleCastExprClass:
1112    return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1113  case DeclRefExprClass:
1114  case QualifiedDeclRefExprClass: {
1115    const Decl *D = cast<DeclRefExpr>(this)->getDecl();
1116    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1117      if (VD->hasGlobalStorage())
1118        return true;
1119      QualType T = VD->getType();
1120      // dereferencing to a  pointer is always a gc'able candidate,
1121      // unless it is __weak.
1122      return T->isPointerType() &&
1123             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1124    }
1125    return false;
1126  }
1127  case MemberExprClass: {
1128    const MemberExpr *M = cast<MemberExpr>(this);
1129    return M->getBase()->isOBJCGCCandidate(Ctx);
1130  }
1131  case ArraySubscriptExprClass:
1132    return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx);
1133  }
1134}
1135Expr* Expr::IgnoreParens() {
1136  Expr* E = this;
1137  while (ParenExpr* P = dyn_cast<ParenExpr>(E))
1138    E = P->getSubExpr();
1139
1140  return E;
1141}
1142
1143/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
1144/// or CastExprs or ImplicitCastExprs, returning their operand.
1145Expr *Expr::IgnoreParenCasts() {
1146  Expr *E = this;
1147  while (true) {
1148    if (ParenExpr *P = dyn_cast<ParenExpr>(E))
1149      E = P->getSubExpr();
1150    else if (CastExpr *P = dyn_cast<CastExpr>(E))
1151      E = P->getSubExpr();
1152    else
1153      return E;
1154  }
1155}
1156
1157/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1158/// value (including ptr->int casts of the same size).  Strip off any
1159/// ParenExpr or CastExprs, returning their operand.
1160Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1161  Expr *E = this;
1162  while (true) {
1163    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1164      E = P->getSubExpr();
1165      continue;
1166    }
1167
1168    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1169      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
1170      // ptr<->int casts of the same width.  We also ignore all identify casts.
1171      Expr *SE = P->getSubExpr();
1172
1173      if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1174        E = SE;
1175        continue;
1176      }
1177
1178      if ((E->getType()->isPointerType() || E->getType()->isIntegralType()) &&
1179          (SE->getType()->isPointerType() || SE->getType()->isIntegralType()) &&
1180          Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1181        E = SE;
1182        continue;
1183      }
1184    }
1185
1186    return E;
1187  }
1188}
1189
1190
1191/// hasAnyTypeDependentArguments - Determines if any of the expressions
1192/// in Exprs is type-dependent.
1193bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
1194  for (unsigned I = 0; I < NumExprs; ++I)
1195    if (Exprs[I]->isTypeDependent())
1196      return true;
1197
1198  return false;
1199}
1200
1201/// hasAnyValueDependentArguments - Determines if any of the expressions
1202/// in Exprs is value-dependent.
1203bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
1204  for (unsigned I = 0; I < NumExprs; ++I)
1205    if (Exprs[I]->isValueDependent())
1206      return true;
1207
1208  return false;
1209}
1210
1211bool Expr::isConstantInitializer(ASTContext &Ctx) const {
1212  // This function is attempting whether an expression is an initializer
1213  // which can be evaluated at compile-time.  isEvaluatable handles most
1214  // of the cases, but it can't deal with some initializer-specific
1215  // expressions, and it can't deal with aggregates; we deal with those here,
1216  // and fall back to isEvaluatable for the other cases.
1217
1218  // FIXME: This function assumes the variable being assigned to
1219  // isn't a reference type!
1220
1221  switch (getStmtClass()) {
1222  default: break;
1223  case StringLiteralClass:
1224  case ObjCStringLiteralClass:
1225  case ObjCEncodeExprClass:
1226    return true;
1227  case CompoundLiteralExprClass: {
1228    // This handles gcc's extension that allows global initializers like
1229    // "struct x {int x;} x = (struct x) {};".
1230    // FIXME: This accepts other cases it shouldn't!
1231    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
1232    return Exp->isConstantInitializer(Ctx);
1233  }
1234  case InitListExprClass: {
1235    // FIXME: This doesn't deal with fields with reference types correctly.
1236    // FIXME: This incorrectly allows pointers cast to integers to be assigned
1237    // to bitfields.
1238    const InitListExpr *Exp = cast<InitListExpr>(this);
1239    unsigned numInits = Exp->getNumInits();
1240    for (unsigned i = 0; i < numInits; i++) {
1241      if (!Exp->getInit(i)->isConstantInitializer(Ctx))
1242        return false;
1243    }
1244    return true;
1245  }
1246  case ImplicitValueInitExprClass:
1247    return true;
1248  case ParenExprClass: {
1249    return cast<ParenExpr>(this)->getSubExpr()->isConstantInitializer(Ctx);
1250  }
1251  case UnaryOperatorClass: {
1252    const UnaryOperator* Exp = cast<UnaryOperator>(this);
1253    if (Exp->getOpcode() == UnaryOperator::Extension)
1254      return Exp->getSubExpr()->isConstantInitializer(Ctx);
1255    break;
1256  }
1257  case ImplicitCastExprClass:
1258  case CStyleCastExprClass:
1259    // Handle casts with a destination that's a struct or union; this
1260    // deals with both the gcc no-op struct cast extension and the
1261    // cast-to-union extension.
1262    if (getType()->isRecordType())
1263      return cast<CastExpr>(this)->getSubExpr()->isConstantInitializer(Ctx);
1264    break;
1265  }
1266  return isEvaluatable(Ctx);
1267}
1268
1269/// isIntegerConstantExpr - this recursive routine will test if an expression is
1270/// an integer constant expression.
1271
1272/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
1273/// comma, etc
1274///
1275/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
1276/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
1277/// cast+dereference.
1278
1279// CheckICE - This function does the fundamental ICE checking: the returned
1280// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
1281// Note that to reduce code duplication, this helper does no evaluation
1282// itself; the caller checks whether the expression is evaluatable, and
1283// in the rare cases where CheckICE actually cares about the evaluated
1284// value, it calls into Evalute.
1285//
1286// Meanings of Val:
1287// 0: This expression is an ICE if it can be evaluated by Evaluate.
1288// 1: This expression is not an ICE, but if it isn't evaluated, it's
1289//    a legal subexpression for an ICE. This return value is used to handle
1290//    the comma operator in C99 mode.
1291// 2: This expression is not an ICE, and is not a legal subexpression for one.
1292
1293struct ICEDiag {
1294  unsigned Val;
1295  SourceLocation Loc;
1296
1297  public:
1298  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
1299  ICEDiag() : Val(0) {}
1300};
1301
1302ICEDiag NoDiag() { return ICEDiag(); }
1303
1304static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
1305  Expr::EvalResult EVResult;
1306  if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
1307      !EVResult.Val.isInt()) {
1308    return ICEDiag(2, E->getLocStart());
1309  }
1310  return NoDiag();
1311}
1312
1313static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
1314  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
1315  if (!E->getType()->isIntegralType()) {
1316    return ICEDiag(2, E->getLocStart());
1317  }
1318
1319  switch (E->getStmtClass()) {
1320#define STMT(Node, Base) case Expr::Node##Class:
1321#define EXPR(Node, Base)
1322#include "clang/AST/StmtNodes.def"
1323  case Expr::PredefinedExprClass:
1324  case Expr::FloatingLiteralClass:
1325  case Expr::ImaginaryLiteralClass:
1326  case Expr::StringLiteralClass:
1327  case Expr::ArraySubscriptExprClass:
1328  case Expr::MemberExprClass:
1329  case Expr::CompoundAssignOperatorClass:
1330  case Expr::CompoundLiteralExprClass:
1331  case Expr::ExtVectorElementExprClass:
1332  case Expr::InitListExprClass:
1333  case Expr::DesignatedInitExprClass:
1334  case Expr::ImplicitValueInitExprClass:
1335  case Expr::ParenListExprClass:
1336  case Expr::VAArgExprClass:
1337  case Expr::AddrLabelExprClass:
1338  case Expr::StmtExprClass:
1339  case Expr::CXXMemberCallExprClass:
1340  case Expr::CXXDynamicCastExprClass:
1341  case Expr::CXXTypeidExprClass:
1342  case Expr::CXXNullPtrLiteralExprClass:
1343  case Expr::CXXThisExprClass:
1344  case Expr::CXXThrowExprClass:
1345  case Expr::CXXConditionDeclExprClass: // FIXME: is this correct?
1346  case Expr::CXXNewExprClass:
1347  case Expr::CXXDeleteExprClass:
1348  case Expr::CXXPseudoDestructorExprClass:
1349  case Expr::UnresolvedFunctionNameExprClass:
1350  case Expr::UnresolvedDeclRefExprClass:
1351  case Expr::TemplateIdRefExprClass:
1352  case Expr::CXXConstructExprClass:
1353  case Expr::CXXBindTemporaryExprClass:
1354  case Expr::CXXExprWithTemporariesClass:
1355  case Expr::CXXTemporaryObjectExprClass:
1356  case Expr::CXXUnresolvedConstructExprClass:
1357  case Expr::CXXUnresolvedMemberExprClass:
1358  case Expr::ObjCStringLiteralClass:
1359  case Expr::ObjCEncodeExprClass:
1360  case Expr::ObjCMessageExprClass:
1361  case Expr::ObjCSelectorExprClass:
1362  case Expr::ObjCProtocolExprClass:
1363  case Expr::ObjCIvarRefExprClass:
1364  case Expr::ObjCPropertyRefExprClass:
1365  case Expr::ObjCImplicitSetterGetterRefExprClass:
1366  case Expr::ObjCSuperExprClass:
1367  case Expr::ObjCIsaExprClass:
1368  case Expr::ShuffleVectorExprClass:
1369  case Expr::BlockExprClass:
1370  case Expr::BlockDeclRefExprClass:
1371  case Expr::NoStmtClass:
1372  case Expr::ExprClass:
1373    return ICEDiag(2, E->getLocStart());
1374
1375  case Expr::GNUNullExprClass:
1376    // GCC considers the GNU __null value to be an integral constant expression.
1377    return NoDiag();
1378
1379  case Expr::ParenExprClass:
1380    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
1381  case Expr::IntegerLiteralClass:
1382  case Expr::CharacterLiteralClass:
1383  case Expr::CXXBoolLiteralExprClass:
1384  case Expr::CXXZeroInitValueExprClass:
1385  case Expr::TypesCompatibleExprClass:
1386  case Expr::UnaryTypeTraitExprClass:
1387    return NoDiag();
1388  case Expr::CallExprClass:
1389  case Expr::CXXOperatorCallExprClass: {
1390    const CallExpr *CE = cast<CallExpr>(E);
1391    if (CE->isBuiltinCall(Ctx))
1392      return CheckEvalInICE(E, Ctx);
1393    return ICEDiag(2, E->getLocStart());
1394  }
1395  case Expr::DeclRefExprClass:
1396  case Expr::QualifiedDeclRefExprClass:
1397    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
1398      return NoDiag();
1399    if (Ctx.getLangOptions().CPlusPlus &&
1400        E->getType().getCVRQualifiers() == Qualifiers::Const) {
1401      // C++ 7.1.5.1p2
1402      //   A variable of non-volatile const-qualified integral or enumeration
1403      //   type initialized by an ICE can be used in ICEs.
1404      if (const VarDecl *Dcl =
1405              dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
1406        if (Dcl->isInitKnownICE()) {
1407          // We have already checked whether this subexpression is an
1408          // integral constant expression.
1409          if (Dcl->isInitICE())
1410            return NoDiag();
1411          else
1412            return ICEDiag(2, E->getLocStart());
1413        }
1414
1415        if (const Expr *Init = Dcl->getInit()) {
1416          ICEDiag Result = CheckICE(Init, Ctx);
1417          // Cache the result of the ICE test.
1418          Dcl->setInitKnownICE(Ctx, Result.Val == 0);
1419          return Result;
1420        }
1421      }
1422    }
1423    return ICEDiag(2, E->getLocStart());
1424  case Expr::UnaryOperatorClass: {
1425    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1426    switch (Exp->getOpcode()) {
1427    case UnaryOperator::PostInc:
1428    case UnaryOperator::PostDec:
1429    case UnaryOperator::PreInc:
1430    case UnaryOperator::PreDec:
1431    case UnaryOperator::AddrOf:
1432    case UnaryOperator::Deref:
1433      return ICEDiag(2, E->getLocStart());
1434
1435    case UnaryOperator::Extension:
1436    case UnaryOperator::LNot:
1437    case UnaryOperator::Plus:
1438    case UnaryOperator::Minus:
1439    case UnaryOperator::Not:
1440    case UnaryOperator::Real:
1441    case UnaryOperator::Imag:
1442      return CheckICE(Exp->getSubExpr(), Ctx);
1443    case UnaryOperator::OffsetOf:
1444      // Note that per C99, offsetof must be an ICE. And AFAIK, using
1445      // Evaluate matches the proposed gcc behavior for cases like
1446      // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
1447      // compliance: we should warn earlier for offsetof expressions with
1448      // array subscripts that aren't ICEs, and if the array subscripts
1449      // are ICEs, the value of the offsetof must be an integer constant.
1450      return CheckEvalInICE(E, Ctx);
1451    }
1452  }
1453  case Expr::SizeOfAlignOfExprClass: {
1454    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
1455    if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
1456      return ICEDiag(2, E->getLocStart());
1457    return NoDiag();
1458  }
1459  case Expr::BinaryOperatorClass: {
1460    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1461    switch (Exp->getOpcode()) {
1462    case BinaryOperator::PtrMemD:
1463    case BinaryOperator::PtrMemI:
1464    case BinaryOperator::Assign:
1465    case BinaryOperator::MulAssign:
1466    case BinaryOperator::DivAssign:
1467    case BinaryOperator::RemAssign:
1468    case BinaryOperator::AddAssign:
1469    case BinaryOperator::SubAssign:
1470    case BinaryOperator::ShlAssign:
1471    case BinaryOperator::ShrAssign:
1472    case BinaryOperator::AndAssign:
1473    case BinaryOperator::XorAssign:
1474    case BinaryOperator::OrAssign:
1475      return ICEDiag(2, E->getLocStart());
1476
1477    case BinaryOperator::Mul:
1478    case BinaryOperator::Div:
1479    case BinaryOperator::Rem:
1480    case BinaryOperator::Add:
1481    case BinaryOperator::Sub:
1482    case BinaryOperator::Shl:
1483    case BinaryOperator::Shr:
1484    case BinaryOperator::LT:
1485    case BinaryOperator::GT:
1486    case BinaryOperator::LE:
1487    case BinaryOperator::GE:
1488    case BinaryOperator::EQ:
1489    case BinaryOperator::NE:
1490    case BinaryOperator::And:
1491    case BinaryOperator::Xor:
1492    case BinaryOperator::Or:
1493    case BinaryOperator::Comma: {
1494      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
1495      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
1496      if (Exp->getOpcode() == BinaryOperator::Div ||
1497          Exp->getOpcode() == BinaryOperator::Rem) {
1498        // Evaluate gives an error for undefined Div/Rem, so make sure
1499        // we don't evaluate one.
1500        if (LHSResult.Val != 2 && RHSResult.Val != 2) {
1501          llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
1502          if (REval == 0)
1503            return ICEDiag(1, E->getLocStart());
1504          if (REval.isSigned() && REval.isAllOnesValue()) {
1505            llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
1506            if (LEval.isMinSignedValue())
1507              return ICEDiag(1, E->getLocStart());
1508          }
1509        }
1510      }
1511      if (Exp->getOpcode() == BinaryOperator::Comma) {
1512        if (Ctx.getLangOptions().C99) {
1513          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
1514          // if it isn't evaluated.
1515          if (LHSResult.Val == 0 && RHSResult.Val == 0)
1516            return ICEDiag(1, E->getLocStart());
1517        } else {
1518          // In both C89 and C++, commas in ICEs are illegal.
1519          return ICEDiag(2, E->getLocStart());
1520        }
1521      }
1522      if (LHSResult.Val >= RHSResult.Val)
1523        return LHSResult;
1524      return RHSResult;
1525    }
1526    case BinaryOperator::LAnd:
1527    case BinaryOperator::LOr: {
1528      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
1529      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
1530      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
1531        // Rare case where the RHS has a comma "side-effect"; we need
1532        // to actually check the condition to see whether the side
1533        // with the comma is evaluated.
1534        if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
1535            (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
1536          return RHSResult;
1537        return NoDiag();
1538      }
1539
1540      if (LHSResult.Val >= RHSResult.Val)
1541        return LHSResult;
1542      return RHSResult;
1543    }
1544    }
1545  }
1546  case Expr::CastExprClass:
1547  case Expr::ImplicitCastExprClass:
1548  case Expr::ExplicitCastExprClass:
1549  case Expr::CStyleCastExprClass:
1550  case Expr::CXXFunctionalCastExprClass:
1551  case Expr::CXXNamedCastExprClass:
1552  case Expr::CXXStaticCastExprClass:
1553  case Expr::CXXReinterpretCastExprClass:
1554  case Expr::CXXConstCastExprClass: {
1555    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
1556    if (SubExpr->getType()->isIntegralType())
1557      return CheckICE(SubExpr, Ctx);
1558    if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
1559      return NoDiag();
1560    return ICEDiag(2, E->getLocStart());
1561  }
1562  case Expr::ConditionalOperatorClass: {
1563    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
1564    // If the condition (ignoring parens) is a __builtin_constant_p call,
1565    // then only the true side is actually considered in an integer constant
1566    // expression, and it is fully evaluated.  This is an important GNU
1567    // extension.  See GCC PR38377 for discussion.
1568    if (const CallExpr *CallCE = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
1569      if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
1570        Expr::EvalResult EVResult;
1571        if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
1572            !EVResult.Val.isInt()) {
1573          return ICEDiag(2, E->getLocStart());
1574        }
1575        return NoDiag();
1576      }
1577    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
1578    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
1579    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
1580    if (CondResult.Val == 2)
1581      return CondResult;
1582    if (TrueResult.Val == 2)
1583      return TrueResult;
1584    if (FalseResult.Val == 2)
1585      return FalseResult;
1586    if (CondResult.Val == 1)
1587      return CondResult;
1588    if (TrueResult.Val == 0 && FalseResult.Val == 0)
1589      return NoDiag();
1590    // Rare case where the diagnostics depend on which side is evaluated
1591    // Note that if we get here, CondResult is 0, and at least one of
1592    // TrueResult and FalseResult is non-zero.
1593    if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
1594      return FalseResult;
1595    }
1596    return TrueResult;
1597  }
1598  case Expr::CXXDefaultArgExprClass:
1599    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
1600  case Expr::ChooseExprClass: {
1601    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
1602  }
1603  }
1604
1605  // Silence a GCC warning
1606  return ICEDiag(2, E->getLocStart());
1607}
1608
1609bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
1610                                 SourceLocation *Loc, bool isEvaluated) const {
1611  ICEDiag d = CheckICE(this, Ctx);
1612  if (d.Val != 0) {
1613    if (Loc) *Loc = d.Loc;
1614    return false;
1615  }
1616  EvalResult EvalResult;
1617  if (!Evaluate(EvalResult, Ctx))
1618    assert(0 && "ICE cannot be evaluated!");
1619  assert(!EvalResult.HasSideEffects && "ICE with side effects!");
1620  assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
1621  Result = EvalResult.Val.getInt();
1622  return true;
1623}
1624
1625/// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
1626/// integer constant expression with the value zero, or if this is one that is
1627/// cast to void*.
1628bool Expr::isNullPointerConstant(ASTContext &Ctx,
1629                                 NullPointerConstantValueDependence NPC) const {
1630  if (isValueDependent()) {
1631    switch (NPC) {
1632    case NPC_NeverValueDependent:
1633      assert(false && "Unexpected value dependent expression!");
1634      // If the unthinkable happens, fall through to the safest alternative.
1635
1636    case NPC_ValueDependentIsNull:
1637      return isTypeDependent() || getType()->isIntegralType();
1638
1639    case NPC_ValueDependentIsNotNull:
1640      return false;
1641    }
1642  }
1643
1644  // Strip off a cast to void*, if it exists. Except in C++.
1645  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
1646    if (!Ctx.getLangOptions().CPlusPlus) {
1647      // Check that it is a cast to void*.
1648      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
1649        QualType Pointee = PT->getPointeeType();
1650        if (!Pointee.hasQualifiers() &&
1651            Pointee->isVoidType() &&                              // to void*
1652            CE->getSubExpr()->getType()->isIntegerType())         // from int.
1653          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
1654      }
1655    }
1656  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
1657    // Ignore the ImplicitCastExpr type entirely.
1658    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
1659  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
1660    // Accept ((void*)0) as a null pointer constant, as many other
1661    // implementations do.
1662    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
1663  } else if (const CXXDefaultArgExpr *DefaultArg
1664               = dyn_cast<CXXDefaultArgExpr>(this)) {
1665    // See through default argument expressions
1666    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
1667  } else if (isa<GNUNullExpr>(this)) {
1668    // The GNU __null extension is always a null pointer constant.
1669    return true;
1670  }
1671
1672  // C++0x nullptr_t is always a null pointer constant.
1673  if (getType()->isNullPtrType())
1674    return true;
1675
1676  // This expression must be an integer type.
1677  if (!getType()->isIntegerType())
1678    return false;
1679
1680  // If we have an integer constant expression, we need to *evaluate* it and
1681  // test for the value 0.
1682  llvm::APSInt Result;
1683  return isIntegerConstantExpr(Result, Ctx) && Result == 0;
1684}
1685
1686FieldDecl *Expr::getBitField() {
1687  Expr *E = this->IgnoreParens();
1688
1689  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
1690    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
1691      if (Field->isBitField())
1692        return Field;
1693
1694  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
1695    if (BinOp->isAssignmentOp() && BinOp->getLHS())
1696      return BinOp->getLHS()->getBitField();
1697
1698  return 0;
1699}
1700
1701/// isArrow - Return true if the base expression is a pointer to vector,
1702/// return false if the base expression is a vector.
1703bool ExtVectorElementExpr::isArrow() const {
1704  return getBase()->getType()->isPointerType();
1705}
1706
1707unsigned ExtVectorElementExpr::getNumElements() const {
1708  if (const VectorType *VT = getType()->getAs<VectorType>())
1709    return VT->getNumElements();
1710  return 1;
1711}
1712
1713/// containsDuplicateElements - Return true if any element access is repeated.
1714bool ExtVectorElementExpr::containsDuplicateElements() const {
1715  const char *compStr = Accessor->getName();
1716  unsigned length = Accessor->getLength();
1717
1718  // Halving swizzles do not contain duplicate elements.
1719  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1720      !strcmp(compStr, "even") || !strcmp(compStr, "odd"))
1721    return false;
1722
1723  // Advance past s-char prefix on hex swizzles.
1724  if (*compStr == 's' || *compStr == 'S') {
1725    compStr++;
1726    length--;
1727  }
1728
1729  for (unsigned i = 0; i != length-1; i++) {
1730    const char *s = compStr+i;
1731    for (const char c = *s++; *s; s++)
1732      if (c == *s)
1733        return true;
1734  }
1735  return false;
1736}
1737
1738/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
1739void ExtVectorElementExpr::getEncodedElementAccess(
1740                                  llvm::SmallVectorImpl<unsigned> &Elts) const {
1741  const char *compStr = Accessor->getName();
1742  if (*compStr == 's' || *compStr == 'S')
1743    compStr++;
1744
1745  bool isHi =   !strcmp(compStr, "hi");
1746  bool isLo =   !strcmp(compStr, "lo");
1747  bool isEven = !strcmp(compStr, "even");
1748  bool isOdd  = !strcmp(compStr, "odd");
1749
1750  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
1751    uint64_t Index;
1752
1753    if (isHi)
1754      Index = e + i;
1755    else if (isLo)
1756      Index = i;
1757    else if (isEven)
1758      Index = 2 * i;
1759    else if (isOdd)
1760      Index = 2 * i + 1;
1761    else
1762      Index = ExtVectorType::getAccessorIdx(compStr[i]);
1763
1764    Elts.push_back(Index);
1765  }
1766}
1767
1768// constructor for instance messages.
1769ObjCMessageExpr::ObjCMessageExpr(Expr *receiver, Selector selInfo,
1770                QualType retType, ObjCMethodDecl *mproto,
1771                SourceLocation LBrac, SourceLocation RBrac,
1772                Expr **ArgExprs, unsigned nargs)
1773  : Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1774    MethodProto(mproto) {
1775  NumArgs = nargs;
1776  SubExprs = new Stmt*[NumArgs+1];
1777  SubExprs[RECEIVER] = receiver;
1778  if (NumArgs) {
1779    for (unsigned i = 0; i != NumArgs; ++i)
1780      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1781  }
1782  LBracloc = LBrac;
1783  RBracloc = RBrac;
1784}
1785
1786// constructor for class messages.
1787// FIXME: clsName should be typed to ObjCInterfaceType
1788ObjCMessageExpr::ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo,
1789                QualType retType, ObjCMethodDecl *mproto,
1790                SourceLocation LBrac, SourceLocation RBrac,
1791                Expr **ArgExprs, unsigned nargs)
1792  : Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1793    MethodProto(mproto) {
1794  NumArgs = nargs;
1795  SubExprs = new Stmt*[NumArgs+1];
1796  SubExprs[RECEIVER] = (Expr*) ((uintptr_t) clsName | IsClsMethDeclUnknown);
1797  if (NumArgs) {
1798    for (unsigned i = 0; i != NumArgs; ++i)
1799      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1800  }
1801  LBracloc = LBrac;
1802  RBracloc = RBrac;
1803}
1804
1805// constructor for class messages.
1806ObjCMessageExpr::ObjCMessageExpr(ObjCInterfaceDecl *cls, Selector selInfo,
1807                                 QualType retType, ObjCMethodDecl *mproto,
1808                                 SourceLocation LBrac, SourceLocation RBrac,
1809                                 Expr **ArgExprs, unsigned nargs)
1810: Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1811MethodProto(mproto) {
1812  NumArgs = nargs;
1813  SubExprs = new Stmt*[NumArgs+1];
1814  SubExprs[RECEIVER] = (Expr*) ((uintptr_t) cls | IsClsMethDeclKnown);
1815  if (NumArgs) {
1816    for (unsigned i = 0; i != NumArgs; ++i)
1817      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1818  }
1819  LBracloc = LBrac;
1820  RBracloc = RBrac;
1821}
1822
1823ObjCMessageExpr::ClassInfo ObjCMessageExpr::getClassInfo() const {
1824  uintptr_t x = (uintptr_t) SubExprs[RECEIVER];
1825  switch (x & Flags) {
1826    default:
1827      assert(false && "Invalid ObjCMessageExpr.");
1828    case IsInstMeth:
1829      return ClassInfo(0, 0);
1830    case IsClsMethDeclUnknown:
1831      return ClassInfo(0, (IdentifierInfo*) (x & ~Flags));
1832    case IsClsMethDeclKnown: {
1833      ObjCInterfaceDecl* D = (ObjCInterfaceDecl*) (x & ~Flags);
1834      return ClassInfo(D, D->getIdentifier());
1835    }
1836  }
1837}
1838
1839void ObjCMessageExpr::setClassInfo(const ObjCMessageExpr::ClassInfo &CI) {
1840  if (CI.first == 0 && CI.second == 0)
1841    SubExprs[RECEIVER] = (Expr*)((uintptr_t)0 | IsInstMeth);
1842  else if (CI.first == 0)
1843    SubExprs[RECEIVER] = (Expr*)((uintptr_t)CI.second | IsClsMethDeclUnknown);
1844  else
1845    SubExprs[RECEIVER] = (Expr*)((uintptr_t)CI.first | IsClsMethDeclKnown);
1846}
1847
1848
1849bool ChooseExpr::isConditionTrue(ASTContext &C) const {
1850  return getCond()->EvaluateAsInt(C) != 0;
1851}
1852
1853void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
1854                                 unsigned NumExprs) {
1855  if (SubExprs) C.Deallocate(SubExprs);
1856
1857  SubExprs = new (C) Stmt* [NumExprs];
1858  this->NumExprs = NumExprs;
1859  memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
1860}
1861
1862void ShuffleVectorExpr::DoDestroy(ASTContext& C) {
1863  DestroyChildren(C);
1864  if (SubExprs) C.Deallocate(SubExprs);
1865  this->~ShuffleVectorExpr();
1866  C.Deallocate(this);
1867}
1868
1869void SizeOfAlignOfExpr::DoDestroy(ASTContext& C) {
1870  // Override default behavior of traversing children. If this has a type
1871  // operand and the type is a variable-length array, the child iteration
1872  // will iterate over the size expression. However, this expression belongs
1873  // to the type, not to this, so we don't want to delete it.
1874  // We still want to delete this expression.
1875  if (isArgumentType()) {
1876    this->~SizeOfAlignOfExpr();
1877    C.Deallocate(this);
1878  }
1879  else
1880    Expr::DoDestroy(C);
1881}
1882
1883//===----------------------------------------------------------------------===//
1884//  DesignatedInitExpr
1885//===----------------------------------------------------------------------===//
1886
1887IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
1888  assert(Kind == FieldDesignator && "Only valid on a field designator");
1889  if (Field.NameOrField & 0x01)
1890    return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
1891  else
1892    return getField()->getIdentifier();
1893}
1894
1895DesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
1896                                       const Designator *Designators,
1897                                       SourceLocation EqualOrColonLoc,
1898                                       bool GNUSyntax,
1899                                       Expr **IndexExprs,
1900                                       unsigned NumIndexExprs,
1901                                       Expr *Init)
1902  : Expr(DesignatedInitExprClass, Ty,
1903         Init->isTypeDependent(), Init->isValueDependent()),
1904    EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
1905    NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
1906  this->Designators = new Designator[NumDesignators];
1907
1908  // Record the initializer itself.
1909  child_iterator Child = child_begin();
1910  *Child++ = Init;
1911
1912  // Copy the designators and their subexpressions, computing
1913  // value-dependence along the way.
1914  unsigned IndexIdx = 0;
1915  for (unsigned I = 0; I != NumDesignators; ++I) {
1916    this->Designators[I] = Designators[I];
1917
1918    if (this->Designators[I].isArrayDesignator()) {
1919      // Compute type- and value-dependence.
1920      Expr *Index = IndexExprs[IndexIdx];
1921      ValueDependent = ValueDependent ||
1922        Index->isTypeDependent() || Index->isValueDependent();
1923
1924      // Copy the index expressions into permanent storage.
1925      *Child++ = IndexExprs[IndexIdx++];
1926    } else if (this->Designators[I].isArrayRangeDesignator()) {
1927      // Compute type- and value-dependence.
1928      Expr *Start = IndexExprs[IndexIdx];
1929      Expr *End = IndexExprs[IndexIdx + 1];
1930      ValueDependent = ValueDependent ||
1931        Start->isTypeDependent() || Start->isValueDependent() ||
1932        End->isTypeDependent() || End->isValueDependent();
1933
1934      // Copy the start/end expressions into permanent storage.
1935      *Child++ = IndexExprs[IndexIdx++];
1936      *Child++ = IndexExprs[IndexIdx++];
1937    }
1938  }
1939
1940  assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
1941}
1942
1943DesignatedInitExpr *
1944DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
1945                           unsigned NumDesignators,
1946                           Expr **IndexExprs, unsigned NumIndexExprs,
1947                           SourceLocation ColonOrEqualLoc,
1948                           bool UsesColonSyntax, Expr *Init) {
1949  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
1950                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
1951  return new (Mem) DesignatedInitExpr(C.VoidTy, NumDesignators, Designators,
1952                                      ColonOrEqualLoc, UsesColonSyntax,
1953                                      IndexExprs, NumIndexExprs, Init);
1954}
1955
1956DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
1957                                                    unsigned NumIndexExprs) {
1958  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
1959                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
1960  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
1961}
1962
1963void DesignatedInitExpr::setDesignators(const Designator *Desigs,
1964                                        unsigned NumDesigs) {
1965  if (Designators)
1966    delete [] Designators;
1967
1968  Designators = new Designator[NumDesigs];
1969  NumDesignators = NumDesigs;
1970  for (unsigned I = 0; I != NumDesigs; ++I)
1971    Designators[I] = Desigs[I];
1972}
1973
1974SourceRange DesignatedInitExpr::getSourceRange() const {
1975  SourceLocation StartLoc;
1976  Designator &First =
1977    *const_cast<DesignatedInitExpr*>(this)->designators_begin();
1978  if (First.isFieldDesignator()) {
1979    if (GNUSyntax)
1980      StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
1981    else
1982      StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
1983  } else
1984    StartLoc =
1985      SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
1986  return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
1987}
1988
1989Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
1990  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
1991  char* Ptr = static_cast<char*>(static_cast<void *>(this));
1992  Ptr += sizeof(DesignatedInitExpr);
1993  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
1994  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
1995}
1996
1997Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
1998  assert(D.Kind == Designator::ArrayRangeDesignator &&
1999         "Requires array range designator");
2000  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2001  Ptr += sizeof(DesignatedInitExpr);
2002  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2003  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2004}
2005
2006Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
2007  assert(D.Kind == Designator::ArrayRangeDesignator &&
2008         "Requires array range designator");
2009  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2010  Ptr += sizeof(DesignatedInitExpr);
2011  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2012  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2013}
2014
2015/// \brief Replaces the designator at index @p Idx with the series
2016/// of designators in [First, Last).
2017void DesignatedInitExpr::ExpandDesignator(unsigned Idx,
2018                                          const Designator *First,
2019                                          const Designator *Last) {
2020  unsigned NumNewDesignators = Last - First;
2021  if (NumNewDesignators == 0) {
2022    std::copy_backward(Designators + Idx + 1,
2023                       Designators + NumDesignators,
2024                       Designators + Idx);
2025    --NumNewDesignators;
2026    return;
2027  } else if (NumNewDesignators == 1) {
2028    Designators[Idx] = *First;
2029    return;
2030  }
2031
2032  Designator *NewDesignators
2033    = new Designator[NumDesignators - 1 + NumNewDesignators];
2034  std::copy(Designators, Designators + Idx, NewDesignators);
2035  std::copy(First, Last, NewDesignators + Idx);
2036  std::copy(Designators + Idx + 1, Designators + NumDesignators,
2037            NewDesignators + Idx + NumNewDesignators);
2038  delete [] Designators;
2039  Designators = NewDesignators;
2040  NumDesignators = NumDesignators - 1 + NumNewDesignators;
2041}
2042
2043void DesignatedInitExpr::DoDestroy(ASTContext &C) {
2044  delete [] Designators;
2045  Expr::DoDestroy(C);
2046}
2047
2048ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
2049                             Expr **exprs, unsigned nexprs,
2050                             SourceLocation rparenloc)
2051: Expr(ParenListExprClass, QualType(),
2052       hasAnyTypeDependentArguments(exprs, nexprs),
2053       hasAnyValueDependentArguments(exprs, nexprs)),
2054  NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
2055
2056  Exprs = new (C) Stmt*[nexprs];
2057  for (unsigned i = 0; i != nexprs; ++i)
2058    Exprs[i] = exprs[i];
2059}
2060
2061void ParenListExpr::DoDestroy(ASTContext& C) {
2062  DestroyChildren(C);
2063  if (Exprs) C.Deallocate(Exprs);
2064  this->~ParenListExpr();
2065  C.Deallocate(this);
2066}
2067
2068//===----------------------------------------------------------------------===//
2069//  ExprIterator.
2070//===----------------------------------------------------------------------===//
2071
2072Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2073Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2074Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2075const Expr* ConstExprIterator::operator[](size_t idx) const {
2076  return cast<Expr>(I[idx]);
2077}
2078const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2079const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2080
2081//===----------------------------------------------------------------------===//
2082//  Child Iterators for iterating over subexpressions/substatements
2083//===----------------------------------------------------------------------===//
2084
2085// DeclRefExpr
2086Stmt::child_iterator DeclRefExpr::child_begin() { return child_iterator(); }
2087Stmt::child_iterator DeclRefExpr::child_end() { return child_iterator(); }
2088
2089// ObjCIvarRefExpr
2090Stmt::child_iterator ObjCIvarRefExpr::child_begin() { return &Base; }
2091Stmt::child_iterator ObjCIvarRefExpr::child_end() { return &Base+1; }
2092
2093// ObjCPropertyRefExpr
2094Stmt::child_iterator ObjCPropertyRefExpr::child_begin() { return &Base; }
2095Stmt::child_iterator ObjCPropertyRefExpr::child_end() { return &Base+1; }
2096
2097// ObjCImplicitSetterGetterRefExpr
2098Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_begin() {
2099  return &Base;
2100}
2101Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_end() {
2102  return &Base+1;
2103}
2104
2105// ObjCSuperExpr
2106Stmt::child_iterator ObjCSuperExpr::child_begin() { return child_iterator(); }
2107Stmt::child_iterator ObjCSuperExpr::child_end() { return child_iterator(); }
2108
2109// ObjCIsaExpr
2110Stmt::child_iterator ObjCIsaExpr::child_begin() { return &Base; }
2111Stmt::child_iterator ObjCIsaExpr::child_end() { return &Base+1; }
2112
2113// PredefinedExpr
2114Stmt::child_iterator PredefinedExpr::child_begin() { return child_iterator(); }
2115Stmt::child_iterator PredefinedExpr::child_end() { return child_iterator(); }
2116
2117// IntegerLiteral
2118Stmt::child_iterator IntegerLiteral::child_begin() { return child_iterator(); }
2119Stmt::child_iterator IntegerLiteral::child_end() { return child_iterator(); }
2120
2121// CharacterLiteral
2122Stmt::child_iterator CharacterLiteral::child_begin() { return child_iterator();}
2123Stmt::child_iterator CharacterLiteral::child_end() { return child_iterator(); }
2124
2125// FloatingLiteral
2126Stmt::child_iterator FloatingLiteral::child_begin() { return child_iterator(); }
2127Stmt::child_iterator FloatingLiteral::child_end() { return child_iterator(); }
2128
2129// ImaginaryLiteral
2130Stmt::child_iterator ImaginaryLiteral::child_begin() { return &Val; }
2131Stmt::child_iterator ImaginaryLiteral::child_end() { return &Val+1; }
2132
2133// StringLiteral
2134Stmt::child_iterator StringLiteral::child_begin() { return child_iterator(); }
2135Stmt::child_iterator StringLiteral::child_end() { return child_iterator(); }
2136
2137// ParenExpr
2138Stmt::child_iterator ParenExpr::child_begin() { return &Val; }
2139Stmt::child_iterator ParenExpr::child_end() { return &Val+1; }
2140
2141// UnaryOperator
2142Stmt::child_iterator UnaryOperator::child_begin() { return &Val; }
2143Stmt::child_iterator UnaryOperator::child_end() { return &Val+1; }
2144
2145// SizeOfAlignOfExpr
2146Stmt::child_iterator SizeOfAlignOfExpr::child_begin() {
2147  // If this is of a type and the type is a VLA type (and not a typedef), the
2148  // size expression of the VLA needs to be treated as an executable expression.
2149  // Why isn't this weirdness documented better in StmtIterator?
2150  if (isArgumentType()) {
2151    if (VariableArrayType* T = dyn_cast<VariableArrayType>(
2152                                   getArgumentType().getTypePtr()))
2153      return child_iterator(T);
2154    return child_iterator();
2155  }
2156  return child_iterator(&Argument.Ex);
2157}
2158Stmt::child_iterator SizeOfAlignOfExpr::child_end() {
2159  if (isArgumentType())
2160    return child_iterator();
2161  return child_iterator(&Argument.Ex + 1);
2162}
2163
2164// ArraySubscriptExpr
2165Stmt::child_iterator ArraySubscriptExpr::child_begin() {
2166  return &SubExprs[0];
2167}
2168Stmt::child_iterator ArraySubscriptExpr::child_end() {
2169  return &SubExprs[0]+END_EXPR;
2170}
2171
2172// CallExpr
2173Stmt::child_iterator CallExpr::child_begin() {
2174  return &SubExprs[0];
2175}
2176Stmt::child_iterator CallExpr::child_end() {
2177  return &SubExprs[0]+NumArgs+ARGS_START;
2178}
2179
2180// MemberExpr
2181Stmt::child_iterator MemberExpr::child_begin() { return &Base; }
2182Stmt::child_iterator MemberExpr::child_end() { return &Base+1; }
2183
2184// ExtVectorElementExpr
2185Stmt::child_iterator ExtVectorElementExpr::child_begin() { return &Base; }
2186Stmt::child_iterator ExtVectorElementExpr::child_end() { return &Base+1; }
2187
2188// CompoundLiteralExpr
2189Stmt::child_iterator CompoundLiteralExpr::child_begin() { return &Init; }
2190Stmt::child_iterator CompoundLiteralExpr::child_end() { return &Init+1; }
2191
2192// CastExpr
2193Stmt::child_iterator CastExpr::child_begin() { return &Op; }
2194Stmt::child_iterator CastExpr::child_end() { return &Op+1; }
2195
2196// BinaryOperator
2197Stmt::child_iterator BinaryOperator::child_begin() {
2198  return &SubExprs[0];
2199}
2200Stmt::child_iterator BinaryOperator::child_end() {
2201  return &SubExprs[0]+END_EXPR;
2202}
2203
2204// ConditionalOperator
2205Stmt::child_iterator ConditionalOperator::child_begin() {
2206  return &SubExprs[0];
2207}
2208Stmt::child_iterator ConditionalOperator::child_end() {
2209  return &SubExprs[0]+END_EXPR;
2210}
2211
2212// AddrLabelExpr
2213Stmt::child_iterator AddrLabelExpr::child_begin() { return child_iterator(); }
2214Stmt::child_iterator AddrLabelExpr::child_end() { return child_iterator(); }
2215
2216// StmtExpr
2217Stmt::child_iterator StmtExpr::child_begin() { return &SubStmt; }
2218Stmt::child_iterator StmtExpr::child_end() { return &SubStmt+1; }
2219
2220// TypesCompatibleExpr
2221Stmt::child_iterator TypesCompatibleExpr::child_begin() {
2222  return child_iterator();
2223}
2224
2225Stmt::child_iterator TypesCompatibleExpr::child_end() {
2226  return child_iterator();
2227}
2228
2229// ChooseExpr
2230Stmt::child_iterator ChooseExpr::child_begin() { return &SubExprs[0]; }
2231Stmt::child_iterator ChooseExpr::child_end() { return &SubExprs[0]+END_EXPR; }
2232
2233// GNUNullExpr
2234Stmt::child_iterator GNUNullExpr::child_begin() { return child_iterator(); }
2235Stmt::child_iterator GNUNullExpr::child_end() { return child_iterator(); }
2236
2237// ShuffleVectorExpr
2238Stmt::child_iterator ShuffleVectorExpr::child_begin() {
2239  return &SubExprs[0];
2240}
2241Stmt::child_iterator ShuffleVectorExpr::child_end() {
2242  return &SubExprs[0]+NumExprs;
2243}
2244
2245// VAArgExpr
2246Stmt::child_iterator VAArgExpr::child_begin() { return &Val; }
2247Stmt::child_iterator VAArgExpr::child_end() { return &Val+1; }
2248
2249// InitListExpr
2250Stmt::child_iterator InitListExpr::child_begin() {
2251  return InitExprs.size() ? &InitExprs[0] : 0;
2252}
2253Stmt::child_iterator InitListExpr::child_end() {
2254  return InitExprs.size() ? &InitExprs[0] + InitExprs.size() : 0;
2255}
2256
2257// DesignatedInitExpr
2258Stmt::child_iterator DesignatedInitExpr::child_begin() {
2259  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2260  Ptr += sizeof(DesignatedInitExpr);
2261  return reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2262}
2263Stmt::child_iterator DesignatedInitExpr::child_end() {
2264  return child_iterator(&*child_begin() + NumSubExprs);
2265}
2266
2267// ImplicitValueInitExpr
2268Stmt::child_iterator ImplicitValueInitExpr::child_begin() {
2269  return child_iterator();
2270}
2271
2272Stmt::child_iterator ImplicitValueInitExpr::child_end() {
2273  return child_iterator();
2274}
2275
2276// ParenListExpr
2277Stmt::child_iterator ParenListExpr::child_begin() {
2278  return &Exprs[0];
2279}
2280Stmt::child_iterator ParenListExpr::child_end() {
2281  return &Exprs[0]+NumExprs;
2282}
2283
2284// ObjCStringLiteral
2285Stmt::child_iterator ObjCStringLiteral::child_begin() {
2286  return &String;
2287}
2288Stmt::child_iterator ObjCStringLiteral::child_end() {
2289  return &String+1;
2290}
2291
2292// ObjCEncodeExpr
2293Stmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); }
2294Stmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); }
2295
2296// ObjCSelectorExpr
2297Stmt::child_iterator ObjCSelectorExpr::child_begin() {
2298  return child_iterator();
2299}
2300Stmt::child_iterator ObjCSelectorExpr::child_end() {
2301  return child_iterator();
2302}
2303
2304// ObjCProtocolExpr
2305Stmt::child_iterator ObjCProtocolExpr::child_begin() {
2306  return child_iterator();
2307}
2308Stmt::child_iterator ObjCProtocolExpr::child_end() {
2309  return child_iterator();
2310}
2311
2312// ObjCMessageExpr
2313Stmt::child_iterator ObjCMessageExpr::child_begin() {
2314  return getReceiver() ? &SubExprs[0] : &SubExprs[0] + ARGS_START;
2315}
2316Stmt::child_iterator ObjCMessageExpr::child_end() {
2317  return &SubExprs[0]+ARGS_START+getNumArgs();
2318}
2319
2320// Blocks
2321Stmt::child_iterator BlockExpr::child_begin() { return child_iterator(); }
2322Stmt::child_iterator BlockExpr::child_end() { return child_iterator(); }
2323
2324Stmt::child_iterator BlockDeclRefExpr::child_begin() { return child_iterator();}
2325Stmt::child_iterator BlockDeclRefExpr::child_end() { return child_iterator(); }
2326