Expr.cpp revision 08f92e3a5dead1f1ee656678a7f06e43279d6e50
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/Lex/LiteralSupport.h"
24#include "clang/Lex/Lexer.h"
25#include "clang/Basic/Builtins.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TargetInfo.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31using namespace clang;
32
33void Expr::ANCHOR() {} // key function for Expr class.
34
35/// isKnownToHaveBooleanValue - Return true if this is an integer expression
36/// that is known to return 0 or 1.  This happens for _Bool/bool expressions
37/// but also int expressions which are produced by things like comparisons in
38/// C.
39bool Expr::isKnownToHaveBooleanValue() const {
40  // If this value has _Bool type, it is obvious 0/1.
41  if (getType()->isBooleanType()) return true;
42  // If this is a non-scalar-integer type, we don't care enough to try.
43  if (!getType()->isIntegralOrEnumerationType()) return false;
44
45  if (const ParenExpr *PE = dyn_cast<ParenExpr>(this))
46    return PE->getSubExpr()->isKnownToHaveBooleanValue();
47
48  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(this)) {
49    switch (UO->getOpcode()) {
50    case UO_Plus:
51    case UO_Extension:
52      return UO->getSubExpr()->isKnownToHaveBooleanValue();
53    default:
54      return false;
55    }
56  }
57
58  // Only look through implicit casts.  If the user writes
59  // '(int) (a && b)' treat it as an arbitrary int.
60  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(this))
61    return CE->getSubExpr()->isKnownToHaveBooleanValue();
62
63  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(this)) {
64    switch (BO->getOpcode()) {
65    default: return false;
66    case BO_LT:   // Relational operators.
67    case BO_GT:
68    case BO_LE:
69    case BO_GE:
70    case BO_EQ:   // Equality operators.
71    case BO_NE:
72    case BO_LAnd: // AND operator.
73    case BO_LOr:  // Logical OR operator.
74      return true;
75
76    case BO_And:  // Bitwise AND operator.
77    case BO_Xor:  // Bitwise XOR operator.
78    case BO_Or:   // Bitwise OR operator.
79      // Handle things like (x==2)|(y==12).
80      return BO->getLHS()->isKnownToHaveBooleanValue() &&
81             BO->getRHS()->isKnownToHaveBooleanValue();
82
83    case BO_Comma:
84    case BO_Assign:
85      return BO->getRHS()->isKnownToHaveBooleanValue();
86    }
87  }
88
89  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(this))
90    return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
91           CO->getFalseExpr()->isKnownToHaveBooleanValue();
92
93  return false;
94}
95
96//===----------------------------------------------------------------------===//
97// Primary Expressions.
98//===----------------------------------------------------------------------===//
99
100void ExplicitTemplateArgumentList::initializeFrom(
101                                      const TemplateArgumentListInfo &Info) {
102  LAngleLoc = Info.getLAngleLoc();
103  RAngleLoc = Info.getRAngleLoc();
104  NumTemplateArgs = Info.size();
105
106  TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
107  for (unsigned i = 0; i != NumTemplateArgs; ++i)
108    new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
109}
110
111void ExplicitTemplateArgumentList::copyInto(
112                                      TemplateArgumentListInfo &Info) const {
113  Info.setLAngleLoc(LAngleLoc);
114  Info.setRAngleLoc(RAngleLoc);
115  for (unsigned I = 0; I != NumTemplateArgs; ++I)
116    Info.addArgument(getTemplateArgs()[I]);
117}
118
119std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
120  return sizeof(ExplicitTemplateArgumentList) +
121         sizeof(TemplateArgumentLoc) * NumTemplateArgs;
122}
123
124std::size_t ExplicitTemplateArgumentList::sizeFor(
125                                      const TemplateArgumentListInfo &Info) {
126  return sizeFor(Info.size());
127}
128
129void DeclRefExpr::computeDependence() {
130  ExprBits.TypeDependent = false;
131  ExprBits.ValueDependent = false;
132
133  NamedDecl *D = getDecl();
134
135  // (TD) C++ [temp.dep.expr]p3:
136  //   An id-expression is type-dependent if it contains:
137  //
138  // and
139  //
140  // (VD) C++ [temp.dep.constexpr]p2:
141  //  An identifier is value-dependent if it is:
142
143  //  (TD)  - an identifier that was declared with dependent type
144  //  (VD)  - a name declared with a dependent type,
145  if (getType()->isDependentType()) {
146    ExprBits.TypeDependent = true;
147    ExprBits.ValueDependent = true;
148  }
149  //  (TD)  - a conversion-function-id that specifies a dependent type
150  else if (D->getDeclName().getNameKind()
151                               == DeclarationName::CXXConversionFunctionName &&
152           D->getDeclName().getCXXNameType()->isDependentType()) {
153    ExprBits.TypeDependent = true;
154    ExprBits.ValueDependent = true;
155  }
156  //  (TD)  - a template-id that is dependent,
157  else if (hasExplicitTemplateArgs() &&
158           TemplateSpecializationType::anyDependentTemplateArguments(
159                                                       getTemplateArgs(),
160                                                       getNumTemplateArgs())) {
161    ExprBits.TypeDependent = true;
162    ExprBits.ValueDependent = true;
163  }
164  //  (VD)  - the name of a non-type template parameter,
165  else if (isa<NonTypeTemplateParmDecl>(D))
166    ExprBits.ValueDependent = true;
167  //  (VD) - a constant with integral or enumeration type and is
168  //         initialized with an expression that is value-dependent.
169  else if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
170    if (Var->getType()->isIntegralOrEnumerationType() &&
171        Var->getType().getCVRQualifiers() == Qualifiers::Const) {
172      if (const Expr *Init = Var->getAnyInitializer())
173        if (Init->isValueDependent())
174          ExprBits.ValueDependent = true;
175    }
176    // (VD) - FIXME: Missing from the standard:
177    //      -  a member function or a static data member of the current
178    //         instantiation
179    else if (Var->isStaticDataMember() &&
180             Var->getDeclContext()->isDependentContext())
181      ExprBits.ValueDependent = true;
182  }
183  // (VD) - FIXME: Missing from the standard:
184  //      -  a member function or a static data member of the current
185  //         instantiation
186  else if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext())
187    ExprBits.ValueDependent = true;
188  //  (TD)  - a nested-name-specifier or a qualified-id that names a
189  //          member of an unknown specialization.
190  //        (handled by DependentScopeDeclRefExpr)
191}
192
193DeclRefExpr::DeclRefExpr(NestedNameSpecifier *Qualifier,
194                         SourceRange QualifierRange,
195                         ValueDecl *D, SourceLocation NameLoc,
196                         const TemplateArgumentListInfo *TemplateArgs,
197                         QualType T)
198  : Expr(DeclRefExprClass, T, false, false),
199    DecoratedD(D,
200               (Qualifier? HasQualifierFlag : 0) |
201               (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
202    Loc(NameLoc) {
203  if (Qualifier) {
204    NameQualifier *NQ = getNameQualifier();
205    NQ->NNS = Qualifier;
206    NQ->Range = QualifierRange;
207  }
208
209  if (TemplateArgs)
210    getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
211
212  computeDependence();
213}
214
215DeclRefExpr::DeclRefExpr(NestedNameSpecifier *Qualifier,
216                         SourceRange QualifierRange,
217                         ValueDecl *D, const DeclarationNameInfo &NameInfo,
218                         const TemplateArgumentListInfo *TemplateArgs,
219                         QualType T)
220  : Expr(DeclRefExprClass, T, false, false),
221    DecoratedD(D,
222               (Qualifier? HasQualifierFlag : 0) |
223               (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
224    Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
225  if (Qualifier) {
226    NameQualifier *NQ = getNameQualifier();
227    NQ->NNS = Qualifier;
228    NQ->Range = QualifierRange;
229  }
230
231  if (TemplateArgs)
232    getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
233
234  computeDependence();
235}
236
237DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
238                                 NestedNameSpecifier *Qualifier,
239                                 SourceRange QualifierRange,
240                                 ValueDecl *D,
241                                 SourceLocation NameLoc,
242                                 QualType T,
243                                 const TemplateArgumentListInfo *TemplateArgs) {
244  return Create(Context, Qualifier, QualifierRange, D,
245                DeclarationNameInfo(D->getDeclName(), NameLoc),
246                T, TemplateArgs);
247}
248
249DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
250                                 NestedNameSpecifier *Qualifier,
251                                 SourceRange QualifierRange,
252                                 ValueDecl *D,
253                                 const DeclarationNameInfo &NameInfo,
254                                 QualType T,
255                                 const TemplateArgumentListInfo *TemplateArgs) {
256  std::size_t Size = sizeof(DeclRefExpr);
257  if (Qualifier != 0)
258    Size += sizeof(NameQualifier);
259
260  if (TemplateArgs)
261    Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
262
263  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
264  return new (Mem) DeclRefExpr(Qualifier, QualifierRange, D, NameInfo,
265                               TemplateArgs, T);
266}
267
268DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context, bool HasQualifier,
269                                      unsigned NumTemplateArgs) {
270  std::size_t Size = sizeof(DeclRefExpr);
271  if (HasQualifier)
272    Size += sizeof(NameQualifier);
273
274  if (NumTemplateArgs)
275    Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
276
277  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
278  return new (Mem) DeclRefExpr(EmptyShell());
279}
280
281SourceRange DeclRefExpr::getSourceRange() const {
282  SourceRange R = getNameInfo().getSourceRange();
283  if (hasQualifier())
284    R.setBegin(getQualifierRange().getBegin());
285  if (hasExplicitTemplateArgs())
286    R.setEnd(getRAngleLoc());
287  return R;
288}
289
290// FIXME: Maybe this should use DeclPrinter with a special "print predefined
291// expr" policy instead.
292std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
293  ASTContext &Context = CurrentDecl->getASTContext();
294
295  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
296    if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
297      return FD->getNameAsString();
298
299    llvm::SmallString<256> Name;
300    llvm::raw_svector_ostream Out(Name);
301
302    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
303      if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
304        Out << "virtual ";
305      if (MD->isStatic())
306        Out << "static ";
307    }
308
309    PrintingPolicy Policy(Context.getLangOptions());
310
311    std::string Proto = FD->getQualifiedNameAsString(Policy);
312
313    const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
314    const FunctionProtoType *FT = 0;
315    if (FD->hasWrittenPrototype())
316      FT = dyn_cast<FunctionProtoType>(AFT);
317
318    Proto += "(";
319    if (FT) {
320      llvm::raw_string_ostream POut(Proto);
321      for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
322        if (i) POut << ", ";
323        std::string Param;
324        FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
325        POut << Param;
326      }
327
328      if (FT->isVariadic()) {
329        if (FD->getNumParams()) POut << ", ";
330        POut << "...";
331      }
332    }
333    Proto += ")";
334
335    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
336      Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
337      if (ThisQuals.hasConst())
338        Proto += " const";
339      if (ThisQuals.hasVolatile())
340        Proto += " volatile";
341    }
342
343    if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
344      AFT->getResultType().getAsStringInternal(Proto, Policy);
345
346    Out << Proto;
347
348    Out.flush();
349    return Name.str().str();
350  }
351  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
352    llvm::SmallString<256> Name;
353    llvm::raw_svector_ostream Out(Name);
354    Out << (MD->isInstanceMethod() ? '-' : '+');
355    Out << '[';
356
357    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
358    // a null check to avoid a crash.
359    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
360      Out << ID;
361
362    if (const ObjCCategoryImplDecl *CID =
363        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
364      Out << '(' << CID << ')';
365
366    Out <<  ' ';
367    Out << MD->getSelector().getAsString();
368    Out <<  ']';
369
370    Out.flush();
371    return Name.str().str();
372  }
373  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
374    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
375    return "top level";
376  }
377  return "";
378}
379
380void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
381  if (hasAllocation())
382    C.Deallocate(pVal);
383
384  BitWidth = Val.getBitWidth();
385  unsigned NumWords = Val.getNumWords();
386  const uint64_t* Words = Val.getRawData();
387  if (NumWords > 1) {
388    pVal = new (C) uint64_t[NumWords];
389    std::copy(Words, Words + NumWords, pVal);
390  } else if (NumWords == 1)
391    VAL = Words[0];
392  else
393    VAL = 0;
394}
395
396IntegerLiteral *
397IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
398                       QualType type, SourceLocation l) {
399  return new (C) IntegerLiteral(C, V, type, l);
400}
401
402IntegerLiteral *
403IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
404  return new (C) IntegerLiteral(Empty);
405}
406
407FloatingLiteral *
408FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
409                        bool isexact, QualType Type, SourceLocation L) {
410  return new (C) FloatingLiteral(C, V, isexact, Type, L);
411}
412
413FloatingLiteral *
414FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
415  return new (C) FloatingLiteral(Empty);
416}
417
418/// getValueAsApproximateDouble - This returns the value as an inaccurate
419/// double.  Note that this may cause loss of precision, but is useful for
420/// debugging dumps, etc.
421double FloatingLiteral::getValueAsApproximateDouble() const {
422  llvm::APFloat V = getValue();
423  bool ignored;
424  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
425            &ignored);
426  return V.convertToDouble();
427}
428
429StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
430                                     unsigned ByteLength, bool Wide,
431                                     QualType Ty,
432                                     const SourceLocation *Loc,
433                                     unsigned NumStrs) {
434  // Allocate enough space for the StringLiteral plus an array of locations for
435  // any concatenated string tokens.
436  void *Mem = C.Allocate(sizeof(StringLiteral)+
437                         sizeof(SourceLocation)*(NumStrs-1),
438                         llvm::alignOf<StringLiteral>());
439  StringLiteral *SL = new (Mem) StringLiteral(Ty);
440
441  // OPTIMIZE: could allocate this appended to the StringLiteral.
442  char *AStrData = new (C, 1) char[ByteLength];
443  memcpy(AStrData, StrData, ByteLength);
444  SL->StrData = AStrData;
445  SL->ByteLength = ByteLength;
446  SL->IsWide = Wide;
447  SL->TokLocs[0] = Loc[0];
448  SL->NumConcatenated = NumStrs;
449
450  if (NumStrs != 1)
451    memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
452  return SL;
453}
454
455StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
456  void *Mem = C.Allocate(sizeof(StringLiteral)+
457                         sizeof(SourceLocation)*(NumStrs-1),
458                         llvm::alignOf<StringLiteral>());
459  StringLiteral *SL = new (Mem) StringLiteral(QualType());
460  SL->StrData = 0;
461  SL->ByteLength = 0;
462  SL->NumConcatenated = NumStrs;
463  return SL;
464}
465
466void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
467  char *AStrData = new (C, 1) char[Str.size()];
468  memcpy(AStrData, Str.data(), Str.size());
469  StrData = AStrData;
470  ByteLength = Str.size();
471}
472
473/// getLocationOfByte - Return a source location that points to the specified
474/// byte of this string literal.
475///
476/// Strings are amazingly complex.  They can be formed from multiple tokens and
477/// can have escape sequences in them in addition to the usual trigraph and
478/// escaped newline business.  This routine handles this complexity.
479///
480SourceLocation StringLiteral::
481getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
482                  const LangOptions &Features, const TargetInfo &Target) const {
483  assert(!isWide() && "This doesn't work for wide strings yet");
484
485  // Loop over all of the tokens in this string until we find the one that
486  // contains the byte we're looking for.
487  unsigned TokNo = 0;
488  while (1) {
489    assert(TokNo < getNumConcatenated() && "Invalid byte number!");
490    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
491
492    // Get the spelling of the string so that we can get the data that makes up
493    // the string literal, not the identifier for the macro it is potentially
494    // expanded through.
495    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
496
497    // Re-lex the token to get its length and original spelling.
498    std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
499    bool Invalid = false;
500    llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
501    if (Invalid)
502      return StrTokSpellingLoc;
503
504    const char *StrData = Buffer.data()+LocInfo.second;
505
506    // Create a langops struct and enable trigraphs.  This is sufficient for
507    // relexing tokens.
508    LangOptions LangOpts;
509    LangOpts.Trigraphs = true;
510
511    // Create a lexer starting at the beginning of this token.
512    Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
513                   Buffer.end());
514    Token TheTok;
515    TheLexer.LexFromRawLexer(TheTok);
516
517    // Use the StringLiteralParser to compute the length of the string in bytes.
518    StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
519    unsigned TokNumBytes = SLP.GetStringLength();
520
521    // If the byte is in this token, return the location of the byte.
522    if (ByteNo < TokNumBytes ||
523        (ByteNo == TokNumBytes && TokNo == getNumConcatenated())) {
524      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
525
526      // Now that we know the offset of the token in the spelling, use the
527      // preprocessor to get the offset in the original source.
528      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
529    }
530
531    // Move to the next string token.
532    ++TokNo;
533    ByteNo -= TokNumBytes;
534  }
535}
536
537
538
539/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
540/// corresponds to, e.g. "sizeof" or "[pre]++".
541const char *UnaryOperator::getOpcodeStr(Opcode Op) {
542  switch (Op) {
543  default: assert(0 && "Unknown unary operator");
544  case UO_PostInc: return "++";
545  case UO_PostDec: return "--";
546  case UO_PreInc:  return "++";
547  case UO_PreDec:  return "--";
548  case UO_AddrOf:  return "&";
549  case UO_Deref:   return "*";
550  case UO_Plus:    return "+";
551  case UO_Minus:   return "-";
552  case UO_Not:     return "~";
553  case UO_LNot:    return "!";
554  case UO_Real:    return "__real";
555  case UO_Imag:    return "__imag";
556  case UO_Extension: return "__extension__";
557  }
558}
559
560UnaryOperatorKind
561UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
562  switch (OO) {
563  default: assert(false && "No unary operator for overloaded function");
564  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
565  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
566  case OO_Amp:        return UO_AddrOf;
567  case OO_Star:       return UO_Deref;
568  case OO_Plus:       return UO_Plus;
569  case OO_Minus:      return UO_Minus;
570  case OO_Tilde:      return UO_Not;
571  case OO_Exclaim:    return UO_LNot;
572  }
573}
574
575OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
576  switch (Opc) {
577  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
578  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
579  case UO_AddrOf: return OO_Amp;
580  case UO_Deref: return OO_Star;
581  case UO_Plus: return OO_Plus;
582  case UO_Minus: return OO_Minus;
583  case UO_Not: return OO_Tilde;
584  case UO_LNot: return OO_Exclaim;
585  default: return OO_None;
586  }
587}
588
589
590//===----------------------------------------------------------------------===//
591// Postfix Operators.
592//===----------------------------------------------------------------------===//
593
594CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args,
595                   unsigned numargs, QualType t, SourceLocation rparenloc)
596  : Expr(SC, t,
597         fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
598         fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)),
599    NumArgs(numargs) {
600
601  SubExprs = new (C) Stmt*[numargs+1];
602  SubExprs[FN] = fn;
603  for (unsigned i = 0; i != numargs; ++i)
604    SubExprs[i+ARGS_START] = args[i];
605
606  RParenLoc = rparenloc;
607}
608
609CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
610                   QualType t, SourceLocation rparenloc)
611  : Expr(CallExprClass, t,
612         fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
613         fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)),
614    NumArgs(numargs) {
615
616  SubExprs = new (C) Stmt*[numargs+1];
617  SubExprs[FN] = fn;
618  for (unsigned i = 0; i != numargs; ++i)
619    SubExprs[i+ARGS_START] = args[i];
620
621  RParenLoc = rparenloc;
622}
623
624CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
625  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
626  SubExprs = new (C) Stmt*[1];
627}
628
629Decl *CallExpr::getCalleeDecl() {
630  Expr *CEE = getCallee()->IgnoreParenCasts();
631  // If we're calling a dereference, look at the pointer instead.
632  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
633    if (BO->isPtrMemOp())
634      CEE = BO->getRHS()->IgnoreParenCasts();
635  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
636    if (UO->getOpcode() == UO_Deref)
637      CEE = UO->getSubExpr()->IgnoreParenCasts();
638  }
639  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
640    return DRE->getDecl();
641  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
642    return ME->getMemberDecl();
643
644  return 0;
645}
646
647FunctionDecl *CallExpr::getDirectCallee() {
648  return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
649}
650
651/// setNumArgs - This changes the number of arguments present in this call.
652/// Any orphaned expressions are deleted by this, and any new operands are set
653/// to null.
654void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
655  // No change, just return.
656  if (NumArgs == getNumArgs()) return;
657
658  // If shrinking # arguments, just delete the extras and forgot them.
659  if (NumArgs < getNumArgs()) {
660    this->NumArgs = NumArgs;
661    return;
662  }
663
664  // Otherwise, we are growing the # arguments.  New an bigger argument array.
665  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+1];
666  // Copy over args.
667  for (unsigned i = 0; i != getNumArgs()+ARGS_START; ++i)
668    NewSubExprs[i] = SubExprs[i];
669  // Null out new args.
670  for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i)
671    NewSubExprs[i] = 0;
672
673  if (SubExprs) C.Deallocate(SubExprs);
674  SubExprs = NewSubExprs;
675  this->NumArgs = NumArgs;
676}
677
678/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
679/// not, return 0.
680unsigned CallExpr::isBuiltinCall(ASTContext &Context) const {
681  // All simple function calls (e.g. func()) are implicitly cast to pointer to
682  // function. As a result, we try and obtain the DeclRefExpr from the
683  // ImplicitCastExpr.
684  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
685  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
686    return 0;
687
688  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
689  if (!DRE)
690    return 0;
691
692  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
693  if (!FDecl)
694    return 0;
695
696  if (!FDecl->getIdentifier())
697    return 0;
698
699  return FDecl->getBuiltinID();
700}
701
702QualType CallExpr::getCallReturnType() const {
703  QualType CalleeType = getCallee()->getType();
704  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
705    CalleeType = FnTypePtr->getPointeeType();
706  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
707    CalleeType = BPT->getPointeeType();
708  else if (const MemberPointerType *MPT
709                                      = CalleeType->getAs<MemberPointerType>())
710    CalleeType = MPT->getPointeeType();
711
712  const FunctionType *FnType = CalleeType->getAs<FunctionType>();
713  return FnType->getResultType();
714}
715
716OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
717                                   SourceLocation OperatorLoc,
718                                   TypeSourceInfo *tsi,
719                                   OffsetOfNode* compsPtr, unsigned numComps,
720                                   Expr** exprsPtr, unsigned numExprs,
721                                   SourceLocation RParenLoc) {
722  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
723                         sizeof(OffsetOfNode) * numComps +
724                         sizeof(Expr*) * numExprs);
725
726  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
727                                exprsPtr, numExprs, RParenLoc);
728}
729
730OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
731                                        unsigned numComps, unsigned numExprs) {
732  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
733                         sizeof(OffsetOfNode) * numComps +
734                         sizeof(Expr*) * numExprs);
735  return new (Mem) OffsetOfExpr(numComps, numExprs);
736}
737
738OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
739                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,
740                           OffsetOfNode* compsPtr, unsigned numComps,
741                           Expr** exprsPtr, unsigned numExprs,
742                           SourceLocation RParenLoc)
743  : Expr(OffsetOfExprClass, type, /*TypeDependent=*/false,
744         /*ValueDependent=*/tsi->getType()->isDependentType() ||
745         hasAnyTypeDependentArguments(exprsPtr, numExprs) ||
746         hasAnyValueDependentArguments(exprsPtr, numExprs)),
747    OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
748    NumComps(numComps), NumExprs(numExprs)
749{
750  for(unsigned i = 0; i < numComps; ++i) {
751    setComponent(i, compsPtr[i]);
752  }
753
754  for(unsigned i = 0; i < numExprs; ++i) {
755    setIndexExpr(i, exprsPtr[i]);
756  }
757}
758
759IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
760  assert(getKind() == Field || getKind() == Identifier);
761  if (getKind() == Field)
762    return getField()->getIdentifier();
763
764  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
765}
766
767MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
768                               NestedNameSpecifier *qual,
769                               SourceRange qualrange,
770                               ValueDecl *memberdecl,
771                               DeclAccessPair founddecl,
772                               DeclarationNameInfo nameinfo,
773                               const TemplateArgumentListInfo *targs,
774                               QualType ty) {
775  std::size_t Size = sizeof(MemberExpr);
776
777  bool hasQualOrFound = (qual != 0 ||
778                         founddecl.getDecl() != memberdecl ||
779                         founddecl.getAccess() != memberdecl->getAccess());
780  if (hasQualOrFound)
781    Size += sizeof(MemberNameQualifier);
782
783  if (targs)
784    Size += ExplicitTemplateArgumentList::sizeFor(*targs);
785
786  void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
787  MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo, ty);
788
789  if (hasQualOrFound) {
790    if (qual && qual->isDependent()) {
791      E->setValueDependent(true);
792      E->setTypeDependent(true);
793    }
794    E->HasQualifierOrFoundDecl = true;
795
796    MemberNameQualifier *NQ = E->getMemberQualifier();
797    NQ->NNS = qual;
798    NQ->Range = qualrange;
799    NQ->FoundDecl = founddecl;
800  }
801
802  if (targs) {
803    E->HasExplicitTemplateArgumentList = true;
804    E->getExplicitTemplateArgs().initializeFrom(*targs);
805  }
806
807  return E;
808}
809
810const char *CastExpr::getCastKindName() const {
811  switch (getCastKind()) {
812  case CK_Dependent:
813    return "Dependent";
814  case CK_BitCast:
815    return "BitCast";
816  case CK_LValueBitCast:
817    return "LValueBitCast";
818  case CK_NoOp:
819    return "NoOp";
820  case CK_BaseToDerived:
821    return "BaseToDerived";
822  case CK_DerivedToBase:
823    return "DerivedToBase";
824  case CK_UncheckedDerivedToBase:
825    return "UncheckedDerivedToBase";
826  case CK_Dynamic:
827    return "Dynamic";
828  case CK_ToUnion:
829    return "ToUnion";
830  case CK_ArrayToPointerDecay:
831    return "ArrayToPointerDecay";
832  case CK_FunctionToPointerDecay:
833    return "FunctionToPointerDecay";
834  case CK_NullToMemberPointer:
835    return "NullToMemberPointer";
836  case CK_NullToPointer:
837    return "NullToPointer";
838  case CK_BaseToDerivedMemberPointer:
839    return "BaseToDerivedMemberPointer";
840  case CK_DerivedToBaseMemberPointer:
841    return "DerivedToBaseMemberPointer";
842  case CK_UserDefinedConversion:
843    return "UserDefinedConversion";
844  case CK_ConstructorConversion:
845    return "ConstructorConversion";
846  case CK_IntegralToPointer:
847    return "IntegralToPointer";
848  case CK_PointerToIntegral:
849    return "PointerToIntegral";
850  case CK_PointerToBoolean:
851    return "PointerToBoolean";
852  case CK_ToVoid:
853    return "ToVoid";
854  case CK_VectorSplat:
855    return "VectorSplat";
856  case CK_IntegralCast:
857    return "IntegralCast";
858  case CK_IntegralToBoolean:
859    return "IntegralToBoolean";
860  case CK_IntegralToFloating:
861    return "IntegralToFloating";
862  case CK_FloatingToIntegral:
863    return "FloatingToIntegral";
864  case CK_FloatingCast:
865    return "FloatingCast";
866  case CK_FloatingToBoolean:
867    return "FloatingToBoolean";
868  case CK_MemberPointerToBoolean:
869    return "MemberPointerToBoolean";
870  case CK_AnyPointerToObjCPointerCast:
871    return "AnyPointerToObjCPointerCast";
872  case CK_AnyPointerToBlockPointerCast:
873    return "AnyPointerToBlockPointerCast";
874  case CK_ObjCObjectLValueCast:
875    return "ObjCObjectLValueCast";
876  case CK_FloatingRealToComplex:
877    return "FloatingRealToComplex";
878  case CK_FloatingComplexToReal:
879    return "FloatingComplexToReal";
880  case CK_FloatingComplexToBoolean:
881    return "FloatingComplexToBoolean";
882  case CK_FloatingComplexCast:
883    return "FloatingComplexCast";
884  case CK_FloatingComplexToIntegralComplex:
885    return "FloatingComplexToIntegralComplex";
886  case CK_IntegralRealToComplex:
887    return "IntegralRealToComplex";
888  case CK_IntegralComplexToReal:
889    return "IntegralComplexToReal";
890  case CK_IntegralComplexToBoolean:
891    return "IntegralComplexToBoolean";
892  case CK_IntegralComplexCast:
893    return "IntegralComplexCast";
894  case CK_IntegralComplexToFloatingComplex:
895    return "IntegralComplexToFloatingComplex";
896  }
897
898  llvm_unreachable("Unhandled cast kind!");
899  return 0;
900}
901
902Expr *CastExpr::getSubExprAsWritten() {
903  Expr *SubExpr = 0;
904  CastExpr *E = this;
905  do {
906    SubExpr = E->getSubExpr();
907
908    // Skip any temporary bindings; they're implicit.
909    if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
910      SubExpr = Binder->getSubExpr();
911
912    // Conversions by constructor and conversion functions have a
913    // subexpression describing the call; strip it off.
914    if (E->getCastKind() == CK_ConstructorConversion)
915      SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
916    else if (E->getCastKind() == CK_UserDefinedConversion)
917      SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
918
919    // If the subexpression we're left with is an implicit cast, look
920    // through that, too.
921  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
922
923  return SubExpr;
924}
925
926CXXBaseSpecifier **CastExpr::path_buffer() {
927  switch (getStmtClass()) {
928#define ABSTRACT_STMT(x)
929#define CASTEXPR(Type, Base) \
930  case Stmt::Type##Class: \
931    return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
932#define STMT(Type, Base)
933#include "clang/AST/StmtNodes.inc"
934  default:
935    llvm_unreachable("non-cast expressions not possible here");
936    return 0;
937  }
938}
939
940void CastExpr::setCastPath(const CXXCastPath &Path) {
941  assert(Path.size() == path_size());
942  memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
943}
944
945ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
946                                           CastKind Kind, Expr *Operand,
947                                           const CXXCastPath *BasePath,
948                                           ExprValueKind VK) {
949  unsigned PathSize = (BasePath ? BasePath->size() : 0);
950  void *Buffer =
951    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
952  ImplicitCastExpr *E =
953    new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
954  if (PathSize) E->setCastPath(*BasePath);
955  return E;
956}
957
958ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
959                                                unsigned PathSize) {
960  void *Buffer =
961    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
962  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
963}
964
965
966CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
967                                       CastKind K, Expr *Op,
968                                       const CXXCastPath *BasePath,
969                                       TypeSourceInfo *WrittenTy,
970                                       SourceLocation L, SourceLocation R) {
971  unsigned PathSize = (BasePath ? BasePath->size() : 0);
972  void *Buffer =
973    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
974  CStyleCastExpr *E =
975    new (Buffer) CStyleCastExpr(T, K, Op, PathSize, WrittenTy, L, R);
976  if (PathSize) E->setCastPath(*BasePath);
977  return E;
978}
979
980CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
981  void *Buffer =
982    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
983  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
984}
985
986/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
987/// corresponds to, e.g. "<<=".
988const char *BinaryOperator::getOpcodeStr(Opcode Op) {
989  switch (Op) {
990  case BO_PtrMemD:   return ".*";
991  case BO_PtrMemI:   return "->*";
992  case BO_Mul:       return "*";
993  case BO_Div:       return "/";
994  case BO_Rem:       return "%";
995  case BO_Add:       return "+";
996  case BO_Sub:       return "-";
997  case BO_Shl:       return "<<";
998  case BO_Shr:       return ">>";
999  case BO_LT:        return "<";
1000  case BO_GT:        return ">";
1001  case BO_LE:        return "<=";
1002  case BO_GE:        return ">=";
1003  case BO_EQ:        return "==";
1004  case BO_NE:        return "!=";
1005  case BO_And:       return "&";
1006  case BO_Xor:       return "^";
1007  case BO_Or:        return "|";
1008  case BO_LAnd:      return "&&";
1009  case BO_LOr:       return "||";
1010  case BO_Assign:    return "=";
1011  case BO_MulAssign: return "*=";
1012  case BO_DivAssign: return "/=";
1013  case BO_RemAssign: return "%=";
1014  case BO_AddAssign: return "+=";
1015  case BO_SubAssign: return "-=";
1016  case BO_ShlAssign: return "<<=";
1017  case BO_ShrAssign: return ">>=";
1018  case BO_AndAssign: return "&=";
1019  case BO_XorAssign: return "^=";
1020  case BO_OrAssign:  return "|=";
1021  case BO_Comma:     return ",";
1022  }
1023
1024  return "";
1025}
1026
1027BinaryOperatorKind
1028BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1029  switch (OO) {
1030  default: assert(false && "Not an overloadable binary operator");
1031  case OO_Plus: return BO_Add;
1032  case OO_Minus: return BO_Sub;
1033  case OO_Star: return BO_Mul;
1034  case OO_Slash: return BO_Div;
1035  case OO_Percent: return BO_Rem;
1036  case OO_Caret: return BO_Xor;
1037  case OO_Amp: return BO_And;
1038  case OO_Pipe: return BO_Or;
1039  case OO_Equal: return BO_Assign;
1040  case OO_Less: return BO_LT;
1041  case OO_Greater: return BO_GT;
1042  case OO_PlusEqual: return BO_AddAssign;
1043  case OO_MinusEqual: return BO_SubAssign;
1044  case OO_StarEqual: return BO_MulAssign;
1045  case OO_SlashEqual: return BO_DivAssign;
1046  case OO_PercentEqual: return BO_RemAssign;
1047  case OO_CaretEqual: return BO_XorAssign;
1048  case OO_AmpEqual: return BO_AndAssign;
1049  case OO_PipeEqual: return BO_OrAssign;
1050  case OO_LessLess: return BO_Shl;
1051  case OO_GreaterGreater: return BO_Shr;
1052  case OO_LessLessEqual: return BO_ShlAssign;
1053  case OO_GreaterGreaterEqual: return BO_ShrAssign;
1054  case OO_EqualEqual: return BO_EQ;
1055  case OO_ExclaimEqual: return BO_NE;
1056  case OO_LessEqual: return BO_LE;
1057  case OO_GreaterEqual: return BO_GE;
1058  case OO_AmpAmp: return BO_LAnd;
1059  case OO_PipePipe: return BO_LOr;
1060  case OO_Comma: return BO_Comma;
1061  case OO_ArrowStar: return BO_PtrMemI;
1062  }
1063}
1064
1065OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1066  static const OverloadedOperatorKind OverOps[] = {
1067    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1068    OO_Star, OO_Slash, OO_Percent,
1069    OO_Plus, OO_Minus,
1070    OO_LessLess, OO_GreaterGreater,
1071    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1072    OO_EqualEqual, OO_ExclaimEqual,
1073    OO_Amp,
1074    OO_Caret,
1075    OO_Pipe,
1076    OO_AmpAmp,
1077    OO_PipePipe,
1078    OO_Equal, OO_StarEqual,
1079    OO_SlashEqual, OO_PercentEqual,
1080    OO_PlusEqual, OO_MinusEqual,
1081    OO_LessLessEqual, OO_GreaterGreaterEqual,
1082    OO_AmpEqual, OO_CaretEqual,
1083    OO_PipeEqual,
1084    OO_Comma
1085  };
1086  return OverOps[Opc];
1087}
1088
1089InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1090                           Expr **initExprs, unsigned numInits,
1091                           SourceLocation rbraceloc)
1092  : Expr(InitListExprClass, QualType(), false, false),
1093    InitExprs(C, numInits),
1094    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
1095    UnionFieldInit(0), HadArrayRangeDesignator(false)
1096{
1097  for (unsigned I = 0; I != numInits; ++I) {
1098    if (initExprs[I]->isTypeDependent())
1099      ExprBits.TypeDependent = true;
1100    if (initExprs[I]->isValueDependent())
1101      ExprBits.ValueDependent = true;
1102  }
1103
1104  InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1105}
1106
1107void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1108  if (NumInits > InitExprs.size())
1109    InitExprs.reserve(C, NumInits);
1110}
1111
1112void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1113  InitExprs.resize(C, NumInits, 0);
1114}
1115
1116Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1117  if (Init >= InitExprs.size()) {
1118    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1119    InitExprs.back() = expr;
1120    return 0;
1121  }
1122
1123  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1124  InitExprs[Init] = expr;
1125  return Result;
1126}
1127
1128SourceRange InitListExpr::getSourceRange() const {
1129  if (SyntacticForm)
1130    return SyntacticForm->getSourceRange();
1131  SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1132  if (Beg.isInvalid()) {
1133    // Find the first non-null initializer.
1134    for (InitExprsTy::const_iterator I = InitExprs.begin(),
1135                                     E = InitExprs.end();
1136      I != E; ++I) {
1137      if (Stmt *S = *I) {
1138        Beg = S->getLocStart();
1139        break;
1140      }
1141    }
1142  }
1143  if (End.isInvalid()) {
1144    // Find the first non-null initializer from the end.
1145    for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1146                                             E = InitExprs.rend();
1147      I != E; ++I) {
1148      if (Stmt *S = *I) {
1149        End = S->getSourceRange().getEnd();
1150        break;
1151      }
1152    }
1153  }
1154  return SourceRange(Beg, End);
1155}
1156
1157/// getFunctionType - Return the underlying function type for this block.
1158///
1159const FunctionType *BlockExpr::getFunctionType() const {
1160  return getType()->getAs<BlockPointerType>()->
1161                    getPointeeType()->getAs<FunctionType>();
1162}
1163
1164SourceLocation BlockExpr::getCaretLocation() const {
1165  return TheBlock->getCaretLocation();
1166}
1167const Stmt *BlockExpr::getBody() const {
1168  return TheBlock->getBody();
1169}
1170Stmt *BlockExpr::getBody() {
1171  return TheBlock->getBody();
1172}
1173
1174
1175//===----------------------------------------------------------------------===//
1176// Generic Expression Routines
1177//===----------------------------------------------------------------------===//
1178
1179/// isUnusedResultAWarning - Return true if this immediate expression should
1180/// be warned about if the result is unused.  If so, fill in Loc and Ranges
1181/// with location to warn on and the source range[s] to report with the
1182/// warning.
1183bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1184                                  SourceRange &R2, ASTContext &Ctx) const {
1185  // Don't warn if the expr is type dependent. The type could end up
1186  // instantiating to void.
1187  if (isTypeDependent())
1188    return false;
1189
1190  switch (getStmtClass()) {
1191  default:
1192    if (getType()->isVoidType())
1193      return false;
1194    Loc = getExprLoc();
1195    R1 = getSourceRange();
1196    return true;
1197  case ParenExprClass:
1198    return cast<ParenExpr>(this)->getSubExpr()->
1199      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1200  case UnaryOperatorClass: {
1201    const UnaryOperator *UO = cast<UnaryOperator>(this);
1202
1203    switch (UO->getOpcode()) {
1204    default: break;
1205    case UO_PostInc:
1206    case UO_PostDec:
1207    case UO_PreInc:
1208    case UO_PreDec:                 // ++/--
1209      return false;  // Not a warning.
1210    case UO_Deref:
1211      // Dereferencing a volatile pointer is a side-effect.
1212      if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1213        return false;
1214      break;
1215    case UO_Real:
1216    case UO_Imag:
1217      // accessing a piece of a volatile complex is a side-effect.
1218      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1219          .isVolatileQualified())
1220        return false;
1221      break;
1222    case UO_Extension:
1223      return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1224    }
1225    Loc = UO->getOperatorLoc();
1226    R1 = UO->getSubExpr()->getSourceRange();
1227    return true;
1228  }
1229  case BinaryOperatorClass: {
1230    const BinaryOperator *BO = cast<BinaryOperator>(this);
1231    switch (BO->getOpcode()) {
1232      default:
1233        break;
1234      // Consider the RHS of comma for side effects. LHS was checked by
1235      // Sema::CheckCommaOperands.
1236      case BO_Comma:
1237        // ((foo = <blah>), 0) is an idiom for hiding the result (and
1238        // lvalue-ness) of an assignment written in a macro.
1239        if (IntegerLiteral *IE =
1240              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1241          if (IE->getValue() == 0)
1242            return false;
1243        return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1244      // Consider '||', '&&' to have side effects if the LHS or RHS does.
1245      case BO_LAnd:
1246      case BO_LOr:
1247        if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1248            !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1249          return false;
1250        break;
1251    }
1252    if (BO->isAssignmentOp())
1253      return false;
1254    Loc = BO->getOperatorLoc();
1255    R1 = BO->getLHS()->getSourceRange();
1256    R2 = BO->getRHS()->getSourceRange();
1257    return true;
1258  }
1259  case CompoundAssignOperatorClass:
1260  case VAArgExprClass:
1261    return false;
1262
1263  case ConditionalOperatorClass: {
1264    // The condition must be evaluated, but if either the LHS or RHS is a
1265    // warning, warn about them.
1266    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1267    if (Exp->getLHS() &&
1268        Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1269      return true;
1270    return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1271  }
1272
1273  case MemberExprClass:
1274    // If the base pointer or element is to a volatile pointer/field, accessing
1275    // it is a side effect.
1276    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1277      return false;
1278    Loc = cast<MemberExpr>(this)->getMemberLoc();
1279    R1 = SourceRange(Loc, Loc);
1280    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1281    return true;
1282
1283  case ArraySubscriptExprClass:
1284    // If the base pointer or element is to a volatile pointer/field, accessing
1285    // it is a side effect.
1286    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1287      return false;
1288    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1289    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1290    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1291    return true;
1292
1293  case CallExprClass:
1294  case CXXOperatorCallExprClass:
1295  case CXXMemberCallExprClass: {
1296    // If this is a direct call, get the callee.
1297    const CallExpr *CE = cast<CallExpr>(this);
1298    if (const Decl *FD = CE->getCalleeDecl()) {
1299      // If the callee has attribute pure, const, or warn_unused_result, warn
1300      // about it. void foo() { strlen("bar"); } should warn.
1301      //
1302      // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1303      // updated to match for QoI.
1304      if (FD->getAttr<WarnUnusedResultAttr>() ||
1305          FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1306        Loc = CE->getCallee()->getLocStart();
1307        R1 = CE->getCallee()->getSourceRange();
1308
1309        if (unsigned NumArgs = CE->getNumArgs())
1310          R2 = SourceRange(CE->getArg(0)->getLocStart(),
1311                           CE->getArg(NumArgs-1)->getLocEnd());
1312        return true;
1313      }
1314    }
1315    return false;
1316  }
1317
1318  case CXXTemporaryObjectExprClass:
1319  case CXXConstructExprClass:
1320    return false;
1321
1322  case ObjCMessageExprClass: {
1323    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1324    const ObjCMethodDecl *MD = ME->getMethodDecl();
1325    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1326      Loc = getExprLoc();
1327      return true;
1328    }
1329    return false;
1330  }
1331
1332  case ObjCImplicitSetterGetterRefExprClass: {   // Dot syntax for message send.
1333#if 0
1334    const ObjCImplicitSetterGetterRefExpr *Ref =
1335      cast<ObjCImplicitSetterGetterRefExpr>(this);
1336    // FIXME: We really want the location of the '.' here.
1337    Loc = Ref->getLocation();
1338    R1 = SourceRange(Ref->getLocation(), Ref->getLocation());
1339    if (Ref->getBase())
1340      R2 = Ref->getBase()->getSourceRange();
1341#else
1342    Loc = getExprLoc();
1343    R1 = getSourceRange();
1344#endif
1345    return true;
1346  }
1347  case StmtExprClass: {
1348    // Statement exprs don't logically have side effects themselves, but are
1349    // sometimes used in macros in ways that give them a type that is unused.
1350    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1351    // however, if the result of the stmt expr is dead, we don't want to emit a
1352    // warning.
1353    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1354    if (!CS->body_empty()) {
1355      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1356        return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1357      if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1358        if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1359          return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1360    }
1361
1362    if (getType()->isVoidType())
1363      return false;
1364    Loc = cast<StmtExpr>(this)->getLParenLoc();
1365    R1 = getSourceRange();
1366    return true;
1367  }
1368  case CStyleCastExprClass:
1369    // If this is an explicit cast to void, allow it.  People do this when they
1370    // think they know what they're doing :).
1371    if (getType()->isVoidType())
1372      return false;
1373    Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1374    R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1375    return true;
1376  case CXXFunctionalCastExprClass: {
1377    if (getType()->isVoidType())
1378      return false;
1379    const CastExpr *CE = cast<CastExpr>(this);
1380
1381    // If this is a cast to void or a constructor conversion, check the operand.
1382    // Otherwise, the result of the cast is unused.
1383    if (CE->getCastKind() == CK_ToVoid ||
1384        CE->getCastKind() == CK_ConstructorConversion)
1385      return (cast<CastExpr>(this)->getSubExpr()
1386              ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1387    Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1388    R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1389    return true;
1390  }
1391
1392  case ImplicitCastExprClass:
1393    // Check the operand, since implicit casts are inserted by Sema
1394    return (cast<ImplicitCastExpr>(this)
1395            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1396
1397  case CXXDefaultArgExprClass:
1398    return (cast<CXXDefaultArgExpr>(this)
1399            ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1400
1401  case CXXNewExprClass:
1402    // FIXME: In theory, there might be new expressions that don't have side
1403    // effects (e.g. a placement new with an uninitialized POD).
1404  case CXXDeleteExprClass:
1405    return false;
1406  case CXXBindTemporaryExprClass:
1407    return (cast<CXXBindTemporaryExpr>(this)
1408            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1409  case CXXExprWithTemporariesClass:
1410    return (cast<CXXExprWithTemporaries>(this)
1411            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1412  }
1413}
1414
1415/// isOBJCGCCandidate - Check if an expression is objc gc'able.
1416/// returns true, if it is; false otherwise.
1417bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1418  switch (getStmtClass()) {
1419  default:
1420    return false;
1421  case ObjCIvarRefExprClass:
1422    return true;
1423  case Expr::UnaryOperatorClass:
1424    return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1425  case ParenExprClass:
1426    return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1427  case ImplicitCastExprClass:
1428    return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1429  case CStyleCastExprClass:
1430    return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1431  case DeclRefExprClass: {
1432    const Decl *D = cast<DeclRefExpr>(this)->getDecl();
1433    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1434      if (VD->hasGlobalStorage())
1435        return true;
1436      QualType T = VD->getType();
1437      // dereferencing to a  pointer is always a gc'able candidate,
1438      // unless it is __weak.
1439      return T->isPointerType() &&
1440             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1441    }
1442    return false;
1443  }
1444  case MemberExprClass: {
1445    const MemberExpr *M = cast<MemberExpr>(this);
1446    return M->getBase()->isOBJCGCCandidate(Ctx);
1447  }
1448  case ArraySubscriptExprClass:
1449    return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx);
1450  }
1451}
1452
1453bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1454  if (isTypeDependent())
1455    return false;
1456  return isLvalue(Ctx) == Expr::LV_MemberFunction;
1457}
1458
1459static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1460                                          Expr::CanThrowResult CT2) {
1461  // CanThrowResult constants are ordered so that the maximum is the correct
1462  // merge result.
1463  return CT1 > CT2 ? CT1 : CT2;
1464}
1465
1466static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1467  Expr *E = const_cast<Expr*>(CE);
1468  Expr::CanThrowResult R = Expr::CT_Cannot;
1469  for (Expr::child_iterator I = E->child_begin(), IE = E->child_end();
1470       I != IE && R != Expr::CT_Can; ++I) {
1471    R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1472  }
1473  return R;
1474}
1475
1476static Expr::CanThrowResult CanCalleeThrow(const Decl *D,
1477                                           bool NullThrows = true) {
1478  if (!D)
1479    return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1480
1481  // See if we can get a function type from the decl somehow.
1482  const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1483  if (!VD) // If we have no clue what we're calling, assume the worst.
1484    return Expr::CT_Can;
1485
1486  // As an extension, we assume that __attribute__((nothrow)) functions don't
1487  // throw.
1488  if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1489    return Expr::CT_Cannot;
1490
1491  QualType T = VD->getType();
1492  const FunctionProtoType *FT;
1493  if ((FT = T->getAs<FunctionProtoType>())) {
1494  } else if (const PointerType *PT = T->getAs<PointerType>())
1495    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1496  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1497    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1498  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1499    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1500  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1501    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1502
1503  if (!FT)
1504    return Expr::CT_Can;
1505
1506  return FT->hasEmptyExceptionSpec() ? Expr::CT_Cannot : Expr::CT_Can;
1507}
1508
1509static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1510  if (DC->isTypeDependent())
1511    return Expr::CT_Dependent;
1512
1513  if (!DC->getTypeAsWritten()->isReferenceType())
1514    return Expr::CT_Cannot;
1515
1516  return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1517}
1518
1519static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1520                                           const CXXTypeidExpr *DC) {
1521  if (DC->isTypeOperand())
1522    return Expr::CT_Cannot;
1523
1524  Expr *Op = DC->getExprOperand();
1525  if (Op->isTypeDependent())
1526    return Expr::CT_Dependent;
1527
1528  const RecordType *RT = Op->getType()->getAs<RecordType>();
1529  if (!RT)
1530    return Expr::CT_Cannot;
1531
1532  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1533    return Expr::CT_Cannot;
1534
1535  if (Op->Classify(C).isPRValue())
1536    return Expr::CT_Cannot;
1537
1538  return Expr::CT_Can;
1539}
1540
1541Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1542  // C++ [expr.unary.noexcept]p3:
1543  //   [Can throw] if in a potentially-evaluated context the expression would
1544  //   contain:
1545  switch (getStmtClass()) {
1546  case CXXThrowExprClass:
1547    //   - a potentially evaluated throw-expression
1548    return CT_Can;
1549
1550  case CXXDynamicCastExprClass: {
1551    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1552    //     where T is a reference type, that requires a run-time check
1553    CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1554    if (CT == CT_Can)
1555      return CT;
1556    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1557  }
1558
1559  case CXXTypeidExprClass:
1560    //   - a potentially evaluated typeid expression applied to a glvalue
1561    //     expression whose type is a polymorphic class type
1562    return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1563
1564    //   - a potentially evaluated call to a function, member function, function
1565    //     pointer, or member function pointer that does not have a non-throwing
1566    //     exception-specification
1567  case CallExprClass:
1568  case CXXOperatorCallExprClass:
1569  case CXXMemberCallExprClass: {
1570    CanThrowResult CT = CanCalleeThrow(cast<CallExpr>(this)->getCalleeDecl());
1571    if (CT == CT_Can)
1572      return CT;
1573    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1574  }
1575
1576  case CXXConstructExprClass:
1577  case CXXTemporaryObjectExprClass: {
1578    CanThrowResult CT = CanCalleeThrow(
1579        cast<CXXConstructExpr>(this)->getConstructor());
1580    if (CT == CT_Can)
1581      return CT;
1582    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1583  }
1584
1585  case CXXNewExprClass: {
1586    CanThrowResult CT = MergeCanThrow(
1587        CanCalleeThrow(cast<CXXNewExpr>(this)->getOperatorNew()),
1588        CanCalleeThrow(cast<CXXNewExpr>(this)->getConstructor(),
1589                       /*NullThrows*/false));
1590    if (CT == CT_Can)
1591      return CT;
1592    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1593  }
1594
1595  case CXXDeleteExprClass: {
1596    CanThrowResult CT = CanCalleeThrow(
1597        cast<CXXDeleteExpr>(this)->getOperatorDelete());
1598    if (CT == CT_Can)
1599      return CT;
1600    const Expr *Arg = cast<CXXDeleteExpr>(this)->getArgument();
1601    // Unwrap exactly one implicit cast, which converts all pointers to void*.
1602    if (const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1603      Arg = Cast->getSubExpr();
1604    if (const PointerType *PT = Arg->getType()->getAs<PointerType>()) {
1605      if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) {
1606        CanThrowResult CT2 = CanCalleeThrow(
1607            cast<CXXRecordDecl>(RT->getDecl())->getDestructor());
1608        if (CT2 == CT_Can)
1609          return CT2;
1610        CT = MergeCanThrow(CT, CT2);
1611      }
1612    }
1613    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1614  }
1615
1616  case CXXBindTemporaryExprClass: {
1617    // The bound temporary has to be destroyed again, which might throw.
1618    CanThrowResult CT = CanCalleeThrow(
1619      cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
1620    if (CT == CT_Can)
1621      return CT;
1622    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1623  }
1624
1625    // ObjC message sends are like function calls, but never have exception
1626    // specs.
1627  case ObjCMessageExprClass:
1628  case ObjCPropertyRefExprClass:
1629  case ObjCImplicitSetterGetterRefExprClass:
1630    return CT_Can;
1631
1632    // Many other things have subexpressions, so we have to test those.
1633    // Some are simple:
1634  case ParenExprClass:
1635  case MemberExprClass:
1636  case CXXReinterpretCastExprClass:
1637  case CXXConstCastExprClass:
1638  case ConditionalOperatorClass:
1639  case CompoundLiteralExprClass:
1640  case ExtVectorElementExprClass:
1641  case InitListExprClass:
1642  case DesignatedInitExprClass:
1643  case ParenListExprClass:
1644  case VAArgExprClass:
1645  case CXXDefaultArgExprClass:
1646  case CXXExprWithTemporariesClass:
1647  case ObjCIvarRefExprClass:
1648  case ObjCIsaExprClass:
1649  case ShuffleVectorExprClass:
1650    return CanSubExprsThrow(C, this);
1651
1652    // Some might be dependent for other reasons.
1653  case UnaryOperatorClass:
1654  case ArraySubscriptExprClass:
1655  case ImplicitCastExprClass:
1656  case CStyleCastExprClass:
1657  case CXXStaticCastExprClass:
1658  case CXXFunctionalCastExprClass:
1659  case BinaryOperatorClass:
1660  case CompoundAssignOperatorClass: {
1661    CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
1662    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1663  }
1664
1665    // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1666  case StmtExprClass:
1667    return CT_Can;
1668
1669  case ChooseExprClass:
1670    if (isTypeDependent() || isValueDependent())
1671      return CT_Dependent;
1672    return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
1673
1674    // Some expressions are always dependent.
1675  case DependentScopeDeclRefExprClass:
1676  case CXXUnresolvedConstructExprClass:
1677  case CXXDependentScopeMemberExprClass:
1678    return CT_Dependent;
1679
1680  default:
1681    // All other expressions don't have subexpressions, or else they are
1682    // unevaluated.
1683    return CT_Cannot;
1684  }
1685}
1686
1687Expr* Expr::IgnoreParens() {
1688  Expr* E = this;
1689  while (true) {
1690    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1691      E = P->getSubExpr();
1692      continue;
1693    }
1694    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1695      if (P->getOpcode() == UO_Extension) {
1696        E = P->getSubExpr();
1697        continue;
1698      }
1699    }
1700    return E;
1701  }
1702}
1703
1704/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
1705/// or CastExprs or ImplicitCastExprs, returning their operand.
1706Expr *Expr::IgnoreParenCasts() {
1707  Expr *E = this;
1708  while (true) {
1709    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1710      E = P->getSubExpr();
1711      continue;
1712    }
1713    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1714      E = P->getSubExpr();
1715      continue;
1716    }
1717    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1718      if (P->getOpcode() == UO_Extension) {
1719        E = P->getSubExpr();
1720        continue;
1721      }
1722    }
1723    return E;
1724  }
1725}
1726
1727Expr *Expr::IgnoreParenImpCasts() {
1728  Expr *E = this;
1729  while (true) {
1730    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1731      E = P->getSubExpr();
1732      continue;
1733    }
1734    if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
1735      E = P->getSubExpr();
1736      continue;
1737    }
1738    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1739      if (P->getOpcode() == UO_Extension) {
1740        E = P->getSubExpr();
1741        continue;
1742      }
1743    }
1744    return E;
1745  }
1746}
1747
1748/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1749/// value (including ptr->int casts of the same size).  Strip off any
1750/// ParenExpr or CastExprs, returning their operand.
1751Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1752  Expr *E = this;
1753  while (true) {
1754    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1755      E = P->getSubExpr();
1756      continue;
1757    }
1758
1759    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1760      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
1761      // ptr<->int casts of the same width.  We also ignore all identity casts.
1762      Expr *SE = P->getSubExpr();
1763
1764      if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1765        E = SE;
1766        continue;
1767      }
1768
1769      if ((E->getType()->isPointerType() ||
1770           E->getType()->isIntegralType(Ctx)) &&
1771          (SE->getType()->isPointerType() ||
1772           SE->getType()->isIntegralType(Ctx)) &&
1773          Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1774        E = SE;
1775        continue;
1776      }
1777    }
1778
1779    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1780      if (P->getOpcode() == UO_Extension) {
1781        E = P->getSubExpr();
1782        continue;
1783      }
1784    }
1785
1786    return E;
1787  }
1788}
1789
1790bool Expr::isDefaultArgument() const {
1791  const Expr *E = this;
1792  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1793    E = ICE->getSubExprAsWritten();
1794
1795  return isa<CXXDefaultArgExpr>(E);
1796}
1797
1798/// \brief Skip over any no-op casts and any temporary-binding
1799/// expressions.
1800static const Expr *skipTemporaryBindingsAndNoOpCasts(const Expr *E) {
1801  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
1802    if (ICE->getCastKind() == CK_NoOp)
1803      E = ICE->getSubExpr();
1804    else
1805      break;
1806  }
1807
1808  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
1809    E = BE->getSubExpr();
1810
1811  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
1812    if (ICE->getCastKind() == CK_NoOp)
1813      E = ICE->getSubExpr();
1814    else
1815      break;
1816  }
1817
1818  return E;
1819}
1820
1821/// isTemporaryObject - Determines if this expression produces a
1822/// temporary of the given class type.
1823bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
1824  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
1825    return false;
1826
1827  const Expr *E = skipTemporaryBindingsAndNoOpCasts(this);
1828
1829  // Temporaries are by definition pr-values of class type.
1830  if (!E->Classify(C).isPRValue()) {
1831    // In this context, property reference is a message call and is pr-value.
1832    if (!isa<ObjCPropertyRefExpr>(E) &&
1833        !isa<ObjCImplicitSetterGetterRefExpr>(E))
1834      return false;
1835  }
1836
1837  // Black-list a few cases which yield pr-values of class type that don't
1838  // refer to temporaries of that type:
1839
1840  // - implicit derived-to-base conversions
1841  if (isa<ImplicitCastExpr>(E)) {
1842    switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
1843    case CK_DerivedToBase:
1844    case CK_UncheckedDerivedToBase:
1845      return false;
1846    default:
1847      break;
1848    }
1849  }
1850
1851  // - member expressions (all)
1852  if (isa<MemberExpr>(E))
1853    return false;
1854
1855  return true;
1856}
1857
1858/// hasAnyTypeDependentArguments - Determines if any of the expressions
1859/// in Exprs is type-dependent.
1860bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
1861  for (unsigned I = 0; I < NumExprs; ++I)
1862    if (Exprs[I]->isTypeDependent())
1863      return true;
1864
1865  return false;
1866}
1867
1868/// hasAnyValueDependentArguments - Determines if any of the expressions
1869/// in Exprs is value-dependent.
1870bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
1871  for (unsigned I = 0; I < NumExprs; ++I)
1872    if (Exprs[I]->isValueDependent())
1873      return true;
1874
1875  return false;
1876}
1877
1878bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
1879  // This function is attempting whether an expression is an initializer
1880  // which can be evaluated at compile-time.  isEvaluatable handles most
1881  // of the cases, but it can't deal with some initializer-specific
1882  // expressions, and it can't deal with aggregates; we deal with those here,
1883  // and fall back to isEvaluatable for the other cases.
1884
1885  // If we ever capture reference-binding directly in the AST, we can
1886  // kill the second parameter.
1887
1888  if (IsForRef) {
1889    EvalResult Result;
1890    return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
1891  }
1892
1893  switch (getStmtClass()) {
1894  default: break;
1895  case StringLiteralClass:
1896  case ObjCStringLiteralClass:
1897  case ObjCEncodeExprClass:
1898    return true;
1899  case CXXTemporaryObjectExprClass:
1900  case CXXConstructExprClass: {
1901    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
1902
1903    // Only if it's
1904    // 1) an application of the trivial default constructor or
1905    if (!CE->getConstructor()->isTrivial()) return false;
1906    if (!CE->getNumArgs()) return true;
1907
1908    // 2) an elidable trivial copy construction of an operand which is
1909    //    itself a constant initializer.  Note that we consider the
1910    //    operand on its own, *not* as a reference binding.
1911    return CE->isElidable() &&
1912           CE->getArg(0)->isConstantInitializer(Ctx, false);
1913  }
1914  case CompoundLiteralExprClass: {
1915    // This handles gcc's extension that allows global initializers like
1916    // "struct x {int x;} x = (struct x) {};".
1917    // FIXME: This accepts other cases it shouldn't!
1918    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
1919    return Exp->isConstantInitializer(Ctx, false);
1920  }
1921  case InitListExprClass: {
1922    // FIXME: This doesn't deal with fields with reference types correctly.
1923    // FIXME: This incorrectly allows pointers cast to integers to be assigned
1924    // to bitfields.
1925    const InitListExpr *Exp = cast<InitListExpr>(this);
1926    unsigned numInits = Exp->getNumInits();
1927    for (unsigned i = 0; i < numInits; i++) {
1928      if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
1929        return false;
1930    }
1931    return true;
1932  }
1933  case ImplicitValueInitExprClass:
1934    return true;
1935  case ParenExprClass:
1936    return cast<ParenExpr>(this)->getSubExpr()
1937      ->isConstantInitializer(Ctx, IsForRef);
1938  case ChooseExprClass:
1939    return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
1940      ->isConstantInitializer(Ctx, IsForRef);
1941  case UnaryOperatorClass: {
1942    const UnaryOperator* Exp = cast<UnaryOperator>(this);
1943    if (Exp->getOpcode() == UO_Extension)
1944      return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
1945    break;
1946  }
1947  case BinaryOperatorClass: {
1948    // Special case &&foo - &&bar.  It would be nice to generalize this somehow
1949    // but this handles the common case.
1950    const BinaryOperator *Exp = cast<BinaryOperator>(this);
1951    if (Exp->getOpcode() == BO_Sub &&
1952        isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
1953        isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
1954      return true;
1955    break;
1956  }
1957  case CXXFunctionalCastExprClass:
1958  case CXXStaticCastExprClass:
1959  case ImplicitCastExprClass:
1960  case CStyleCastExprClass:
1961    // Handle casts with a destination that's a struct or union; this
1962    // deals with both the gcc no-op struct cast extension and the
1963    // cast-to-union extension.
1964    if (getType()->isRecordType())
1965      return cast<CastExpr>(this)->getSubExpr()
1966        ->isConstantInitializer(Ctx, false);
1967
1968    // Integer->integer casts can be handled here, which is important for
1969    // things like (int)(&&x-&&y).  Scary but true.
1970    if (getType()->isIntegerType() &&
1971        cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
1972      return cast<CastExpr>(this)->getSubExpr()
1973        ->isConstantInitializer(Ctx, false);
1974
1975    break;
1976  }
1977  return isEvaluatable(Ctx);
1978}
1979
1980/// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
1981/// integer constant expression with the value zero, or if this is one that is
1982/// cast to void*.
1983bool Expr::isNullPointerConstant(ASTContext &Ctx,
1984                                 NullPointerConstantValueDependence NPC) const {
1985  if (isValueDependent()) {
1986    switch (NPC) {
1987    case NPC_NeverValueDependent:
1988      assert(false && "Unexpected value dependent expression!");
1989      // If the unthinkable happens, fall through to the safest alternative.
1990
1991    case NPC_ValueDependentIsNull:
1992      return isTypeDependent() || getType()->isIntegralType(Ctx);
1993
1994    case NPC_ValueDependentIsNotNull:
1995      return false;
1996    }
1997  }
1998
1999  // Strip off a cast to void*, if it exists. Except in C++.
2000  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2001    if (!Ctx.getLangOptions().CPlusPlus) {
2002      // Check that it is a cast to void*.
2003      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2004        QualType Pointee = PT->getPointeeType();
2005        if (!Pointee.hasQualifiers() &&
2006            Pointee->isVoidType() &&                              // to void*
2007            CE->getSubExpr()->getType()->isIntegerType())         // from int.
2008          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2009      }
2010    }
2011  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2012    // Ignore the ImplicitCastExpr type entirely.
2013    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2014  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2015    // Accept ((void*)0) as a null pointer constant, as many other
2016    // implementations do.
2017    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2018  } else if (const CXXDefaultArgExpr *DefaultArg
2019               = dyn_cast<CXXDefaultArgExpr>(this)) {
2020    // See through default argument expressions
2021    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2022  } else if (isa<GNUNullExpr>(this)) {
2023    // The GNU __null extension is always a null pointer constant.
2024    return true;
2025  }
2026
2027  // C++0x nullptr_t is always a null pointer constant.
2028  if (getType()->isNullPtrType())
2029    return true;
2030
2031  if (const RecordType *UT = getType()->getAsUnionType())
2032    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2033      if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2034        const Expr *InitExpr = CLE->getInitializer();
2035        if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2036          return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2037      }
2038  // This expression must be an integer type.
2039  if (!getType()->isIntegerType() ||
2040      (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
2041    return false;
2042
2043  // If we have an integer constant expression, we need to *evaluate* it and
2044  // test for the value 0.
2045  llvm::APSInt Result;
2046  return isIntegerConstantExpr(Result, Ctx) && Result == 0;
2047}
2048
2049FieldDecl *Expr::getBitField() {
2050  Expr *E = this->IgnoreParens();
2051
2052  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2053    if (ICE->getValueKind() != VK_RValue &&
2054        ICE->getCastKind() == CK_NoOp)
2055      E = ICE->getSubExpr()->IgnoreParens();
2056    else
2057      break;
2058  }
2059
2060  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2061    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2062      if (Field->isBitField())
2063        return Field;
2064
2065  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2066    if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2067      if (Field->isBitField())
2068        return Field;
2069
2070  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
2071    if (BinOp->isAssignmentOp() && BinOp->getLHS())
2072      return BinOp->getLHS()->getBitField();
2073
2074  return 0;
2075}
2076
2077bool Expr::refersToVectorElement() const {
2078  const Expr *E = this->IgnoreParens();
2079
2080  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2081    if (ICE->getValueKind() != VK_RValue &&
2082        ICE->getCastKind() == CK_NoOp)
2083      E = ICE->getSubExpr()->IgnoreParens();
2084    else
2085      break;
2086  }
2087
2088  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2089    return ASE->getBase()->getType()->isVectorType();
2090
2091  if (isa<ExtVectorElementExpr>(E))
2092    return true;
2093
2094  return false;
2095}
2096
2097/// isArrow - Return true if the base expression is a pointer to vector,
2098/// return false if the base expression is a vector.
2099bool ExtVectorElementExpr::isArrow() const {
2100  return getBase()->getType()->isPointerType();
2101}
2102
2103unsigned ExtVectorElementExpr::getNumElements() const {
2104  if (const VectorType *VT = getType()->getAs<VectorType>())
2105    return VT->getNumElements();
2106  return 1;
2107}
2108
2109/// containsDuplicateElements - Return true if any element access is repeated.
2110bool ExtVectorElementExpr::containsDuplicateElements() const {
2111  // FIXME: Refactor this code to an accessor on the AST node which returns the
2112  // "type" of component access, and share with code below and in Sema.
2113  llvm::StringRef Comp = Accessor->getName();
2114
2115  // Halving swizzles do not contain duplicate elements.
2116  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
2117    return false;
2118
2119  // Advance past s-char prefix on hex swizzles.
2120  if (Comp[0] == 's' || Comp[0] == 'S')
2121    Comp = Comp.substr(1);
2122
2123  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2124    if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
2125        return true;
2126
2127  return false;
2128}
2129
2130/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
2131void ExtVectorElementExpr::getEncodedElementAccess(
2132                                  llvm::SmallVectorImpl<unsigned> &Elts) const {
2133  llvm::StringRef Comp = Accessor->getName();
2134  if (Comp[0] == 's' || Comp[0] == 'S')
2135    Comp = Comp.substr(1);
2136
2137  bool isHi =   Comp == "hi";
2138  bool isLo =   Comp == "lo";
2139  bool isEven = Comp == "even";
2140  bool isOdd  = Comp == "odd";
2141
2142  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2143    uint64_t Index;
2144
2145    if (isHi)
2146      Index = e + i;
2147    else if (isLo)
2148      Index = i;
2149    else if (isEven)
2150      Index = 2 * i;
2151    else if (isOdd)
2152      Index = 2 * i + 1;
2153    else
2154      Index = ExtVectorType::getAccessorIdx(Comp[i]);
2155
2156    Elts.push_back(Index);
2157  }
2158}
2159
2160ObjCMessageExpr::ObjCMessageExpr(QualType T,
2161                                 SourceLocation LBracLoc,
2162                                 SourceLocation SuperLoc,
2163                                 bool IsInstanceSuper,
2164                                 QualType SuperType,
2165                                 Selector Sel,
2166                                 ObjCMethodDecl *Method,
2167                                 Expr **Args, unsigned NumArgs,
2168                                 SourceLocation RBracLoc)
2169  : Expr(ObjCMessageExprClass, T, /*TypeDependent=*/false,
2170         /*ValueDependent=*/false),
2171    NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2172    HasMethod(Method != 0), SuperLoc(SuperLoc),
2173    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2174                                                       : Sel.getAsOpaquePtr())),
2175    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2176{
2177  setReceiverPointer(SuperType.getAsOpaquePtr());
2178  if (NumArgs)
2179    memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2180}
2181
2182ObjCMessageExpr::ObjCMessageExpr(QualType T,
2183                                 SourceLocation LBracLoc,
2184                                 TypeSourceInfo *Receiver,
2185                                 Selector Sel,
2186                                 ObjCMethodDecl *Method,
2187                                 Expr **Args, unsigned NumArgs,
2188                                 SourceLocation RBracLoc)
2189  : Expr(ObjCMessageExprClass, T, T->isDependentType(),
2190         (T->isDependentType() ||
2191          hasAnyValueDependentArguments(Args, NumArgs))),
2192    NumArgs(NumArgs), Kind(Class), HasMethod(Method != 0),
2193    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2194                                                       : Sel.getAsOpaquePtr())),
2195    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2196{
2197  setReceiverPointer(Receiver);
2198  if (NumArgs)
2199    memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2200}
2201
2202ObjCMessageExpr::ObjCMessageExpr(QualType T,
2203                                 SourceLocation LBracLoc,
2204                                 Expr *Receiver,
2205                                 Selector Sel,
2206                                 ObjCMethodDecl *Method,
2207                                 Expr **Args, unsigned NumArgs,
2208                                 SourceLocation RBracLoc)
2209  : Expr(ObjCMessageExprClass, T, Receiver->isTypeDependent(),
2210         (Receiver->isTypeDependent() ||
2211          hasAnyValueDependentArguments(Args, NumArgs))),
2212    NumArgs(NumArgs), Kind(Instance), HasMethod(Method != 0),
2213    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2214                                                       : Sel.getAsOpaquePtr())),
2215    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2216{
2217  setReceiverPointer(Receiver);
2218  if (NumArgs)
2219    memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2220}
2221
2222ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2223                                         SourceLocation LBracLoc,
2224                                         SourceLocation SuperLoc,
2225                                         bool IsInstanceSuper,
2226                                         QualType SuperType,
2227                                         Selector Sel,
2228                                         ObjCMethodDecl *Method,
2229                                         Expr **Args, unsigned NumArgs,
2230                                         SourceLocation RBracLoc) {
2231  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2232    NumArgs * sizeof(Expr *);
2233  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2234  return new (Mem) ObjCMessageExpr(T, LBracLoc, SuperLoc, IsInstanceSuper,
2235                                   SuperType, Sel, Method, Args, NumArgs,
2236                                   RBracLoc);
2237}
2238
2239ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2240                                         SourceLocation LBracLoc,
2241                                         TypeSourceInfo *Receiver,
2242                                         Selector Sel,
2243                                         ObjCMethodDecl *Method,
2244                                         Expr **Args, unsigned NumArgs,
2245                                         SourceLocation RBracLoc) {
2246  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2247    NumArgs * sizeof(Expr *);
2248  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2249  return new (Mem) ObjCMessageExpr(T, LBracLoc, Receiver, Sel, Method, Args,
2250                                   NumArgs, RBracLoc);
2251}
2252
2253ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2254                                         SourceLocation LBracLoc,
2255                                         Expr *Receiver,
2256                                         Selector Sel,
2257                                         ObjCMethodDecl *Method,
2258                                         Expr **Args, unsigned NumArgs,
2259                                         SourceLocation RBracLoc) {
2260  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2261    NumArgs * sizeof(Expr *);
2262  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2263  return new (Mem) ObjCMessageExpr(T, LBracLoc, Receiver, Sel, Method, Args,
2264                                   NumArgs, RBracLoc);
2265}
2266
2267ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
2268                                              unsigned NumArgs) {
2269  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2270    NumArgs * sizeof(Expr *);
2271  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2272  return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2273}
2274
2275Selector ObjCMessageExpr::getSelector() const {
2276  if (HasMethod)
2277    return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2278                                                               ->getSelector();
2279  return Selector(SelectorOrMethod);
2280}
2281
2282ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2283  switch (getReceiverKind()) {
2284  case Instance:
2285    if (const ObjCObjectPointerType *Ptr
2286          = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2287      return Ptr->getInterfaceDecl();
2288    break;
2289
2290  case Class:
2291    if (const ObjCObjectType *Ty
2292          = getClassReceiver()->getAs<ObjCObjectType>())
2293      return Ty->getInterface();
2294    break;
2295
2296  case SuperInstance:
2297    if (const ObjCObjectPointerType *Ptr
2298          = getSuperType()->getAs<ObjCObjectPointerType>())
2299      return Ptr->getInterfaceDecl();
2300    break;
2301
2302  case SuperClass:
2303    if (const ObjCObjectPointerType *Iface
2304                       = getSuperType()->getAs<ObjCObjectPointerType>())
2305      return Iface->getInterfaceDecl();
2306    break;
2307  }
2308
2309  return 0;
2310}
2311
2312bool ChooseExpr::isConditionTrue(ASTContext &C) const {
2313  return getCond()->EvaluateAsInt(C) != 0;
2314}
2315
2316void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
2317                                 unsigned NumExprs) {
2318  if (SubExprs) C.Deallocate(SubExprs);
2319
2320  SubExprs = new (C) Stmt* [NumExprs];
2321  this->NumExprs = NumExprs;
2322  memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
2323}
2324
2325//===----------------------------------------------------------------------===//
2326//  DesignatedInitExpr
2327//===----------------------------------------------------------------------===//
2328
2329IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
2330  assert(Kind == FieldDesignator && "Only valid on a field designator");
2331  if (Field.NameOrField & 0x01)
2332    return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
2333  else
2334    return getField()->getIdentifier();
2335}
2336
2337DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
2338                                       unsigned NumDesignators,
2339                                       const Designator *Designators,
2340                                       SourceLocation EqualOrColonLoc,
2341                                       bool GNUSyntax,
2342                                       Expr **IndexExprs,
2343                                       unsigned NumIndexExprs,
2344                                       Expr *Init)
2345  : Expr(DesignatedInitExprClass, Ty,
2346         Init->isTypeDependent(), Init->isValueDependent()),
2347    EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
2348    NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
2349  this->Designators = new (C) Designator[NumDesignators];
2350
2351  // Record the initializer itself.
2352  child_iterator Child = child_begin();
2353  *Child++ = Init;
2354
2355  // Copy the designators and their subexpressions, computing
2356  // value-dependence along the way.
2357  unsigned IndexIdx = 0;
2358  for (unsigned I = 0; I != NumDesignators; ++I) {
2359    this->Designators[I] = Designators[I];
2360
2361    if (this->Designators[I].isArrayDesignator()) {
2362      // Compute type- and value-dependence.
2363      Expr *Index = IndexExprs[IndexIdx];
2364      ExprBits.ValueDependent = ExprBits.ValueDependent ||
2365        Index->isTypeDependent() || Index->isValueDependent();
2366
2367      // Copy the index expressions into permanent storage.
2368      *Child++ = IndexExprs[IndexIdx++];
2369    } else if (this->Designators[I].isArrayRangeDesignator()) {
2370      // Compute type- and value-dependence.
2371      Expr *Start = IndexExprs[IndexIdx];
2372      Expr *End = IndexExprs[IndexIdx + 1];
2373      ExprBits.ValueDependent = ExprBits.ValueDependent ||
2374        Start->isTypeDependent() || Start->isValueDependent() ||
2375        End->isTypeDependent() || End->isValueDependent();
2376
2377      // Copy the start/end expressions into permanent storage.
2378      *Child++ = IndexExprs[IndexIdx++];
2379      *Child++ = IndexExprs[IndexIdx++];
2380    }
2381  }
2382
2383  assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
2384}
2385
2386DesignatedInitExpr *
2387DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
2388                           unsigned NumDesignators,
2389                           Expr **IndexExprs, unsigned NumIndexExprs,
2390                           SourceLocation ColonOrEqualLoc,
2391                           bool UsesColonSyntax, Expr *Init) {
2392  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2393                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2394  return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
2395                                      ColonOrEqualLoc, UsesColonSyntax,
2396                                      IndexExprs, NumIndexExprs, Init);
2397}
2398
2399DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
2400                                                    unsigned NumIndexExprs) {
2401  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2402                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2403  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
2404}
2405
2406void DesignatedInitExpr::setDesignators(ASTContext &C,
2407                                        const Designator *Desigs,
2408                                        unsigned NumDesigs) {
2409  Designators = new (C) Designator[NumDesigs];
2410  NumDesignators = NumDesigs;
2411  for (unsigned I = 0; I != NumDesigs; ++I)
2412    Designators[I] = Desigs[I];
2413}
2414
2415SourceRange DesignatedInitExpr::getSourceRange() const {
2416  SourceLocation StartLoc;
2417  Designator &First =
2418    *const_cast<DesignatedInitExpr*>(this)->designators_begin();
2419  if (First.isFieldDesignator()) {
2420    if (GNUSyntax)
2421      StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
2422    else
2423      StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
2424  } else
2425    StartLoc =
2426      SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
2427  return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
2428}
2429
2430Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
2431  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
2432  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2433  Ptr += sizeof(DesignatedInitExpr);
2434  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2435  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2436}
2437
2438Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
2439  assert(D.Kind == Designator::ArrayRangeDesignator &&
2440         "Requires array range designator");
2441  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2442  Ptr += sizeof(DesignatedInitExpr);
2443  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2444  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2445}
2446
2447Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
2448  assert(D.Kind == Designator::ArrayRangeDesignator &&
2449         "Requires array range designator");
2450  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2451  Ptr += sizeof(DesignatedInitExpr);
2452  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2453  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2454}
2455
2456/// \brief Replaces the designator at index @p Idx with the series
2457/// of designators in [First, Last).
2458void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
2459                                          const Designator *First,
2460                                          const Designator *Last) {
2461  unsigned NumNewDesignators = Last - First;
2462  if (NumNewDesignators == 0) {
2463    std::copy_backward(Designators + Idx + 1,
2464                       Designators + NumDesignators,
2465                       Designators + Idx);
2466    --NumNewDesignators;
2467    return;
2468  } else if (NumNewDesignators == 1) {
2469    Designators[Idx] = *First;
2470    return;
2471  }
2472
2473  Designator *NewDesignators
2474    = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
2475  std::copy(Designators, Designators + Idx, NewDesignators);
2476  std::copy(First, Last, NewDesignators + Idx);
2477  std::copy(Designators + Idx + 1, Designators + NumDesignators,
2478            NewDesignators + Idx + NumNewDesignators);
2479  Designators = NewDesignators;
2480  NumDesignators = NumDesignators - 1 + NumNewDesignators;
2481}
2482
2483ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
2484                             Expr **exprs, unsigned nexprs,
2485                             SourceLocation rparenloc)
2486: Expr(ParenListExprClass, QualType(),
2487       hasAnyTypeDependentArguments(exprs, nexprs),
2488       hasAnyValueDependentArguments(exprs, nexprs)),
2489  NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
2490
2491  Exprs = new (C) Stmt*[nexprs];
2492  for (unsigned i = 0; i != nexprs; ++i)
2493    Exprs[i] = exprs[i];
2494}
2495
2496//===----------------------------------------------------------------------===//
2497//  ExprIterator.
2498//===----------------------------------------------------------------------===//
2499
2500Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2501Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2502Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2503const Expr* ConstExprIterator::operator[](size_t idx) const {
2504  return cast<Expr>(I[idx]);
2505}
2506const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2507const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2508
2509//===----------------------------------------------------------------------===//
2510//  Child Iterators for iterating over subexpressions/substatements
2511//===----------------------------------------------------------------------===//
2512
2513// DeclRefExpr
2514Stmt::child_iterator DeclRefExpr::child_begin() { return child_iterator(); }
2515Stmt::child_iterator DeclRefExpr::child_end() { return child_iterator(); }
2516
2517// ObjCIvarRefExpr
2518Stmt::child_iterator ObjCIvarRefExpr::child_begin() { return &Base; }
2519Stmt::child_iterator ObjCIvarRefExpr::child_end() { return &Base+1; }
2520
2521// ObjCPropertyRefExpr
2522Stmt::child_iterator ObjCPropertyRefExpr::child_begin()
2523{
2524  if (BaseExprOrSuperType.is<Stmt*>()) {
2525    // Hack alert!
2526    return reinterpret_cast<Stmt**> (&BaseExprOrSuperType);
2527  }
2528  return child_iterator();
2529}
2530
2531Stmt::child_iterator ObjCPropertyRefExpr::child_end()
2532{ return BaseExprOrSuperType.is<Stmt*>() ?
2533          reinterpret_cast<Stmt**> (&BaseExprOrSuperType)+1 :
2534          child_iterator();
2535}
2536
2537// ObjCImplicitSetterGetterRefExpr
2538Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_begin() {
2539  // If this is accessing a class member or super, skip that entry.
2540  // Technically, 2nd condition is sufficient. But I want to be verbose
2541  if (isSuperReceiver() || !Base)
2542    return child_iterator();
2543  return &Base;
2544}
2545Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_end() {
2546  if (isSuperReceiver() || !Base)
2547    return child_iterator();
2548  return &Base+1;
2549}
2550
2551// ObjCIsaExpr
2552Stmt::child_iterator ObjCIsaExpr::child_begin() { return &Base; }
2553Stmt::child_iterator ObjCIsaExpr::child_end() { return &Base+1; }
2554
2555// PredefinedExpr
2556Stmt::child_iterator PredefinedExpr::child_begin() { return child_iterator(); }
2557Stmt::child_iterator PredefinedExpr::child_end() { return child_iterator(); }
2558
2559// IntegerLiteral
2560Stmt::child_iterator IntegerLiteral::child_begin() { return child_iterator(); }
2561Stmt::child_iterator IntegerLiteral::child_end() { return child_iterator(); }
2562
2563// CharacterLiteral
2564Stmt::child_iterator CharacterLiteral::child_begin() { return child_iterator();}
2565Stmt::child_iterator CharacterLiteral::child_end() { return child_iterator(); }
2566
2567// FloatingLiteral
2568Stmt::child_iterator FloatingLiteral::child_begin() { return child_iterator(); }
2569Stmt::child_iterator FloatingLiteral::child_end() { return child_iterator(); }
2570
2571// ImaginaryLiteral
2572Stmt::child_iterator ImaginaryLiteral::child_begin() { return &Val; }
2573Stmt::child_iterator ImaginaryLiteral::child_end() { return &Val+1; }
2574
2575// StringLiteral
2576Stmt::child_iterator StringLiteral::child_begin() { return child_iterator(); }
2577Stmt::child_iterator StringLiteral::child_end() { return child_iterator(); }
2578
2579// ParenExpr
2580Stmt::child_iterator ParenExpr::child_begin() { return &Val; }
2581Stmt::child_iterator ParenExpr::child_end() { return &Val+1; }
2582
2583// UnaryOperator
2584Stmt::child_iterator UnaryOperator::child_begin() { return &Val; }
2585Stmt::child_iterator UnaryOperator::child_end() { return &Val+1; }
2586
2587// OffsetOfExpr
2588Stmt::child_iterator OffsetOfExpr::child_begin() {
2589  return reinterpret_cast<Stmt **> (reinterpret_cast<OffsetOfNode *> (this + 1)
2590                                      + NumComps);
2591}
2592Stmt::child_iterator OffsetOfExpr::child_end() {
2593  return child_iterator(&*child_begin() + NumExprs);
2594}
2595
2596// SizeOfAlignOfExpr
2597Stmt::child_iterator SizeOfAlignOfExpr::child_begin() {
2598  // If this is of a type and the type is a VLA type (and not a typedef), the
2599  // size expression of the VLA needs to be treated as an executable expression.
2600  // Why isn't this weirdness documented better in StmtIterator?
2601  if (isArgumentType()) {
2602    if (VariableArrayType* T = dyn_cast<VariableArrayType>(
2603                                   getArgumentType().getTypePtr()))
2604      return child_iterator(T);
2605    return child_iterator();
2606  }
2607  return child_iterator(&Argument.Ex);
2608}
2609Stmt::child_iterator SizeOfAlignOfExpr::child_end() {
2610  if (isArgumentType())
2611    return child_iterator();
2612  return child_iterator(&Argument.Ex + 1);
2613}
2614
2615// ArraySubscriptExpr
2616Stmt::child_iterator ArraySubscriptExpr::child_begin() {
2617  return &SubExprs[0];
2618}
2619Stmt::child_iterator ArraySubscriptExpr::child_end() {
2620  return &SubExprs[0]+END_EXPR;
2621}
2622
2623// CallExpr
2624Stmt::child_iterator CallExpr::child_begin() {
2625  return &SubExprs[0];
2626}
2627Stmt::child_iterator CallExpr::child_end() {
2628  return &SubExprs[0]+NumArgs+ARGS_START;
2629}
2630
2631// MemberExpr
2632Stmt::child_iterator MemberExpr::child_begin() { return &Base; }
2633Stmt::child_iterator MemberExpr::child_end() { return &Base+1; }
2634
2635// ExtVectorElementExpr
2636Stmt::child_iterator ExtVectorElementExpr::child_begin() { return &Base; }
2637Stmt::child_iterator ExtVectorElementExpr::child_end() { return &Base+1; }
2638
2639// CompoundLiteralExpr
2640Stmt::child_iterator CompoundLiteralExpr::child_begin() { return &Init; }
2641Stmt::child_iterator CompoundLiteralExpr::child_end() { return &Init+1; }
2642
2643// CastExpr
2644Stmt::child_iterator CastExpr::child_begin() { return &Op; }
2645Stmt::child_iterator CastExpr::child_end() { return &Op+1; }
2646
2647// BinaryOperator
2648Stmt::child_iterator BinaryOperator::child_begin() {
2649  return &SubExprs[0];
2650}
2651Stmt::child_iterator BinaryOperator::child_end() {
2652  return &SubExprs[0]+END_EXPR;
2653}
2654
2655// ConditionalOperator
2656Stmt::child_iterator ConditionalOperator::child_begin() {
2657  return &SubExprs[0];
2658}
2659Stmt::child_iterator ConditionalOperator::child_end() {
2660  return &SubExprs[0]+END_EXPR;
2661}
2662
2663// AddrLabelExpr
2664Stmt::child_iterator AddrLabelExpr::child_begin() { return child_iterator(); }
2665Stmt::child_iterator AddrLabelExpr::child_end() { return child_iterator(); }
2666
2667// StmtExpr
2668Stmt::child_iterator StmtExpr::child_begin() { return &SubStmt; }
2669Stmt::child_iterator StmtExpr::child_end() { return &SubStmt+1; }
2670
2671// TypesCompatibleExpr
2672Stmt::child_iterator TypesCompatibleExpr::child_begin() {
2673  return child_iterator();
2674}
2675
2676Stmt::child_iterator TypesCompatibleExpr::child_end() {
2677  return child_iterator();
2678}
2679
2680// ChooseExpr
2681Stmt::child_iterator ChooseExpr::child_begin() { return &SubExprs[0]; }
2682Stmt::child_iterator ChooseExpr::child_end() { return &SubExprs[0]+END_EXPR; }
2683
2684// GNUNullExpr
2685Stmt::child_iterator GNUNullExpr::child_begin() { return child_iterator(); }
2686Stmt::child_iterator GNUNullExpr::child_end() { return child_iterator(); }
2687
2688// ShuffleVectorExpr
2689Stmt::child_iterator ShuffleVectorExpr::child_begin() {
2690  return &SubExprs[0];
2691}
2692Stmt::child_iterator ShuffleVectorExpr::child_end() {
2693  return &SubExprs[0]+NumExprs;
2694}
2695
2696// VAArgExpr
2697Stmt::child_iterator VAArgExpr::child_begin() { return &Val; }
2698Stmt::child_iterator VAArgExpr::child_end() { return &Val+1; }
2699
2700// InitListExpr
2701Stmt::child_iterator InitListExpr::child_begin() {
2702  return InitExprs.size() ? &InitExprs[0] : 0;
2703}
2704Stmt::child_iterator InitListExpr::child_end() {
2705  return InitExprs.size() ? &InitExprs[0] + InitExprs.size() : 0;
2706}
2707
2708// DesignatedInitExpr
2709Stmt::child_iterator DesignatedInitExpr::child_begin() {
2710  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2711  Ptr += sizeof(DesignatedInitExpr);
2712  return reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2713}
2714Stmt::child_iterator DesignatedInitExpr::child_end() {
2715  return child_iterator(&*child_begin() + NumSubExprs);
2716}
2717
2718// ImplicitValueInitExpr
2719Stmt::child_iterator ImplicitValueInitExpr::child_begin() {
2720  return child_iterator();
2721}
2722
2723Stmt::child_iterator ImplicitValueInitExpr::child_end() {
2724  return child_iterator();
2725}
2726
2727// ParenListExpr
2728Stmt::child_iterator ParenListExpr::child_begin() {
2729  return &Exprs[0];
2730}
2731Stmt::child_iterator ParenListExpr::child_end() {
2732  return &Exprs[0]+NumExprs;
2733}
2734
2735// ObjCStringLiteral
2736Stmt::child_iterator ObjCStringLiteral::child_begin() {
2737  return &String;
2738}
2739Stmt::child_iterator ObjCStringLiteral::child_end() {
2740  return &String+1;
2741}
2742
2743// ObjCEncodeExpr
2744Stmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); }
2745Stmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); }
2746
2747// ObjCSelectorExpr
2748Stmt::child_iterator ObjCSelectorExpr::child_begin() {
2749  return child_iterator();
2750}
2751Stmt::child_iterator ObjCSelectorExpr::child_end() {
2752  return child_iterator();
2753}
2754
2755// ObjCProtocolExpr
2756Stmt::child_iterator ObjCProtocolExpr::child_begin() {
2757  return child_iterator();
2758}
2759Stmt::child_iterator ObjCProtocolExpr::child_end() {
2760  return child_iterator();
2761}
2762
2763// ObjCMessageExpr
2764Stmt::child_iterator ObjCMessageExpr::child_begin() {
2765  if (getReceiverKind() == Instance)
2766    return reinterpret_cast<Stmt **>(this + 1);
2767  return getArgs();
2768}
2769Stmt::child_iterator ObjCMessageExpr::child_end() {
2770  return getArgs() + getNumArgs();
2771}
2772
2773// Blocks
2774Stmt::child_iterator BlockExpr::child_begin() { return child_iterator(); }
2775Stmt::child_iterator BlockExpr::child_end() { return child_iterator(); }
2776
2777Stmt::child_iterator BlockDeclRefExpr::child_begin() { return child_iterator();}
2778Stmt::child_iterator BlockDeclRefExpr::child_end() { return child_iterator(); }
2779
2780// OpaqueValueExpr
2781SourceRange OpaqueValueExpr::getSourceRange() const { return SourceRange(); }
2782Stmt::child_iterator OpaqueValueExpr::child_begin() { return child_iterator(); }
2783Stmt::child_iterator OpaqueValueExpr::child_end() { return child_iterator(); }
2784
2785