Expr.cpp revision 25d0a0f67d9e949ffbfc57bf487012f5cbfd886e
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/EvaluatedExprVisitor.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Lexer.h"
26#include "clang/Sema/SemaDiagnostic.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32#include <algorithm>
33#include <cstring>
34using namespace clang;
35
36/// isKnownToHaveBooleanValue - Return true if this is an integer expression
37/// that is known to return 0 or 1.  This happens for _Bool/bool expressions
38/// but also int expressions which are produced by things like comparisons in
39/// C.
40bool Expr::isKnownToHaveBooleanValue() const {
41  const Expr *E = IgnoreParens();
42
43  // If this value has _Bool type, it is obvious 0/1.
44  if (E->getType()->isBooleanType()) return true;
45  // If this is a non-scalar-integer type, we don't care enough to try.
46  if (!E->getType()->isIntegralOrEnumerationType()) return false;
47
48  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
49    switch (UO->getOpcode()) {
50    case UO_Plus:
51      return UO->getSubExpr()->isKnownToHaveBooleanValue();
52    default:
53      return false;
54    }
55  }
56
57  // Only look through implicit casts.  If the user writes
58  // '(int) (a && b)' treat it as an arbitrary int.
59  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
60    return CE->getSubExpr()->isKnownToHaveBooleanValue();
61
62  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
63    switch (BO->getOpcode()) {
64    default: return false;
65    case BO_LT:   // Relational operators.
66    case BO_GT:
67    case BO_LE:
68    case BO_GE:
69    case BO_EQ:   // Equality operators.
70    case BO_NE:
71    case BO_LAnd: // AND operator.
72    case BO_LOr:  // Logical OR operator.
73      return true;
74
75    case BO_And:  // Bitwise AND operator.
76    case BO_Xor:  // Bitwise XOR operator.
77    case BO_Or:   // Bitwise OR operator.
78      // Handle things like (x==2)|(y==12).
79      return BO->getLHS()->isKnownToHaveBooleanValue() &&
80             BO->getRHS()->isKnownToHaveBooleanValue();
81
82    case BO_Comma:
83    case BO_Assign:
84      return BO->getRHS()->isKnownToHaveBooleanValue();
85    }
86  }
87
88  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
89    return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
90           CO->getFalseExpr()->isKnownToHaveBooleanValue();
91
92  return false;
93}
94
95// Amusing macro metaprogramming hack: check whether a class provides
96// a more specific implementation of getExprLoc().
97namespace {
98  /// This implementation is used when a class provides a custom
99  /// implementation of getExprLoc.
100  template <class E, class T>
101  SourceLocation getExprLocImpl(const Expr *expr,
102                                SourceLocation (T::*v)() const) {
103    return static_cast<const E*>(expr)->getExprLoc();
104  }
105
106  /// This implementation is used when a class doesn't provide
107  /// a custom implementation of getExprLoc.  Overload resolution
108  /// should pick it over the implementation above because it's
109  /// more specialized according to function template partial ordering.
110  template <class E>
111  SourceLocation getExprLocImpl(const Expr *expr,
112                                SourceLocation (Expr::*v)() const) {
113    return static_cast<const E*>(expr)->getSourceRange().getBegin();
114  }
115}
116
117SourceLocation Expr::getExprLoc() const {
118  switch (getStmtClass()) {
119  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
120#define ABSTRACT_STMT(type)
121#define STMT(type, base) \
122  case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
123#define EXPR(type, base) \
124  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
125#include "clang/AST/StmtNodes.inc"
126  }
127  llvm_unreachable("unknown statement kind");
128}
129
130//===----------------------------------------------------------------------===//
131// Primary Expressions.
132//===----------------------------------------------------------------------===//
133
134/// \brief Compute the type-, value-, and instantiation-dependence of a
135/// declaration reference
136/// based on the declaration being referenced.
137static void computeDeclRefDependence(NamedDecl *D, QualType T,
138                                     bool &TypeDependent,
139                                     bool &ValueDependent,
140                                     bool &InstantiationDependent) {
141  TypeDependent = false;
142  ValueDependent = false;
143  InstantiationDependent = false;
144
145  // (TD) C++ [temp.dep.expr]p3:
146  //   An id-expression is type-dependent if it contains:
147  //
148  // and
149  //
150  // (VD) C++ [temp.dep.constexpr]p2:
151  //  An identifier is value-dependent if it is:
152
153  //  (TD)  - an identifier that was declared with dependent type
154  //  (VD)  - a name declared with a dependent type,
155  if (T->isDependentType()) {
156    TypeDependent = true;
157    ValueDependent = true;
158    InstantiationDependent = true;
159    return;
160  } else if (T->isInstantiationDependentType()) {
161    InstantiationDependent = true;
162  }
163
164  //  (TD)  - a conversion-function-id that specifies a dependent type
165  if (D->getDeclName().getNameKind()
166                                == DeclarationName::CXXConversionFunctionName) {
167    QualType T = D->getDeclName().getCXXNameType();
168    if (T->isDependentType()) {
169      TypeDependent = true;
170      ValueDependent = true;
171      InstantiationDependent = true;
172      return;
173    }
174
175    if (T->isInstantiationDependentType())
176      InstantiationDependent = true;
177  }
178
179  //  (VD)  - the name of a non-type template parameter,
180  if (isa<NonTypeTemplateParmDecl>(D)) {
181    ValueDependent = true;
182    InstantiationDependent = true;
183    return;
184  }
185
186  //  (VD) - a constant with integral or enumeration type and is
187  //         initialized with an expression that is value-dependent.
188  //  (VD) - a constant with literal type and is initialized with an
189  //         expression that is value-dependent [C++11].
190  //  (VD) - FIXME: Missing from the standard:
191  //       -  an entity with reference type and is initialized with an
192  //          expression that is value-dependent [C++11]
193  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
194    if ((D->getASTContext().getLangOptions().CPlusPlus0x ?
195           Var->getType()->isLiteralType() :
196           Var->getType()->isIntegralOrEnumerationType()) &&
197        (Var->getType().getCVRQualifiers() == Qualifiers::Const ||
198         Var->getType()->isReferenceType())) {
199      if (const Expr *Init = Var->getAnyInitializer())
200        if (Init->isValueDependent()) {
201          ValueDependent = true;
202          InstantiationDependent = true;
203        }
204    }
205
206    // (VD) - FIXME: Missing from the standard:
207    //      -  a member function or a static data member of the current
208    //         instantiation
209    if (Var->isStaticDataMember() &&
210        Var->getDeclContext()->isDependentContext()) {
211      ValueDependent = true;
212      InstantiationDependent = true;
213    }
214
215    return;
216  }
217
218  // (VD) - FIXME: Missing from the standard:
219  //      -  a member function or a static data member of the current
220  //         instantiation
221  if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
222    ValueDependent = true;
223    InstantiationDependent = true;
224  }
225}
226
227void DeclRefExpr::computeDependence() {
228  bool TypeDependent = false;
229  bool ValueDependent = false;
230  bool InstantiationDependent = false;
231  computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent,
232                           InstantiationDependent);
233
234  // (TD) C++ [temp.dep.expr]p3:
235  //   An id-expression is type-dependent if it contains:
236  //
237  // and
238  //
239  // (VD) C++ [temp.dep.constexpr]p2:
240  //  An identifier is value-dependent if it is:
241  if (!TypeDependent && !ValueDependent &&
242      hasExplicitTemplateArgs() &&
243      TemplateSpecializationType::anyDependentTemplateArguments(
244                                                            getTemplateArgs(),
245                                                       getNumTemplateArgs(),
246                                                      InstantiationDependent)) {
247    TypeDependent = true;
248    ValueDependent = true;
249    InstantiationDependent = true;
250  }
251
252  ExprBits.TypeDependent = TypeDependent;
253  ExprBits.ValueDependent = ValueDependent;
254  ExprBits.InstantiationDependent = InstantiationDependent;
255
256  // Is the declaration a parameter pack?
257  if (getDecl()->isParameterPack())
258    ExprBits.ContainsUnexpandedParameterPack = true;
259}
260
261DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
262                         SourceLocation TemplateKWLoc,
263                         ValueDecl *D, const DeclarationNameInfo &NameInfo,
264                         NamedDecl *FoundD,
265                         const TemplateArgumentListInfo *TemplateArgs,
266                         QualType T, ExprValueKind VK)
267  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
268    D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
269  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
270  if (QualifierLoc)
271    getInternalQualifierLoc() = QualifierLoc;
272  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
273  if (FoundD)
274    getInternalFoundDecl() = FoundD;
275  DeclRefExprBits.HasTemplateKWAndArgsInfo
276    = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
277  if (TemplateArgs) {
278    bool Dependent = false;
279    bool InstantiationDependent = false;
280    bool ContainsUnexpandedParameterPack = false;
281    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
282                                               Dependent,
283                                               InstantiationDependent,
284                                               ContainsUnexpandedParameterPack);
285    if (InstantiationDependent)
286      setInstantiationDependent(true);
287  } else if (TemplateKWLoc.isValid()) {
288    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
289  }
290  DeclRefExprBits.HadMultipleCandidates = 0;
291
292  computeDependence();
293}
294
295DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
296                                 NestedNameSpecifierLoc QualifierLoc,
297                                 SourceLocation TemplateKWLoc,
298                                 ValueDecl *D,
299                                 SourceLocation NameLoc,
300                                 QualType T,
301                                 ExprValueKind VK,
302                                 NamedDecl *FoundD,
303                                 const TemplateArgumentListInfo *TemplateArgs) {
304  return Create(Context, QualifierLoc, TemplateKWLoc, D,
305                DeclarationNameInfo(D->getDeclName(), NameLoc),
306                T, VK, FoundD, TemplateArgs);
307}
308
309DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
310                                 NestedNameSpecifierLoc QualifierLoc,
311                                 SourceLocation TemplateKWLoc,
312                                 ValueDecl *D,
313                                 const DeclarationNameInfo &NameInfo,
314                                 QualType T,
315                                 ExprValueKind VK,
316                                 NamedDecl *FoundD,
317                                 const TemplateArgumentListInfo *TemplateArgs) {
318  // Filter out cases where the found Decl is the same as the value refenenced.
319  if (D == FoundD)
320    FoundD = 0;
321
322  std::size_t Size = sizeof(DeclRefExpr);
323  if (QualifierLoc != 0)
324    Size += sizeof(NestedNameSpecifierLoc);
325  if (FoundD)
326    Size += sizeof(NamedDecl *);
327  if (TemplateArgs)
328    Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
329  else if (TemplateKWLoc.isValid())
330    Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
331
332  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
333  return new (Mem) DeclRefExpr(QualifierLoc, TemplateKWLoc, D, NameInfo,
334                               FoundD, TemplateArgs, T, VK);
335}
336
337DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
338                                      bool HasQualifier,
339                                      bool HasFoundDecl,
340                                      bool HasTemplateKWAndArgsInfo,
341                                      unsigned NumTemplateArgs) {
342  std::size_t Size = sizeof(DeclRefExpr);
343  if (HasQualifier)
344    Size += sizeof(NestedNameSpecifierLoc);
345  if (HasFoundDecl)
346    Size += sizeof(NamedDecl *);
347  if (HasTemplateKWAndArgsInfo)
348    Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
349
350  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
351  return new (Mem) DeclRefExpr(EmptyShell());
352}
353
354SourceRange DeclRefExpr::getSourceRange() const {
355  SourceRange R = getNameInfo().getSourceRange();
356  if (hasQualifier())
357    R.setBegin(getQualifierLoc().getBeginLoc());
358  if (hasExplicitTemplateArgs())
359    R.setEnd(getRAngleLoc());
360  return R;
361}
362
363// FIXME: Maybe this should use DeclPrinter with a special "print predefined
364// expr" policy instead.
365std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
366  ASTContext &Context = CurrentDecl->getASTContext();
367
368  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
369    if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
370      return FD->getNameAsString();
371
372    SmallString<256> Name;
373    llvm::raw_svector_ostream Out(Name);
374
375    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
376      if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
377        Out << "virtual ";
378      if (MD->isStatic())
379        Out << "static ";
380    }
381
382    PrintingPolicy Policy(Context.getLangOptions());
383
384    std::string Proto = FD->getQualifiedNameAsString(Policy);
385
386    const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
387    const FunctionProtoType *FT = 0;
388    if (FD->hasWrittenPrototype())
389      FT = dyn_cast<FunctionProtoType>(AFT);
390
391    Proto += "(";
392    if (FT) {
393      llvm::raw_string_ostream POut(Proto);
394      for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
395        if (i) POut << ", ";
396        std::string Param;
397        FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
398        POut << Param;
399      }
400
401      if (FT->isVariadic()) {
402        if (FD->getNumParams()) POut << ", ";
403        POut << "...";
404      }
405    }
406    Proto += ")";
407
408    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
409      Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
410      if (ThisQuals.hasConst())
411        Proto += " const";
412      if (ThisQuals.hasVolatile())
413        Proto += " volatile";
414    }
415
416    if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
417      AFT->getResultType().getAsStringInternal(Proto, Policy);
418
419    Out << Proto;
420
421    Out.flush();
422    return Name.str().str();
423  }
424  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
425    SmallString<256> Name;
426    llvm::raw_svector_ostream Out(Name);
427    Out << (MD->isInstanceMethod() ? '-' : '+');
428    Out << '[';
429
430    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
431    // a null check to avoid a crash.
432    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
433      Out << *ID;
434
435    if (const ObjCCategoryImplDecl *CID =
436        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
437      Out << '(' << *CID << ')';
438
439    Out <<  ' ';
440    Out << MD->getSelector().getAsString();
441    Out <<  ']';
442
443    Out.flush();
444    return Name.str().str();
445  }
446  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
447    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
448    return "top level";
449  }
450  return "";
451}
452
453void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
454  if (hasAllocation())
455    C.Deallocate(pVal);
456
457  BitWidth = Val.getBitWidth();
458  unsigned NumWords = Val.getNumWords();
459  const uint64_t* Words = Val.getRawData();
460  if (NumWords > 1) {
461    pVal = new (C) uint64_t[NumWords];
462    std::copy(Words, Words + NumWords, pVal);
463  } else if (NumWords == 1)
464    VAL = Words[0];
465  else
466    VAL = 0;
467}
468
469IntegerLiteral *
470IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
471                       QualType type, SourceLocation l) {
472  return new (C) IntegerLiteral(C, V, type, l);
473}
474
475IntegerLiteral *
476IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
477  return new (C) IntegerLiteral(Empty);
478}
479
480FloatingLiteral *
481FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
482                        bool isexact, QualType Type, SourceLocation L) {
483  return new (C) FloatingLiteral(C, V, isexact, Type, L);
484}
485
486FloatingLiteral *
487FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
488  return new (C) FloatingLiteral(C, Empty);
489}
490
491/// getValueAsApproximateDouble - This returns the value as an inaccurate
492/// double.  Note that this may cause loss of precision, but is useful for
493/// debugging dumps, etc.
494double FloatingLiteral::getValueAsApproximateDouble() const {
495  llvm::APFloat V = getValue();
496  bool ignored;
497  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
498            &ignored);
499  return V.convertToDouble();
500}
501
502int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
503  int CharByteWidth;
504  switch(k) {
505    case Ascii:
506    case UTF8:
507      CharByteWidth = target.getCharWidth();
508      break;
509    case Wide:
510      CharByteWidth = target.getWCharWidth();
511      break;
512    case UTF16:
513      CharByteWidth = target.getChar16Width();
514      break;
515    case UTF32:
516      CharByteWidth = target.getChar32Width();
517  }
518  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
519  CharByteWidth /= 8;
520  assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
521         && "character byte widths supported are 1, 2, and 4 only");
522  return CharByteWidth;
523}
524
525StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
526                                     StringKind Kind, bool Pascal, QualType Ty,
527                                     const SourceLocation *Loc,
528                                     unsigned NumStrs) {
529  // Allocate enough space for the StringLiteral plus an array of locations for
530  // any concatenated string tokens.
531  void *Mem = C.Allocate(sizeof(StringLiteral)+
532                         sizeof(SourceLocation)*(NumStrs-1),
533                         llvm::alignOf<StringLiteral>());
534  StringLiteral *SL = new (Mem) StringLiteral(Ty);
535
536  // OPTIMIZE: could allocate this appended to the StringLiteral.
537  SL->setString(C,Str,Kind,Pascal);
538
539  SL->TokLocs[0] = Loc[0];
540  SL->NumConcatenated = NumStrs;
541
542  if (NumStrs != 1)
543    memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
544  return SL;
545}
546
547StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
548  void *Mem = C.Allocate(sizeof(StringLiteral)+
549                         sizeof(SourceLocation)*(NumStrs-1),
550                         llvm::alignOf<StringLiteral>());
551  StringLiteral *SL = new (Mem) StringLiteral(QualType());
552  SL->CharByteWidth = 0;
553  SL->Length = 0;
554  SL->NumConcatenated = NumStrs;
555  return SL;
556}
557
558void StringLiteral::setString(ASTContext &C, StringRef Str,
559                              StringKind Kind, bool IsPascal) {
560  //FIXME: we assume that the string data comes from a target that uses the same
561  // code unit size and endianess for the type of string.
562  this->Kind = Kind;
563  this->IsPascal = IsPascal;
564
565  CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
566  assert((Str.size()%CharByteWidth == 0)
567         && "size of data must be multiple of CharByteWidth");
568  Length = Str.size()/CharByteWidth;
569
570  switch(CharByteWidth) {
571    case 1: {
572      char *AStrData = new (C) char[Length];
573      std::memcpy(AStrData,Str.data(),Str.size());
574      StrData.asChar = AStrData;
575      break;
576    }
577    case 2: {
578      uint16_t *AStrData = new (C) uint16_t[Length];
579      std::memcpy(AStrData,Str.data(),Str.size());
580      StrData.asUInt16 = AStrData;
581      break;
582    }
583    case 4: {
584      uint32_t *AStrData = new (C) uint32_t[Length];
585      std::memcpy(AStrData,Str.data(),Str.size());
586      StrData.asUInt32 = AStrData;
587      break;
588    }
589    default:
590      assert(false && "unsupported CharByteWidth");
591  }
592}
593
594/// getLocationOfByte - Return a source location that points to the specified
595/// byte of this string literal.
596///
597/// Strings are amazingly complex.  They can be formed from multiple tokens and
598/// can have escape sequences in them in addition to the usual trigraph and
599/// escaped newline business.  This routine handles this complexity.
600///
601SourceLocation StringLiteral::
602getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
603                  const LangOptions &Features, const TargetInfo &Target) const {
604  assert(Kind == StringLiteral::Ascii && "This only works for ASCII strings");
605
606  // Loop over all of the tokens in this string until we find the one that
607  // contains the byte we're looking for.
608  unsigned TokNo = 0;
609  while (1) {
610    assert(TokNo < getNumConcatenated() && "Invalid byte number!");
611    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
612
613    // Get the spelling of the string so that we can get the data that makes up
614    // the string literal, not the identifier for the macro it is potentially
615    // expanded through.
616    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
617
618    // Re-lex the token to get its length and original spelling.
619    std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
620    bool Invalid = false;
621    StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
622    if (Invalid)
623      return StrTokSpellingLoc;
624
625    const char *StrData = Buffer.data()+LocInfo.second;
626
627    // Create a langops struct and enable trigraphs.  This is sufficient for
628    // relexing tokens.
629    LangOptions LangOpts;
630    LangOpts.Trigraphs = true;
631
632    // Create a lexer starting at the beginning of this token.
633    Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
634                   Buffer.end());
635    Token TheTok;
636    TheLexer.LexFromRawLexer(TheTok);
637
638    // Use the StringLiteralParser to compute the length of the string in bytes.
639    StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
640    unsigned TokNumBytes = SLP.GetStringLength();
641
642    // If the byte is in this token, return the location of the byte.
643    if (ByteNo < TokNumBytes ||
644        (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
645      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
646
647      // Now that we know the offset of the token in the spelling, use the
648      // preprocessor to get the offset in the original source.
649      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
650    }
651
652    // Move to the next string token.
653    ++TokNo;
654    ByteNo -= TokNumBytes;
655  }
656}
657
658
659
660/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
661/// corresponds to, e.g. "sizeof" or "[pre]++".
662const char *UnaryOperator::getOpcodeStr(Opcode Op) {
663  switch (Op) {
664  case UO_PostInc: return "++";
665  case UO_PostDec: return "--";
666  case UO_PreInc:  return "++";
667  case UO_PreDec:  return "--";
668  case UO_AddrOf:  return "&";
669  case UO_Deref:   return "*";
670  case UO_Plus:    return "+";
671  case UO_Minus:   return "-";
672  case UO_Not:     return "~";
673  case UO_LNot:    return "!";
674  case UO_Real:    return "__real";
675  case UO_Imag:    return "__imag";
676  case UO_Extension: return "__extension__";
677  }
678  llvm_unreachable("Unknown unary operator");
679}
680
681UnaryOperatorKind
682UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
683  switch (OO) {
684  default: llvm_unreachable("No unary operator for overloaded function");
685  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
686  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
687  case OO_Amp:        return UO_AddrOf;
688  case OO_Star:       return UO_Deref;
689  case OO_Plus:       return UO_Plus;
690  case OO_Minus:      return UO_Minus;
691  case OO_Tilde:      return UO_Not;
692  case OO_Exclaim:    return UO_LNot;
693  }
694}
695
696OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
697  switch (Opc) {
698  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
699  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
700  case UO_AddrOf: return OO_Amp;
701  case UO_Deref: return OO_Star;
702  case UO_Plus: return OO_Plus;
703  case UO_Minus: return OO_Minus;
704  case UO_Not: return OO_Tilde;
705  case UO_LNot: return OO_Exclaim;
706  default: return OO_None;
707  }
708}
709
710
711//===----------------------------------------------------------------------===//
712// Postfix Operators.
713//===----------------------------------------------------------------------===//
714
715CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
716                   Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
717                   SourceLocation rparenloc)
718  : Expr(SC, t, VK, OK_Ordinary,
719         fn->isTypeDependent(),
720         fn->isValueDependent(),
721         fn->isInstantiationDependent(),
722         fn->containsUnexpandedParameterPack()),
723    NumArgs(numargs) {
724
725  SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
726  SubExprs[FN] = fn;
727  for (unsigned i = 0; i != numargs; ++i) {
728    if (args[i]->isTypeDependent())
729      ExprBits.TypeDependent = true;
730    if (args[i]->isValueDependent())
731      ExprBits.ValueDependent = true;
732    if (args[i]->isInstantiationDependent())
733      ExprBits.InstantiationDependent = true;
734    if (args[i]->containsUnexpandedParameterPack())
735      ExprBits.ContainsUnexpandedParameterPack = true;
736
737    SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
738  }
739
740  CallExprBits.NumPreArgs = NumPreArgs;
741  RParenLoc = rparenloc;
742}
743
744CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
745                   QualType t, ExprValueKind VK, SourceLocation rparenloc)
746  : Expr(CallExprClass, t, VK, OK_Ordinary,
747         fn->isTypeDependent(),
748         fn->isValueDependent(),
749         fn->isInstantiationDependent(),
750         fn->containsUnexpandedParameterPack()),
751    NumArgs(numargs) {
752
753  SubExprs = new (C) Stmt*[numargs+PREARGS_START];
754  SubExprs[FN] = fn;
755  for (unsigned i = 0; i != numargs; ++i) {
756    if (args[i]->isTypeDependent())
757      ExprBits.TypeDependent = true;
758    if (args[i]->isValueDependent())
759      ExprBits.ValueDependent = true;
760    if (args[i]->isInstantiationDependent())
761      ExprBits.InstantiationDependent = true;
762    if (args[i]->containsUnexpandedParameterPack())
763      ExprBits.ContainsUnexpandedParameterPack = true;
764
765    SubExprs[i+PREARGS_START] = args[i];
766  }
767
768  CallExprBits.NumPreArgs = 0;
769  RParenLoc = rparenloc;
770}
771
772CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
773  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
774  // FIXME: Why do we allocate this?
775  SubExprs = new (C) Stmt*[PREARGS_START];
776  CallExprBits.NumPreArgs = 0;
777}
778
779CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
780                   EmptyShell Empty)
781  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
782  // FIXME: Why do we allocate this?
783  SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
784  CallExprBits.NumPreArgs = NumPreArgs;
785}
786
787Decl *CallExpr::getCalleeDecl() {
788  Expr *CEE = getCallee()->IgnoreParenImpCasts();
789
790  while (SubstNonTypeTemplateParmExpr *NTTP
791                                = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
792    CEE = NTTP->getReplacement()->IgnoreParenCasts();
793  }
794
795  // If we're calling a dereference, look at the pointer instead.
796  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
797    if (BO->isPtrMemOp())
798      CEE = BO->getRHS()->IgnoreParenCasts();
799  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
800    if (UO->getOpcode() == UO_Deref)
801      CEE = UO->getSubExpr()->IgnoreParenCasts();
802  }
803  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
804    return DRE->getDecl();
805  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
806    return ME->getMemberDecl();
807
808  return 0;
809}
810
811FunctionDecl *CallExpr::getDirectCallee() {
812  return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
813}
814
815/// setNumArgs - This changes the number of arguments present in this call.
816/// Any orphaned expressions are deleted by this, and any new operands are set
817/// to null.
818void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
819  // No change, just return.
820  if (NumArgs == getNumArgs()) return;
821
822  // If shrinking # arguments, just delete the extras and forgot them.
823  if (NumArgs < getNumArgs()) {
824    this->NumArgs = NumArgs;
825    return;
826  }
827
828  // Otherwise, we are growing the # arguments.  New an bigger argument array.
829  unsigned NumPreArgs = getNumPreArgs();
830  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
831  // Copy over args.
832  for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
833    NewSubExprs[i] = SubExprs[i];
834  // Null out new args.
835  for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
836       i != NumArgs+PREARGS_START+NumPreArgs; ++i)
837    NewSubExprs[i] = 0;
838
839  if (SubExprs) C.Deallocate(SubExprs);
840  SubExprs = NewSubExprs;
841  this->NumArgs = NumArgs;
842}
843
844/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
845/// not, return 0.
846unsigned CallExpr::isBuiltinCall() const {
847  // All simple function calls (e.g. func()) are implicitly cast to pointer to
848  // function. As a result, we try and obtain the DeclRefExpr from the
849  // ImplicitCastExpr.
850  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
851  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
852    return 0;
853
854  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
855  if (!DRE)
856    return 0;
857
858  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
859  if (!FDecl)
860    return 0;
861
862  if (!FDecl->getIdentifier())
863    return 0;
864
865  return FDecl->getBuiltinID();
866}
867
868QualType CallExpr::getCallReturnType() const {
869  QualType CalleeType = getCallee()->getType();
870  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
871    CalleeType = FnTypePtr->getPointeeType();
872  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
873    CalleeType = BPT->getPointeeType();
874  else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
875    // This should never be overloaded and so should never return null.
876    CalleeType = Expr::findBoundMemberType(getCallee());
877
878  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
879  return FnType->getResultType();
880}
881
882SourceRange CallExpr::getSourceRange() const {
883  if (isa<CXXOperatorCallExpr>(this))
884    return cast<CXXOperatorCallExpr>(this)->getSourceRange();
885
886  SourceLocation begin = getCallee()->getLocStart();
887  if (begin.isInvalid() && getNumArgs() > 0)
888    begin = getArg(0)->getLocStart();
889  SourceLocation end = getRParenLoc();
890  if (end.isInvalid() && getNumArgs() > 0)
891    end = getArg(getNumArgs() - 1)->getLocEnd();
892  return SourceRange(begin, end);
893}
894
895OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
896                                   SourceLocation OperatorLoc,
897                                   TypeSourceInfo *tsi,
898                                   OffsetOfNode* compsPtr, unsigned numComps,
899                                   Expr** exprsPtr, unsigned numExprs,
900                                   SourceLocation RParenLoc) {
901  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
902                         sizeof(OffsetOfNode) * numComps +
903                         sizeof(Expr*) * numExprs);
904
905  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
906                                exprsPtr, numExprs, RParenLoc);
907}
908
909OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
910                                        unsigned numComps, unsigned numExprs) {
911  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
912                         sizeof(OffsetOfNode) * numComps +
913                         sizeof(Expr*) * numExprs);
914  return new (Mem) OffsetOfExpr(numComps, numExprs);
915}
916
917OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
918                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,
919                           OffsetOfNode* compsPtr, unsigned numComps,
920                           Expr** exprsPtr, unsigned numExprs,
921                           SourceLocation RParenLoc)
922  : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
923         /*TypeDependent=*/false,
924         /*ValueDependent=*/tsi->getType()->isDependentType(),
925         tsi->getType()->isInstantiationDependentType(),
926         tsi->getType()->containsUnexpandedParameterPack()),
927    OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
928    NumComps(numComps), NumExprs(numExprs)
929{
930  for(unsigned i = 0; i < numComps; ++i) {
931    setComponent(i, compsPtr[i]);
932  }
933
934  for(unsigned i = 0; i < numExprs; ++i) {
935    if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
936      ExprBits.ValueDependent = true;
937    if (exprsPtr[i]->containsUnexpandedParameterPack())
938      ExprBits.ContainsUnexpandedParameterPack = true;
939
940    setIndexExpr(i, exprsPtr[i]);
941  }
942}
943
944IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
945  assert(getKind() == Field || getKind() == Identifier);
946  if (getKind() == Field)
947    return getField()->getIdentifier();
948
949  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
950}
951
952MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
953                               NestedNameSpecifierLoc QualifierLoc,
954                               SourceLocation TemplateKWLoc,
955                               ValueDecl *memberdecl,
956                               DeclAccessPair founddecl,
957                               DeclarationNameInfo nameinfo,
958                               const TemplateArgumentListInfo *targs,
959                               QualType ty,
960                               ExprValueKind vk,
961                               ExprObjectKind ok) {
962  std::size_t Size = sizeof(MemberExpr);
963
964  bool hasQualOrFound = (QualifierLoc ||
965                         founddecl.getDecl() != memberdecl ||
966                         founddecl.getAccess() != memberdecl->getAccess());
967  if (hasQualOrFound)
968    Size += sizeof(MemberNameQualifier);
969
970  if (targs)
971    Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
972  else if (TemplateKWLoc.isValid())
973    Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
974
975  void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
976  MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
977                                       ty, vk, ok);
978
979  if (hasQualOrFound) {
980    // FIXME: Wrong. We should be looking at the member declaration we found.
981    if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
982      E->setValueDependent(true);
983      E->setTypeDependent(true);
984      E->setInstantiationDependent(true);
985    }
986    else if (QualifierLoc &&
987             QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
988      E->setInstantiationDependent(true);
989
990    E->HasQualifierOrFoundDecl = true;
991
992    MemberNameQualifier *NQ = E->getMemberQualifier();
993    NQ->QualifierLoc = QualifierLoc;
994    NQ->FoundDecl = founddecl;
995  }
996
997  E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
998
999  if (targs) {
1000    bool Dependent = false;
1001    bool InstantiationDependent = false;
1002    bool ContainsUnexpandedParameterPack = false;
1003    E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
1004                                                  Dependent,
1005                                                  InstantiationDependent,
1006                                             ContainsUnexpandedParameterPack);
1007    if (InstantiationDependent)
1008      E->setInstantiationDependent(true);
1009  } else if (TemplateKWLoc.isValid()) {
1010    E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1011  }
1012
1013  return E;
1014}
1015
1016SourceRange MemberExpr::getSourceRange() const {
1017  SourceLocation StartLoc;
1018  if (isImplicitAccess()) {
1019    if (hasQualifier())
1020      StartLoc = getQualifierLoc().getBeginLoc();
1021    else
1022      StartLoc = MemberLoc;
1023  } else {
1024    // FIXME: We don't want this to happen. Rather, we should be able to
1025    // detect all kinds of implicit accesses more cleanly.
1026    StartLoc = getBase()->getLocStart();
1027    if (StartLoc.isInvalid())
1028      StartLoc = MemberLoc;
1029  }
1030
1031  SourceLocation EndLoc = hasExplicitTemplateArgs()
1032    ? getRAngleLoc() : getMemberNameInfo().getEndLoc();
1033
1034  return SourceRange(StartLoc, EndLoc);
1035}
1036
1037void CastExpr::CheckCastConsistency() const {
1038  switch (getCastKind()) {
1039  case CK_DerivedToBase:
1040  case CK_UncheckedDerivedToBase:
1041  case CK_DerivedToBaseMemberPointer:
1042  case CK_BaseToDerived:
1043  case CK_BaseToDerivedMemberPointer:
1044    assert(!path_empty() && "Cast kind should have a base path!");
1045    break;
1046
1047  case CK_CPointerToObjCPointerCast:
1048    assert(getType()->isObjCObjectPointerType());
1049    assert(getSubExpr()->getType()->isPointerType());
1050    goto CheckNoBasePath;
1051
1052  case CK_BlockPointerToObjCPointerCast:
1053    assert(getType()->isObjCObjectPointerType());
1054    assert(getSubExpr()->getType()->isBlockPointerType());
1055    goto CheckNoBasePath;
1056
1057  case CK_ReinterpretMemberPointer:
1058    assert(getType()->isMemberPointerType());
1059    assert(getSubExpr()->getType()->isMemberPointerType());
1060    goto CheckNoBasePath;
1061
1062  case CK_BitCast:
1063    // Arbitrary casts to C pointer types count as bitcasts.
1064    // Otherwise, we should only have block and ObjC pointer casts
1065    // here if they stay within the type kind.
1066    if (!getType()->isPointerType()) {
1067      assert(getType()->isObjCObjectPointerType() ==
1068             getSubExpr()->getType()->isObjCObjectPointerType());
1069      assert(getType()->isBlockPointerType() ==
1070             getSubExpr()->getType()->isBlockPointerType());
1071    }
1072    goto CheckNoBasePath;
1073
1074  case CK_AnyPointerToBlockPointerCast:
1075    assert(getType()->isBlockPointerType());
1076    assert(getSubExpr()->getType()->isAnyPointerType() &&
1077           !getSubExpr()->getType()->isBlockPointerType());
1078    goto CheckNoBasePath;
1079
1080  case CK_CopyAndAutoreleaseBlockObject:
1081    assert(getType()->isBlockPointerType());
1082    assert(getSubExpr()->getType()->isBlockPointerType());
1083    goto CheckNoBasePath;
1084
1085  // These should not have an inheritance path.
1086  case CK_Dynamic:
1087  case CK_ToUnion:
1088  case CK_ArrayToPointerDecay:
1089  case CK_FunctionToPointerDecay:
1090  case CK_NullToMemberPointer:
1091  case CK_NullToPointer:
1092  case CK_ConstructorConversion:
1093  case CK_IntegralToPointer:
1094  case CK_PointerToIntegral:
1095  case CK_ToVoid:
1096  case CK_VectorSplat:
1097  case CK_IntegralCast:
1098  case CK_IntegralToFloating:
1099  case CK_FloatingToIntegral:
1100  case CK_FloatingCast:
1101  case CK_ObjCObjectLValueCast:
1102  case CK_FloatingRealToComplex:
1103  case CK_FloatingComplexToReal:
1104  case CK_FloatingComplexCast:
1105  case CK_FloatingComplexToIntegralComplex:
1106  case CK_IntegralRealToComplex:
1107  case CK_IntegralComplexToReal:
1108  case CK_IntegralComplexCast:
1109  case CK_IntegralComplexToFloatingComplex:
1110  case CK_ARCProduceObject:
1111  case CK_ARCConsumeObject:
1112  case CK_ARCReclaimReturnedObject:
1113  case CK_ARCExtendBlockObject:
1114    assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1115    goto CheckNoBasePath;
1116
1117  case CK_Dependent:
1118  case CK_LValueToRValue:
1119  case CK_NoOp:
1120  case CK_AtomicToNonAtomic:
1121  case CK_NonAtomicToAtomic:
1122  case CK_PointerToBoolean:
1123  case CK_IntegralToBoolean:
1124  case CK_FloatingToBoolean:
1125  case CK_MemberPointerToBoolean:
1126  case CK_FloatingComplexToBoolean:
1127  case CK_IntegralComplexToBoolean:
1128  case CK_LValueBitCast:            // -> bool&
1129  case CK_UserDefinedConversion:    // operator bool()
1130  CheckNoBasePath:
1131    assert(path_empty() && "Cast kind should not have a base path!");
1132    break;
1133  }
1134}
1135
1136const char *CastExpr::getCastKindName() const {
1137  switch (getCastKind()) {
1138  case CK_Dependent:
1139    return "Dependent";
1140  case CK_BitCast:
1141    return "BitCast";
1142  case CK_LValueBitCast:
1143    return "LValueBitCast";
1144  case CK_LValueToRValue:
1145    return "LValueToRValue";
1146  case CK_NoOp:
1147    return "NoOp";
1148  case CK_BaseToDerived:
1149    return "BaseToDerived";
1150  case CK_DerivedToBase:
1151    return "DerivedToBase";
1152  case CK_UncheckedDerivedToBase:
1153    return "UncheckedDerivedToBase";
1154  case CK_Dynamic:
1155    return "Dynamic";
1156  case CK_ToUnion:
1157    return "ToUnion";
1158  case CK_ArrayToPointerDecay:
1159    return "ArrayToPointerDecay";
1160  case CK_FunctionToPointerDecay:
1161    return "FunctionToPointerDecay";
1162  case CK_NullToMemberPointer:
1163    return "NullToMemberPointer";
1164  case CK_NullToPointer:
1165    return "NullToPointer";
1166  case CK_BaseToDerivedMemberPointer:
1167    return "BaseToDerivedMemberPointer";
1168  case CK_DerivedToBaseMemberPointer:
1169    return "DerivedToBaseMemberPointer";
1170  case CK_ReinterpretMemberPointer:
1171    return "ReinterpretMemberPointer";
1172  case CK_UserDefinedConversion:
1173    return "UserDefinedConversion";
1174  case CK_ConstructorConversion:
1175    return "ConstructorConversion";
1176  case CK_IntegralToPointer:
1177    return "IntegralToPointer";
1178  case CK_PointerToIntegral:
1179    return "PointerToIntegral";
1180  case CK_PointerToBoolean:
1181    return "PointerToBoolean";
1182  case CK_ToVoid:
1183    return "ToVoid";
1184  case CK_VectorSplat:
1185    return "VectorSplat";
1186  case CK_IntegralCast:
1187    return "IntegralCast";
1188  case CK_IntegralToBoolean:
1189    return "IntegralToBoolean";
1190  case CK_IntegralToFloating:
1191    return "IntegralToFloating";
1192  case CK_FloatingToIntegral:
1193    return "FloatingToIntegral";
1194  case CK_FloatingCast:
1195    return "FloatingCast";
1196  case CK_FloatingToBoolean:
1197    return "FloatingToBoolean";
1198  case CK_MemberPointerToBoolean:
1199    return "MemberPointerToBoolean";
1200  case CK_CPointerToObjCPointerCast:
1201    return "CPointerToObjCPointerCast";
1202  case CK_BlockPointerToObjCPointerCast:
1203    return "BlockPointerToObjCPointerCast";
1204  case CK_AnyPointerToBlockPointerCast:
1205    return "AnyPointerToBlockPointerCast";
1206  case CK_ObjCObjectLValueCast:
1207    return "ObjCObjectLValueCast";
1208  case CK_FloatingRealToComplex:
1209    return "FloatingRealToComplex";
1210  case CK_FloatingComplexToReal:
1211    return "FloatingComplexToReal";
1212  case CK_FloatingComplexToBoolean:
1213    return "FloatingComplexToBoolean";
1214  case CK_FloatingComplexCast:
1215    return "FloatingComplexCast";
1216  case CK_FloatingComplexToIntegralComplex:
1217    return "FloatingComplexToIntegralComplex";
1218  case CK_IntegralRealToComplex:
1219    return "IntegralRealToComplex";
1220  case CK_IntegralComplexToReal:
1221    return "IntegralComplexToReal";
1222  case CK_IntegralComplexToBoolean:
1223    return "IntegralComplexToBoolean";
1224  case CK_IntegralComplexCast:
1225    return "IntegralComplexCast";
1226  case CK_IntegralComplexToFloatingComplex:
1227    return "IntegralComplexToFloatingComplex";
1228  case CK_ARCConsumeObject:
1229    return "ARCConsumeObject";
1230  case CK_ARCProduceObject:
1231    return "ARCProduceObject";
1232  case CK_ARCReclaimReturnedObject:
1233    return "ARCReclaimReturnedObject";
1234  case CK_ARCExtendBlockObject:
1235    return "ARCCExtendBlockObject";
1236  case CK_AtomicToNonAtomic:
1237    return "AtomicToNonAtomic";
1238  case CK_NonAtomicToAtomic:
1239    return "NonAtomicToAtomic";
1240  case CK_CopyAndAutoreleaseBlockObject:
1241    return "CopyAndAutoreleaseBlockObject";
1242  }
1243
1244  llvm_unreachable("Unhandled cast kind!");
1245}
1246
1247Expr *CastExpr::getSubExprAsWritten() {
1248  Expr *SubExpr = 0;
1249  CastExpr *E = this;
1250  do {
1251    SubExpr = E->getSubExpr();
1252
1253    // Skip through reference binding to temporary.
1254    if (MaterializeTemporaryExpr *Materialize
1255                                  = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1256      SubExpr = Materialize->GetTemporaryExpr();
1257
1258    // Skip any temporary bindings; they're implicit.
1259    if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1260      SubExpr = Binder->getSubExpr();
1261
1262    // Conversions by constructor and conversion functions have a
1263    // subexpression describing the call; strip it off.
1264    if (E->getCastKind() == CK_ConstructorConversion)
1265      SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1266    else if (E->getCastKind() == CK_UserDefinedConversion)
1267      SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1268
1269    // If the subexpression we're left with is an implicit cast, look
1270    // through that, too.
1271  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1272
1273  return SubExpr;
1274}
1275
1276CXXBaseSpecifier **CastExpr::path_buffer() {
1277  switch (getStmtClass()) {
1278#define ABSTRACT_STMT(x)
1279#define CASTEXPR(Type, Base) \
1280  case Stmt::Type##Class: \
1281    return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1282#define STMT(Type, Base)
1283#include "clang/AST/StmtNodes.inc"
1284  default:
1285    llvm_unreachable("non-cast expressions not possible here");
1286  }
1287}
1288
1289void CastExpr::setCastPath(const CXXCastPath &Path) {
1290  assert(Path.size() == path_size());
1291  memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1292}
1293
1294ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1295                                           CastKind Kind, Expr *Operand,
1296                                           const CXXCastPath *BasePath,
1297                                           ExprValueKind VK) {
1298  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1299  void *Buffer =
1300    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1301  ImplicitCastExpr *E =
1302    new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1303  if (PathSize) E->setCastPath(*BasePath);
1304  return E;
1305}
1306
1307ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1308                                                unsigned PathSize) {
1309  void *Buffer =
1310    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1311  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1312}
1313
1314
1315CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1316                                       ExprValueKind VK, CastKind K, Expr *Op,
1317                                       const CXXCastPath *BasePath,
1318                                       TypeSourceInfo *WrittenTy,
1319                                       SourceLocation L, SourceLocation R) {
1320  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1321  void *Buffer =
1322    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1323  CStyleCastExpr *E =
1324    new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1325  if (PathSize) E->setCastPath(*BasePath);
1326  return E;
1327}
1328
1329CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1330  void *Buffer =
1331    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1332  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1333}
1334
1335/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1336/// corresponds to, e.g. "<<=".
1337const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1338  switch (Op) {
1339  case BO_PtrMemD:   return ".*";
1340  case BO_PtrMemI:   return "->*";
1341  case BO_Mul:       return "*";
1342  case BO_Div:       return "/";
1343  case BO_Rem:       return "%";
1344  case BO_Add:       return "+";
1345  case BO_Sub:       return "-";
1346  case BO_Shl:       return "<<";
1347  case BO_Shr:       return ">>";
1348  case BO_LT:        return "<";
1349  case BO_GT:        return ">";
1350  case BO_LE:        return "<=";
1351  case BO_GE:        return ">=";
1352  case BO_EQ:        return "==";
1353  case BO_NE:        return "!=";
1354  case BO_And:       return "&";
1355  case BO_Xor:       return "^";
1356  case BO_Or:        return "|";
1357  case BO_LAnd:      return "&&";
1358  case BO_LOr:       return "||";
1359  case BO_Assign:    return "=";
1360  case BO_MulAssign: return "*=";
1361  case BO_DivAssign: return "/=";
1362  case BO_RemAssign: return "%=";
1363  case BO_AddAssign: return "+=";
1364  case BO_SubAssign: return "-=";
1365  case BO_ShlAssign: return "<<=";
1366  case BO_ShrAssign: return ">>=";
1367  case BO_AndAssign: return "&=";
1368  case BO_XorAssign: return "^=";
1369  case BO_OrAssign:  return "|=";
1370  case BO_Comma:     return ",";
1371  }
1372
1373  llvm_unreachable("Invalid OpCode!");
1374}
1375
1376BinaryOperatorKind
1377BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1378  switch (OO) {
1379  default: llvm_unreachable("Not an overloadable binary operator");
1380  case OO_Plus: return BO_Add;
1381  case OO_Minus: return BO_Sub;
1382  case OO_Star: return BO_Mul;
1383  case OO_Slash: return BO_Div;
1384  case OO_Percent: return BO_Rem;
1385  case OO_Caret: return BO_Xor;
1386  case OO_Amp: return BO_And;
1387  case OO_Pipe: return BO_Or;
1388  case OO_Equal: return BO_Assign;
1389  case OO_Less: return BO_LT;
1390  case OO_Greater: return BO_GT;
1391  case OO_PlusEqual: return BO_AddAssign;
1392  case OO_MinusEqual: return BO_SubAssign;
1393  case OO_StarEqual: return BO_MulAssign;
1394  case OO_SlashEqual: return BO_DivAssign;
1395  case OO_PercentEqual: return BO_RemAssign;
1396  case OO_CaretEqual: return BO_XorAssign;
1397  case OO_AmpEqual: return BO_AndAssign;
1398  case OO_PipeEqual: return BO_OrAssign;
1399  case OO_LessLess: return BO_Shl;
1400  case OO_GreaterGreater: return BO_Shr;
1401  case OO_LessLessEqual: return BO_ShlAssign;
1402  case OO_GreaterGreaterEqual: return BO_ShrAssign;
1403  case OO_EqualEqual: return BO_EQ;
1404  case OO_ExclaimEqual: return BO_NE;
1405  case OO_LessEqual: return BO_LE;
1406  case OO_GreaterEqual: return BO_GE;
1407  case OO_AmpAmp: return BO_LAnd;
1408  case OO_PipePipe: return BO_LOr;
1409  case OO_Comma: return BO_Comma;
1410  case OO_ArrowStar: return BO_PtrMemI;
1411  }
1412}
1413
1414OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1415  static const OverloadedOperatorKind OverOps[] = {
1416    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1417    OO_Star, OO_Slash, OO_Percent,
1418    OO_Plus, OO_Minus,
1419    OO_LessLess, OO_GreaterGreater,
1420    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1421    OO_EqualEqual, OO_ExclaimEqual,
1422    OO_Amp,
1423    OO_Caret,
1424    OO_Pipe,
1425    OO_AmpAmp,
1426    OO_PipePipe,
1427    OO_Equal, OO_StarEqual,
1428    OO_SlashEqual, OO_PercentEqual,
1429    OO_PlusEqual, OO_MinusEqual,
1430    OO_LessLessEqual, OO_GreaterGreaterEqual,
1431    OO_AmpEqual, OO_CaretEqual,
1432    OO_PipeEqual,
1433    OO_Comma
1434  };
1435  return OverOps[Opc];
1436}
1437
1438InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1439                           Expr **initExprs, unsigned numInits,
1440                           SourceLocation rbraceloc)
1441  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1442         false, false),
1443    InitExprs(C, numInits),
1444    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0)
1445{
1446  sawArrayRangeDesignator(false);
1447  setInitializesStdInitializerList(false);
1448  for (unsigned I = 0; I != numInits; ++I) {
1449    if (initExprs[I]->isTypeDependent())
1450      ExprBits.TypeDependent = true;
1451    if (initExprs[I]->isValueDependent())
1452      ExprBits.ValueDependent = true;
1453    if (initExprs[I]->isInstantiationDependent())
1454      ExprBits.InstantiationDependent = true;
1455    if (initExprs[I]->containsUnexpandedParameterPack())
1456      ExprBits.ContainsUnexpandedParameterPack = true;
1457  }
1458
1459  InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1460}
1461
1462void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1463  if (NumInits > InitExprs.size())
1464    InitExprs.reserve(C, NumInits);
1465}
1466
1467void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1468  InitExprs.resize(C, NumInits, 0);
1469}
1470
1471Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1472  if (Init >= InitExprs.size()) {
1473    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1474    InitExprs.back() = expr;
1475    return 0;
1476  }
1477
1478  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1479  InitExprs[Init] = expr;
1480  return Result;
1481}
1482
1483void InitListExpr::setArrayFiller(Expr *filler) {
1484  assert(!hasArrayFiller() && "Filler already set!");
1485  ArrayFillerOrUnionFieldInit = filler;
1486  // Fill out any "holes" in the array due to designated initializers.
1487  Expr **inits = getInits();
1488  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1489    if (inits[i] == 0)
1490      inits[i] = filler;
1491}
1492
1493SourceRange InitListExpr::getSourceRange() const {
1494  if (SyntacticForm)
1495    return SyntacticForm->getSourceRange();
1496  SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1497  if (Beg.isInvalid()) {
1498    // Find the first non-null initializer.
1499    for (InitExprsTy::const_iterator I = InitExprs.begin(),
1500                                     E = InitExprs.end();
1501      I != E; ++I) {
1502      if (Stmt *S = *I) {
1503        Beg = S->getLocStart();
1504        break;
1505      }
1506    }
1507  }
1508  if (End.isInvalid()) {
1509    // Find the first non-null initializer from the end.
1510    for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1511                                             E = InitExprs.rend();
1512      I != E; ++I) {
1513      if (Stmt *S = *I) {
1514        End = S->getSourceRange().getEnd();
1515        break;
1516      }
1517    }
1518  }
1519  return SourceRange(Beg, End);
1520}
1521
1522/// getFunctionType - Return the underlying function type for this block.
1523///
1524const FunctionProtoType *BlockExpr::getFunctionType() const {
1525  // The block pointer is never sugared, but the function type might be.
1526  return cast<BlockPointerType>(getType())
1527           ->getPointeeType()->castAs<FunctionProtoType>();
1528}
1529
1530SourceLocation BlockExpr::getCaretLocation() const {
1531  return TheBlock->getCaretLocation();
1532}
1533const Stmt *BlockExpr::getBody() const {
1534  return TheBlock->getBody();
1535}
1536Stmt *BlockExpr::getBody() {
1537  return TheBlock->getBody();
1538}
1539
1540
1541//===----------------------------------------------------------------------===//
1542// Generic Expression Routines
1543//===----------------------------------------------------------------------===//
1544
1545/// isUnusedResultAWarning - Return true if this immediate expression should
1546/// be warned about if the result is unused.  If so, fill in Loc and Ranges
1547/// with location to warn on and the source range[s] to report with the
1548/// warning.
1549bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1550                                  SourceRange &R2, ASTContext &Ctx) const {
1551  // Don't warn if the expr is type dependent. The type could end up
1552  // instantiating to void.
1553  if (isTypeDependent())
1554    return false;
1555
1556  switch (getStmtClass()) {
1557  default:
1558    if (getType()->isVoidType())
1559      return false;
1560    Loc = getExprLoc();
1561    R1 = getSourceRange();
1562    return true;
1563  case ParenExprClass:
1564    return cast<ParenExpr>(this)->getSubExpr()->
1565      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1566  case GenericSelectionExprClass:
1567    return cast<GenericSelectionExpr>(this)->getResultExpr()->
1568      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1569  case UnaryOperatorClass: {
1570    const UnaryOperator *UO = cast<UnaryOperator>(this);
1571
1572    switch (UO->getOpcode()) {
1573    default: break;
1574    case UO_PostInc:
1575    case UO_PostDec:
1576    case UO_PreInc:
1577    case UO_PreDec:                 // ++/--
1578      return false;  // Not a warning.
1579    case UO_Deref:
1580      // Dereferencing a volatile pointer is a side-effect.
1581      if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1582        return false;
1583      break;
1584    case UO_Real:
1585    case UO_Imag:
1586      // accessing a piece of a volatile complex is a side-effect.
1587      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1588          .isVolatileQualified())
1589        return false;
1590      break;
1591    case UO_Extension:
1592      return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1593    }
1594    Loc = UO->getOperatorLoc();
1595    R1 = UO->getSubExpr()->getSourceRange();
1596    return true;
1597  }
1598  case BinaryOperatorClass: {
1599    const BinaryOperator *BO = cast<BinaryOperator>(this);
1600    switch (BO->getOpcode()) {
1601      default:
1602        break;
1603      // Consider the RHS of comma for side effects. LHS was checked by
1604      // Sema::CheckCommaOperands.
1605      case BO_Comma:
1606        // ((foo = <blah>), 0) is an idiom for hiding the result (and
1607        // lvalue-ness) of an assignment written in a macro.
1608        if (IntegerLiteral *IE =
1609              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1610          if (IE->getValue() == 0)
1611            return false;
1612        return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1613      // Consider '||', '&&' to have side effects if the LHS or RHS does.
1614      case BO_LAnd:
1615      case BO_LOr:
1616        if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1617            !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1618          return false;
1619        break;
1620    }
1621    if (BO->isAssignmentOp())
1622      return false;
1623    Loc = BO->getOperatorLoc();
1624    R1 = BO->getLHS()->getSourceRange();
1625    R2 = BO->getRHS()->getSourceRange();
1626    return true;
1627  }
1628  case CompoundAssignOperatorClass:
1629  case VAArgExprClass:
1630  case AtomicExprClass:
1631    return false;
1632
1633  case ConditionalOperatorClass: {
1634    // If only one of the LHS or RHS is a warning, the operator might
1635    // be being used for control flow. Only warn if both the LHS and
1636    // RHS are warnings.
1637    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1638    if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1639      return false;
1640    if (!Exp->getLHS())
1641      return true;
1642    return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1643  }
1644
1645  case MemberExprClass:
1646    // If the base pointer or element is to a volatile pointer/field, accessing
1647    // it is a side effect.
1648    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1649      return false;
1650    Loc = cast<MemberExpr>(this)->getMemberLoc();
1651    R1 = SourceRange(Loc, Loc);
1652    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1653    return true;
1654
1655  case ArraySubscriptExprClass:
1656    // If the base pointer or element is to a volatile pointer/field, accessing
1657    // it is a side effect.
1658    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1659      return false;
1660    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1661    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1662    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1663    return true;
1664
1665  case CXXOperatorCallExprClass: {
1666    // We warn about operator== and operator!= even when user-defined operator
1667    // overloads as there is no reasonable way to define these such that they
1668    // have non-trivial, desirable side-effects. See the -Wunused-comparison
1669    // warning: these operators are commonly typo'ed, and so warning on them
1670    // provides additional value as well. If this list is updated,
1671    // DiagnoseUnusedComparison should be as well.
1672    const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
1673    if (Op->getOperator() == OO_EqualEqual ||
1674        Op->getOperator() == OO_ExclaimEqual) {
1675      Loc = Op->getOperatorLoc();
1676      R1 = Op->getSourceRange();
1677      return true;
1678    }
1679
1680    // Fallthrough for generic call handling.
1681  }
1682  case CallExprClass:
1683  case CXXMemberCallExprClass: {
1684    // If this is a direct call, get the callee.
1685    const CallExpr *CE = cast<CallExpr>(this);
1686    if (const Decl *FD = CE->getCalleeDecl()) {
1687      // If the callee has attribute pure, const, or warn_unused_result, warn
1688      // about it. void foo() { strlen("bar"); } should warn.
1689      //
1690      // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1691      // updated to match for QoI.
1692      if (FD->getAttr<WarnUnusedResultAttr>() ||
1693          FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1694        Loc = CE->getCallee()->getLocStart();
1695        R1 = CE->getCallee()->getSourceRange();
1696
1697        if (unsigned NumArgs = CE->getNumArgs())
1698          R2 = SourceRange(CE->getArg(0)->getLocStart(),
1699                           CE->getArg(NumArgs-1)->getLocEnd());
1700        return true;
1701      }
1702    }
1703    return false;
1704  }
1705
1706  case CXXTemporaryObjectExprClass:
1707  case CXXConstructExprClass:
1708    return false;
1709
1710  case ObjCMessageExprClass: {
1711    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1712    if (Ctx.getLangOptions().ObjCAutoRefCount &&
1713        ME->isInstanceMessage() &&
1714        !ME->getType()->isVoidType() &&
1715        ME->getSelector().getIdentifierInfoForSlot(0) &&
1716        ME->getSelector().getIdentifierInfoForSlot(0)
1717                                               ->getName().startswith("init")) {
1718      Loc = getExprLoc();
1719      R1 = ME->getSourceRange();
1720      return true;
1721    }
1722
1723    const ObjCMethodDecl *MD = ME->getMethodDecl();
1724    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1725      Loc = getExprLoc();
1726      return true;
1727    }
1728    return false;
1729  }
1730
1731  case ObjCPropertyRefExprClass:
1732    Loc = getExprLoc();
1733    R1 = getSourceRange();
1734    return true;
1735
1736  case PseudoObjectExprClass: {
1737    const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
1738
1739    // Only complain about things that have the form of a getter.
1740    if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
1741        isa<BinaryOperator>(PO->getSyntacticForm()))
1742      return false;
1743
1744    Loc = getExprLoc();
1745    R1 = getSourceRange();
1746    return true;
1747  }
1748
1749  case StmtExprClass: {
1750    // Statement exprs don't logically have side effects themselves, but are
1751    // sometimes used in macros in ways that give them a type that is unused.
1752    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1753    // however, if the result of the stmt expr is dead, we don't want to emit a
1754    // warning.
1755    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1756    if (!CS->body_empty()) {
1757      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1758        return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1759      if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1760        if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1761          return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1762    }
1763
1764    if (getType()->isVoidType())
1765      return false;
1766    Loc = cast<StmtExpr>(this)->getLParenLoc();
1767    R1 = getSourceRange();
1768    return true;
1769  }
1770  case CStyleCastExprClass:
1771    // If this is an explicit cast to void, allow it.  People do this when they
1772    // think they know what they're doing :).
1773    if (getType()->isVoidType())
1774      return false;
1775    Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1776    R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1777    return true;
1778  case CXXFunctionalCastExprClass: {
1779    if (getType()->isVoidType())
1780      return false;
1781    const CastExpr *CE = cast<CastExpr>(this);
1782
1783    // If this is a cast to void or a constructor conversion, check the operand.
1784    // Otherwise, the result of the cast is unused.
1785    if (CE->getCastKind() == CK_ToVoid ||
1786        CE->getCastKind() == CK_ConstructorConversion)
1787      return (cast<CastExpr>(this)->getSubExpr()
1788              ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1789    Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1790    R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1791    return true;
1792  }
1793
1794  case ImplicitCastExprClass:
1795    // Check the operand, since implicit casts are inserted by Sema
1796    return (cast<ImplicitCastExpr>(this)
1797            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1798
1799  case CXXDefaultArgExprClass:
1800    return (cast<CXXDefaultArgExpr>(this)
1801            ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1802
1803  case CXXNewExprClass:
1804    // FIXME: In theory, there might be new expressions that don't have side
1805    // effects (e.g. a placement new with an uninitialized POD).
1806  case CXXDeleteExprClass:
1807    return false;
1808  case CXXBindTemporaryExprClass:
1809    return (cast<CXXBindTemporaryExpr>(this)
1810            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1811  case ExprWithCleanupsClass:
1812    return (cast<ExprWithCleanups>(this)
1813            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1814  }
1815}
1816
1817/// isOBJCGCCandidate - Check if an expression is objc gc'able.
1818/// returns true, if it is; false otherwise.
1819bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1820  const Expr *E = IgnoreParens();
1821  switch (E->getStmtClass()) {
1822  default:
1823    return false;
1824  case ObjCIvarRefExprClass:
1825    return true;
1826  case Expr::UnaryOperatorClass:
1827    return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1828  case ImplicitCastExprClass:
1829    return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1830  case MaterializeTemporaryExprClass:
1831    return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
1832                                                      ->isOBJCGCCandidate(Ctx);
1833  case CStyleCastExprClass:
1834    return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1835  case BlockDeclRefExprClass:
1836  case DeclRefExprClass: {
1837
1838    const Decl *D;
1839    if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E))
1840        D = BDRE->getDecl();
1841    else
1842        D = cast<DeclRefExpr>(E)->getDecl();
1843
1844    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1845      if (VD->hasGlobalStorage())
1846        return true;
1847      QualType T = VD->getType();
1848      // dereferencing to a  pointer is always a gc'able candidate,
1849      // unless it is __weak.
1850      return T->isPointerType() &&
1851             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1852    }
1853    return false;
1854  }
1855  case MemberExprClass: {
1856    const MemberExpr *M = cast<MemberExpr>(E);
1857    return M->getBase()->isOBJCGCCandidate(Ctx);
1858  }
1859  case ArraySubscriptExprClass:
1860    return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
1861  }
1862}
1863
1864bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1865  if (isTypeDependent())
1866    return false;
1867  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
1868}
1869
1870QualType Expr::findBoundMemberType(const Expr *expr) {
1871  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
1872
1873  // Bound member expressions are always one of these possibilities:
1874  //   x->m      x.m      x->*y      x.*y
1875  // (possibly parenthesized)
1876
1877  expr = expr->IgnoreParens();
1878  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
1879    assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
1880    return mem->getMemberDecl()->getType();
1881  }
1882
1883  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
1884    QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
1885                      ->getPointeeType();
1886    assert(type->isFunctionType());
1887    return type;
1888  }
1889
1890  assert(isa<UnresolvedMemberExpr>(expr));
1891  return QualType();
1892}
1893
1894static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1895                                          Expr::CanThrowResult CT2) {
1896  // CanThrowResult constants are ordered so that the maximum is the correct
1897  // merge result.
1898  return CT1 > CT2 ? CT1 : CT2;
1899}
1900
1901static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1902  Expr *E = const_cast<Expr*>(CE);
1903  Expr::CanThrowResult R = Expr::CT_Cannot;
1904  for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
1905    R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1906  }
1907  return R;
1908}
1909
1910static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E,
1911                                           const Decl *D,
1912                                           bool NullThrows = true) {
1913  if (!D)
1914    return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1915
1916  // See if we can get a function type from the decl somehow.
1917  const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1918  if (!VD) // If we have no clue what we're calling, assume the worst.
1919    return Expr::CT_Can;
1920
1921  // As an extension, we assume that __attribute__((nothrow)) functions don't
1922  // throw.
1923  if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1924    return Expr::CT_Cannot;
1925
1926  QualType T = VD->getType();
1927  const FunctionProtoType *FT;
1928  if ((FT = T->getAs<FunctionProtoType>())) {
1929  } else if (const PointerType *PT = T->getAs<PointerType>())
1930    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1931  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1932    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1933  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1934    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1935  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1936    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1937
1938  if (!FT)
1939    return Expr::CT_Can;
1940
1941  if (FT->getExceptionSpecType() == EST_Delayed) {
1942    assert(isa<CXXConstructorDecl>(D) &&
1943           "only constructor exception specs can be unknown");
1944    Ctx.getDiagnostics().Report(E->getLocStart(),
1945                                diag::err_exception_spec_unknown)
1946      << E->getSourceRange();
1947    return Expr::CT_Can;
1948  }
1949
1950  return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can;
1951}
1952
1953static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1954  if (DC->isTypeDependent())
1955    return Expr::CT_Dependent;
1956
1957  if (!DC->getTypeAsWritten()->isReferenceType())
1958    return Expr::CT_Cannot;
1959
1960  if (DC->getSubExpr()->isTypeDependent())
1961    return Expr::CT_Dependent;
1962
1963  return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1964}
1965
1966static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1967                                           const CXXTypeidExpr *DC) {
1968  if (DC->isTypeOperand())
1969    return Expr::CT_Cannot;
1970
1971  Expr *Op = DC->getExprOperand();
1972  if (Op->isTypeDependent())
1973    return Expr::CT_Dependent;
1974
1975  const RecordType *RT = Op->getType()->getAs<RecordType>();
1976  if (!RT)
1977    return Expr::CT_Cannot;
1978
1979  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1980    return Expr::CT_Cannot;
1981
1982  if (Op->Classify(C).isPRValue())
1983    return Expr::CT_Cannot;
1984
1985  return Expr::CT_Can;
1986}
1987
1988Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1989  // C++ [expr.unary.noexcept]p3:
1990  //   [Can throw] if in a potentially-evaluated context the expression would
1991  //   contain:
1992  switch (getStmtClass()) {
1993  case CXXThrowExprClass:
1994    //   - a potentially evaluated throw-expression
1995    return CT_Can;
1996
1997  case CXXDynamicCastExprClass: {
1998    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1999    //     where T is a reference type, that requires a run-time check
2000    CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
2001    if (CT == CT_Can)
2002      return CT;
2003    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2004  }
2005
2006  case CXXTypeidExprClass:
2007    //   - a potentially evaluated typeid expression applied to a glvalue
2008    //     expression whose type is a polymorphic class type
2009    return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
2010
2011    //   - a potentially evaluated call to a function, member function, function
2012    //     pointer, or member function pointer that does not have a non-throwing
2013    //     exception-specification
2014  case CallExprClass:
2015  case CXXMemberCallExprClass:
2016  case CXXOperatorCallExprClass: {
2017    const CallExpr *CE = cast<CallExpr>(this);
2018    CanThrowResult CT;
2019    if (isTypeDependent())
2020      CT = CT_Dependent;
2021    else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
2022      CT = CT_Cannot;
2023    else
2024      CT = CanCalleeThrow(C, this, CE->getCalleeDecl());
2025    if (CT == CT_Can)
2026      return CT;
2027    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2028  }
2029
2030  case CXXConstructExprClass:
2031  case CXXTemporaryObjectExprClass: {
2032    CanThrowResult CT = CanCalleeThrow(C, this,
2033        cast<CXXConstructExpr>(this)->getConstructor());
2034    if (CT == CT_Can)
2035      return CT;
2036    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2037  }
2038
2039  case LambdaExprClass: {
2040    const LambdaExpr *Lambda = cast<LambdaExpr>(this);
2041    CanThrowResult CT = Expr::CT_Cannot;
2042    for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
2043                                        CapEnd = Lambda->capture_init_end();
2044         Cap != CapEnd; ++Cap)
2045      CT = MergeCanThrow(CT, (*Cap)->CanThrow(C));
2046    return CT;
2047  }
2048
2049  case CXXNewExprClass: {
2050    CanThrowResult CT;
2051    if (isTypeDependent())
2052      CT = CT_Dependent;
2053    else
2054      CT = CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew());
2055    if (CT == CT_Can)
2056      return CT;
2057    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2058  }
2059
2060  case CXXDeleteExprClass: {
2061    CanThrowResult CT;
2062    QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType();
2063    if (DTy.isNull() || DTy->isDependentType()) {
2064      CT = CT_Dependent;
2065    } else {
2066      CT = CanCalleeThrow(C, this,
2067                          cast<CXXDeleteExpr>(this)->getOperatorDelete());
2068      if (const RecordType *RT = DTy->getAs<RecordType>()) {
2069        const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2070        CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor()));
2071      }
2072      if (CT == CT_Can)
2073        return CT;
2074    }
2075    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2076  }
2077
2078  case CXXBindTemporaryExprClass: {
2079    // The bound temporary has to be destroyed again, which might throw.
2080    CanThrowResult CT = CanCalleeThrow(C, this,
2081      cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
2082    if (CT == CT_Can)
2083      return CT;
2084    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2085  }
2086
2087    // ObjC message sends are like function calls, but never have exception
2088    // specs.
2089  case ObjCMessageExprClass:
2090  case ObjCPropertyRefExprClass:
2091    return CT_Can;
2092
2093    // Many other things have subexpressions, so we have to test those.
2094    // Some are simple:
2095  case ConditionalOperatorClass:
2096  case CompoundLiteralExprClass:
2097  case CXXConstCastExprClass:
2098  case CXXDefaultArgExprClass:
2099  case CXXReinterpretCastExprClass:
2100  case DesignatedInitExprClass:
2101  case ExprWithCleanupsClass:
2102  case ExtVectorElementExprClass:
2103  case InitListExprClass:
2104  case MemberExprClass:
2105  case ObjCIsaExprClass:
2106  case ObjCIvarRefExprClass:
2107  case ParenExprClass:
2108  case ParenListExprClass:
2109  case ShuffleVectorExprClass:
2110  case VAArgExprClass:
2111    return CanSubExprsThrow(C, this);
2112
2113    // Some might be dependent for other reasons.
2114  case ArraySubscriptExprClass:
2115  case BinaryOperatorClass:
2116  case CompoundAssignOperatorClass:
2117  case CStyleCastExprClass:
2118  case CXXStaticCastExprClass:
2119  case CXXFunctionalCastExprClass:
2120  case ImplicitCastExprClass:
2121  case MaterializeTemporaryExprClass:
2122  case UnaryOperatorClass: {
2123    CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
2124    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2125  }
2126
2127    // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
2128  case StmtExprClass:
2129    return CT_Can;
2130
2131  case ChooseExprClass:
2132    if (isTypeDependent() || isValueDependent())
2133      return CT_Dependent;
2134    return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
2135
2136  case GenericSelectionExprClass:
2137    if (cast<GenericSelectionExpr>(this)->isResultDependent())
2138      return CT_Dependent;
2139    return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
2140
2141    // Some expressions are always dependent.
2142  case CXXDependentScopeMemberExprClass:
2143  case CXXUnresolvedConstructExprClass:
2144  case DependentScopeDeclRefExprClass:
2145    return CT_Dependent;
2146
2147  case AtomicExprClass:
2148  case AsTypeExprClass:
2149  case BinaryConditionalOperatorClass:
2150  case BlockExprClass:
2151  case BlockDeclRefExprClass:
2152  case CUDAKernelCallExprClass:
2153  case DeclRefExprClass:
2154  case ObjCBridgedCastExprClass:
2155  case ObjCIndirectCopyRestoreExprClass:
2156  case ObjCProtocolExprClass:
2157  case ObjCSelectorExprClass:
2158  case OffsetOfExprClass:
2159  case PackExpansionExprClass:
2160  case PseudoObjectExprClass:
2161  case SubstNonTypeTemplateParmExprClass:
2162  case SubstNonTypeTemplateParmPackExprClass:
2163  case UnaryExprOrTypeTraitExprClass:
2164  case UnresolvedLookupExprClass:
2165  case UnresolvedMemberExprClass:
2166    // FIXME: Can any of the above throw?  If so, when?
2167    return CT_Cannot;
2168
2169  case AddrLabelExprClass:
2170  case ArrayTypeTraitExprClass:
2171  case BinaryTypeTraitExprClass:
2172  case CXXBoolLiteralExprClass:
2173  case CXXNoexceptExprClass:
2174  case CXXNullPtrLiteralExprClass:
2175  case CXXPseudoDestructorExprClass:
2176  case CXXScalarValueInitExprClass:
2177  case CXXThisExprClass:
2178  case CXXUuidofExprClass:
2179  case CharacterLiteralClass:
2180  case ExpressionTraitExprClass:
2181  case FloatingLiteralClass:
2182  case GNUNullExprClass:
2183  case ImaginaryLiteralClass:
2184  case ImplicitValueInitExprClass:
2185  case IntegerLiteralClass:
2186  case ObjCEncodeExprClass:
2187  case ObjCStringLiteralClass:
2188  case OpaqueValueExprClass:
2189  case PredefinedExprClass:
2190  case SizeOfPackExprClass:
2191  case StringLiteralClass:
2192  case UnaryTypeTraitExprClass:
2193    // These expressions can never throw.
2194    return CT_Cannot;
2195
2196#define STMT(CLASS, PARENT) case CLASS##Class:
2197#define STMT_RANGE(Base, First, Last)
2198#define LAST_STMT_RANGE(BASE, FIRST, LAST)
2199#define EXPR(CLASS, PARENT)
2200#define ABSTRACT_STMT(STMT)
2201#include "clang/AST/StmtNodes.inc"
2202  case NoStmtClass:
2203    llvm_unreachable("Invalid class for expression");
2204  }
2205  llvm_unreachable("Bogus StmtClass");
2206}
2207
2208Expr* Expr::IgnoreParens() {
2209  Expr* E = this;
2210  while (true) {
2211    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2212      E = P->getSubExpr();
2213      continue;
2214    }
2215    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2216      if (P->getOpcode() == UO_Extension) {
2217        E = P->getSubExpr();
2218        continue;
2219      }
2220    }
2221    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2222      if (!P->isResultDependent()) {
2223        E = P->getResultExpr();
2224        continue;
2225      }
2226    }
2227    return E;
2228  }
2229}
2230
2231/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
2232/// or CastExprs or ImplicitCastExprs, returning their operand.
2233Expr *Expr::IgnoreParenCasts() {
2234  Expr *E = this;
2235  while (true) {
2236    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2237      E = P->getSubExpr();
2238      continue;
2239    }
2240    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2241      E = P->getSubExpr();
2242      continue;
2243    }
2244    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2245      if (P->getOpcode() == UO_Extension) {
2246        E = P->getSubExpr();
2247        continue;
2248      }
2249    }
2250    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2251      if (!P->isResultDependent()) {
2252        E = P->getResultExpr();
2253        continue;
2254      }
2255    }
2256    if (MaterializeTemporaryExpr *Materialize
2257                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2258      E = Materialize->GetTemporaryExpr();
2259      continue;
2260    }
2261    if (SubstNonTypeTemplateParmExpr *NTTP
2262                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2263      E = NTTP->getReplacement();
2264      continue;
2265    }
2266    return E;
2267  }
2268}
2269
2270/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2271/// casts.  This is intended purely as a temporary workaround for code
2272/// that hasn't yet been rewritten to do the right thing about those
2273/// casts, and may disappear along with the last internal use.
2274Expr *Expr::IgnoreParenLValueCasts() {
2275  Expr *E = this;
2276  while (true) {
2277    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2278      E = P->getSubExpr();
2279      continue;
2280    } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2281      if (P->getCastKind() == CK_LValueToRValue) {
2282        E = P->getSubExpr();
2283        continue;
2284      }
2285    } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2286      if (P->getOpcode() == UO_Extension) {
2287        E = P->getSubExpr();
2288        continue;
2289      }
2290    } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2291      if (!P->isResultDependent()) {
2292        E = P->getResultExpr();
2293        continue;
2294      }
2295    } else if (MaterializeTemporaryExpr *Materialize
2296                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2297      E = Materialize->GetTemporaryExpr();
2298      continue;
2299    } else if (SubstNonTypeTemplateParmExpr *NTTP
2300                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2301      E = NTTP->getReplacement();
2302      continue;
2303    }
2304    break;
2305  }
2306  return E;
2307}
2308
2309Expr *Expr::IgnoreParenImpCasts() {
2310  Expr *E = this;
2311  while (true) {
2312    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2313      E = P->getSubExpr();
2314      continue;
2315    }
2316    if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2317      E = P->getSubExpr();
2318      continue;
2319    }
2320    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2321      if (P->getOpcode() == UO_Extension) {
2322        E = P->getSubExpr();
2323        continue;
2324      }
2325    }
2326    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2327      if (!P->isResultDependent()) {
2328        E = P->getResultExpr();
2329        continue;
2330      }
2331    }
2332    if (MaterializeTemporaryExpr *Materialize
2333                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2334      E = Materialize->GetTemporaryExpr();
2335      continue;
2336    }
2337    if (SubstNonTypeTemplateParmExpr *NTTP
2338                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2339      E = NTTP->getReplacement();
2340      continue;
2341    }
2342    return E;
2343  }
2344}
2345
2346Expr *Expr::IgnoreConversionOperator() {
2347  if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2348    if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2349      return MCE->getImplicitObjectArgument();
2350  }
2351  return this;
2352}
2353
2354/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2355/// value (including ptr->int casts of the same size).  Strip off any
2356/// ParenExpr or CastExprs, returning their operand.
2357Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2358  Expr *E = this;
2359  while (true) {
2360    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2361      E = P->getSubExpr();
2362      continue;
2363    }
2364
2365    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2366      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2367      // ptr<->int casts of the same width.  We also ignore all identity casts.
2368      Expr *SE = P->getSubExpr();
2369
2370      if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2371        E = SE;
2372        continue;
2373      }
2374
2375      if ((E->getType()->isPointerType() ||
2376           E->getType()->isIntegralType(Ctx)) &&
2377          (SE->getType()->isPointerType() ||
2378           SE->getType()->isIntegralType(Ctx)) &&
2379          Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2380        E = SE;
2381        continue;
2382      }
2383    }
2384
2385    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2386      if (P->getOpcode() == UO_Extension) {
2387        E = P->getSubExpr();
2388        continue;
2389      }
2390    }
2391
2392    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2393      if (!P->isResultDependent()) {
2394        E = P->getResultExpr();
2395        continue;
2396      }
2397    }
2398
2399    if (SubstNonTypeTemplateParmExpr *NTTP
2400                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2401      E = NTTP->getReplacement();
2402      continue;
2403    }
2404
2405    return E;
2406  }
2407}
2408
2409bool Expr::isDefaultArgument() const {
2410  const Expr *E = this;
2411  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2412    E = M->GetTemporaryExpr();
2413
2414  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2415    E = ICE->getSubExprAsWritten();
2416
2417  return isa<CXXDefaultArgExpr>(E);
2418}
2419
2420/// \brief Skip over any no-op casts and any temporary-binding
2421/// expressions.
2422static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2423  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2424    E = M->GetTemporaryExpr();
2425
2426  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2427    if (ICE->getCastKind() == CK_NoOp)
2428      E = ICE->getSubExpr();
2429    else
2430      break;
2431  }
2432
2433  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2434    E = BE->getSubExpr();
2435
2436  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2437    if (ICE->getCastKind() == CK_NoOp)
2438      E = ICE->getSubExpr();
2439    else
2440      break;
2441  }
2442
2443  return E->IgnoreParens();
2444}
2445
2446/// isTemporaryObject - Determines if this expression produces a
2447/// temporary of the given class type.
2448bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2449  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2450    return false;
2451
2452  const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2453
2454  // Temporaries are by definition pr-values of class type.
2455  if (!E->Classify(C).isPRValue()) {
2456    // In this context, property reference is a message call and is pr-value.
2457    if (!isa<ObjCPropertyRefExpr>(E))
2458      return false;
2459  }
2460
2461  // Black-list a few cases which yield pr-values of class type that don't
2462  // refer to temporaries of that type:
2463
2464  // - implicit derived-to-base conversions
2465  if (isa<ImplicitCastExpr>(E)) {
2466    switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2467    case CK_DerivedToBase:
2468    case CK_UncheckedDerivedToBase:
2469      return false;
2470    default:
2471      break;
2472    }
2473  }
2474
2475  // - member expressions (all)
2476  if (isa<MemberExpr>(E))
2477    return false;
2478
2479  // - opaque values (all)
2480  if (isa<OpaqueValueExpr>(E))
2481    return false;
2482
2483  return true;
2484}
2485
2486bool Expr::isImplicitCXXThis() const {
2487  const Expr *E = this;
2488
2489  // Strip away parentheses and casts we don't care about.
2490  while (true) {
2491    if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2492      E = Paren->getSubExpr();
2493      continue;
2494    }
2495
2496    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2497      if (ICE->getCastKind() == CK_NoOp ||
2498          ICE->getCastKind() == CK_LValueToRValue ||
2499          ICE->getCastKind() == CK_DerivedToBase ||
2500          ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2501        E = ICE->getSubExpr();
2502        continue;
2503      }
2504    }
2505
2506    if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2507      if (UnOp->getOpcode() == UO_Extension) {
2508        E = UnOp->getSubExpr();
2509        continue;
2510      }
2511    }
2512
2513    if (const MaterializeTemporaryExpr *M
2514                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2515      E = M->GetTemporaryExpr();
2516      continue;
2517    }
2518
2519    break;
2520  }
2521
2522  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2523    return This->isImplicit();
2524
2525  return false;
2526}
2527
2528/// hasAnyTypeDependentArguments - Determines if any of the expressions
2529/// in Exprs is type-dependent.
2530bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2531  for (unsigned I = 0; I < NumExprs; ++I)
2532    if (Exprs[I]->isTypeDependent())
2533      return true;
2534
2535  return false;
2536}
2537
2538/// hasAnyValueDependentArguments - Determines if any of the expressions
2539/// in Exprs is value-dependent.
2540bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2541  for (unsigned I = 0; I < NumExprs; ++I)
2542    if (Exprs[I]->isValueDependent())
2543      return true;
2544
2545  return false;
2546}
2547
2548bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2549  // This function is attempting whether an expression is an initializer
2550  // which can be evaluated at compile-time.  isEvaluatable handles most
2551  // of the cases, but it can't deal with some initializer-specific
2552  // expressions, and it can't deal with aggregates; we deal with those here,
2553  // and fall back to isEvaluatable for the other cases.
2554
2555  // If we ever capture reference-binding directly in the AST, we can
2556  // kill the second parameter.
2557
2558  if (IsForRef) {
2559    EvalResult Result;
2560    return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2561  }
2562
2563  switch (getStmtClass()) {
2564  default: break;
2565  case IntegerLiteralClass:
2566  case FloatingLiteralClass:
2567  case StringLiteralClass:
2568  case ObjCStringLiteralClass:
2569  case ObjCEncodeExprClass:
2570    return true;
2571  case CXXTemporaryObjectExprClass:
2572  case CXXConstructExprClass: {
2573    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2574
2575    // Only if it's
2576    if (CE->getConstructor()->isTrivial()) {
2577      // 1) an application of the trivial default constructor or
2578      if (!CE->getNumArgs()) return true;
2579
2580      // 2) an elidable trivial copy construction of an operand which is
2581      //    itself a constant initializer.  Note that we consider the
2582      //    operand on its own, *not* as a reference binding.
2583      if (CE->isElidable() &&
2584          CE->getArg(0)->isConstantInitializer(Ctx, false))
2585        return true;
2586    }
2587
2588    // 3) a foldable constexpr constructor.
2589    break;
2590  }
2591  case CompoundLiteralExprClass: {
2592    // This handles gcc's extension that allows global initializers like
2593    // "struct x {int x;} x = (struct x) {};".
2594    // FIXME: This accepts other cases it shouldn't!
2595    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2596    return Exp->isConstantInitializer(Ctx, false);
2597  }
2598  case InitListExprClass: {
2599    // FIXME: This doesn't deal with fields with reference types correctly.
2600    // FIXME: This incorrectly allows pointers cast to integers to be assigned
2601    // to bitfields.
2602    const InitListExpr *Exp = cast<InitListExpr>(this);
2603    unsigned numInits = Exp->getNumInits();
2604    for (unsigned i = 0; i < numInits; i++) {
2605      if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2606        return false;
2607    }
2608    return true;
2609  }
2610  case ImplicitValueInitExprClass:
2611    return true;
2612  case ParenExprClass:
2613    return cast<ParenExpr>(this)->getSubExpr()
2614      ->isConstantInitializer(Ctx, IsForRef);
2615  case GenericSelectionExprClass:
2616    if (cast<GenericSelectionExpr>(this)->isResultDependent())
2617      return false;
2618    return cast<GenericSelectionExpr>(this)->getResultExpr()
2619      ->isConstantInitializer(Ctx, IsForRef);
2620  case ChooseExprClass:
2621    return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2622      ->isConstantInitializer(Ctx, IsForRef);
2623  case UnaryOperatorClass: {
2624    const UnaryOperator* Exp = cast<UnaryOperator>(this);
2625    if (Exp->getOpcode() == UO_Extension)
2626      return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2627    break;
2628  }
2629  case CXXFunctionalCastExprClass:
2630  case CXXStaticCastExprClass:
2631  case ImplicitCastExprClass:
2632  case CStyleCastExprClass: {
2633    const CastExpr *CE = cast<CastExpr>(this);
2634
2635    // If we're promoting an integer to an _Atomic type then this is constant
2636    // if the integer is constant.  We also need to check the converse in case
2637    // someone does something like:
2638    //
2639    // int a = (_Atomic(int))42;
2640    //
2641    // I doubt anyone would write code like this directly, but it's quite
2642    // possible as the result of macro expansions.
2643    if (CE->getCastKind() == CK_NonAtomicToAtomic ||
2644        CE->getCastKind() == CK_AtomicToNonAtomic)
2645      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2646
2647    // Handle bitcasts of vector constants.
2648    if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast)
2649      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2650
2651    // Handle misc casts we want to ignore.
2652    // FIXME: Is it really safe to ignore all these?
2653    if (CE->getCastKind() == CK_NoOp ||
2654        CE->getCastKind() == CK_LValueToRValue ||
2655        CE->getCastKind() == CK_ToUnion ||
2656        CE->getCastKind() == CK_ConstructorConversion)
2657      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2658
2659    break;
2660  }
2661  case MaterializeTemporaryExprClass:
2662    return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2663                                            ->isConstantInitializer(Ctx, false);
2664  }
2665  return isEvaluatable(Ctx);
2666}
2667
2668namespace {
2669  /// \brief Look for a call to a non-trivial function within an expression.
2670  class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder>
2671  {
2672    typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
2673
2674    bool NonTrivial;
2675
2676  public:
2677    explicit NonTrivialCallFinder(ASTContext &Context)
2678    : EvaluatedExprVisitor(Context), NonTrivial(false) { }
2679
2680    bool hasNonTrivialCall() const { return NonTrivial; }
2681
2682    void VisitCallExpr(CallExpr *E) {
2683      if (CXXMethodDecl *Method
2684          = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
2685        if (Method->isTrivial()) {
2686          // Recurse to children of the call.
2687          Inherited::VisitStmt(E);
2688          return;
2689        }
2690      }
2691
2692      NonTrivial = true;
2693    }
2694
2695    void VisitCXXConstructExpr(CXXConstructExpr *E) {
2696      if (E->getConstructor()->isTrivial()) {
2697        // Recurse to children of the call.
2698        Inherited::VisitStmt(E);
2699        return;
2700      }
2701
2702      NonTrivial = true;
2703    }
2704
2705    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2706      if (E->getTemporary()->getDestructor()->isTrivial()) {
2707        Inherited::VisitStmt(E);
2708        return;
2709      }
2710
2711      NonTrivial = true;
2712    }
2713  };
2714}
2715
2716bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
2717  NonTrivialCallFinder Finder(Ctx);
2718  Finder.Visit(this);
2719  return Finder.hasNonTrivialCall();
2720}
2721
2722/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2723/// pointer constant or not, as well as the specific kind of constant detected.
2724/// Null pointer constants can be integer constant expressions with the
2725/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2726/// (a GNU extension).
2727Expr::NullPointerConstantKind
2728Expr::isNullPointerConstant(ASTContext &Ctx,
2729                            NullPointerConstantValueDependence NPC) const {
2730  if (isValueDependent()) {
2731    switch (NPC) {
2732    case NPC_NeverValueDependent:
2733      llvm_unreachable("Unexpected value dependent expression!");
2734    case NPC_ValueDependentIsNull:
2735      if (isTypeDependent() || getType()->isIntegralType(Ctx))
2736        return NPCK_ZeroInteger;
2737      else
2738        return NPCK_NotNull;
2739
2740    case NPC_ValueDependentIsNotNull:
2741      return NPCK_NotNull;
2742    }
2743  }
2744
2745  // Strip off a cast to void*, if it exists. Except in C++.
2746  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2747    if (!Ctx.getLangOptions().CPlusPlus) {
2748      // Check that it is a cast to void*.
2749      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2750        QualType Pointee = PT->getPointeeType();
2751        if (!Pointee.hasQualifiers() &&
2752            Pointee->isVoidType() &&                              // to void*
2753            CE->getSubExpr()->getType()->isIntegerType())         // from int.
2754          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2755      }
2756    }
2757  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2758    // Ignore the ImplicitCastExpr type entirely.
2759    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2760  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2761    // Accept ((void*)0) as a null pointer constant, as many other
2762    // implementations do.
2763    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2764  } else if (const GenericSelectionExpr *GE =
2765               dyn_cast<GenericSelectionExpr>(this)) {
2766    return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
2767  } else if (const CXXDefaultArgExpr *DefaultArg
2768               = dyn_cast<CXXDefaultArgExpr>(this)) {
2769    // See through default argument expressions
2770    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2771  } else if (isa<GNUNullExpr>(this)) {
2772    // The GNU __null extension is always a null pointer constant.
2773    return NPCK_GNUNull;
2774  } else if (const MaterializeTemporaryExpr *M
2775                                   = dyn_cast<MaterializeTemporaryExpr>(this)) {
2776    return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
2777  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
2778    if (const Expr *Source = OVE->getSourceExpr())
2779      return Source->isNullPointerConstant(Ctx, NPC);
2780  }
2781
2782  // C++0x nullptr_t is always a null pointer constant.
2783  if (getType()->isNullPtrType())
2784    return NPCK_CXX0X_nullptr;
2785
2786  if (const RecordType *UT = getType()->getAsUnionType())
2787    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2788      if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2789        const Expr *InitExpr = CLE->getInitializer();
2790        if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2791          return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2792      }
2793  // This expression must be an integer type.
2794  if (!getType()->isIntegerType() ||
2795      (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
2796    return NPCK_NotNull;
2797
2798  // If we have an integer constant expression, we need to *evaluate* it and
2799  // test for the value 0. Don't use the C++11 constant expression semantics
2800  // for this, for now; once the dust settles on core issue 903, we might only
2801  // allow a literal 0 here in C++11 mode.
2802  if (Ctx.getLangOptions().CPlusPlus0x) {
2803    if (!isCXX98IntegralConstantExpr(Ctx))
2804      return NPCK_NotNull;
2805  } else {
2806    if (!isIntegerConstantExpr(Ctx))
2807      return NPCK_NotNull;
2808  }
2809
2810  return (EvaluateKnownConstInt(Ctx) == 0) ? NPCK_ZeroInteger : NPCK_NotNull;
2811}
2812
2813/// \brief If this expression is an l-value for an Objective C
2814/// property, find the underlying property reference expression.
2815const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2816  const Expr *E = this;
2817  while (true) {
2818    assert((E->getValueKind() == VK_LValue &&
2819            E->getObjectKind() == OK_ObjCProperty) &&
2820           "expression is not a property reference");
2821    E = E->IgnoreParenCasts();
2822    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2823      if (BO->getOpcode() == BO_Comma) {
2824        E = BO->getRHS();
2825        continue;
2826      }
2827    }
2828
2829    break;
2830  }
2831
2832  return cast<ObjCPropertyRefExpr>(E);
2833}
2834
2835FieldDecl *Expr::getBitField() {
2836  Expr *E = this->IgnoreParens();
2837
2838  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2839    if (ICE->getCastKind() == CK_LValueToRValue ||
2840        (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
2841      E = ICE->getSubExpr()->IgnoreParens();
2842    else
2843      break;
2844  }
2845
2846  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2847    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2848      if (Field->isBitField())
2849        return Field;
2850
2851  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2852    if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2853      if (Field->isBitField())
2854        return Field;
2855
2856  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
2857    if (BinOp->isAssignmentOp() && BinOp->getLHS())
2858      return BinOp->getLHS()->getBitField();
2859
2860    if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
2861      return BinOp->getRHS()->getBitField();
2862  }
2863
2864  return 0;
2865}
2866
2867bool Expr::refersToVectorElement() const {
2868  const Expr *E = this->IgnoreParens();
2869
2870  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2871    if (ICE->getValueKind() != VK_RValue &&
2872        ICE->getCastKind() == CK_NoOp)
2873      E = ICE->getSubExpr()->IgnoreParens();
2874    else
2875      break;
2876  }
2877
2878  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2879    return ASE->getBase()->getType()->isVectorType();
2880
2881  if (isa<ExtVectorElementExpr>(E))
2882    return true;
2883
2884  return false;
2885}
2886
2887/// isArrow - Return true if the base expression is a pointer to vector,
2888/// return false if the base expression is a vector.
2889bool ExtVectorElementExpr::isArrow() const {
2890  return getBase()->getType()->isPointerType();
2891}
2892
2893unsigned ExtVectorElementExpr::getNumElements() const {
2894  if (const VectorType *VT = getType()->getAs<VectorType>())
2895    return VT->getNumElements();
2896  return 1;
2897}
2898
2899/// containsDuplicateElements - Return true if any element access is repeated.
2900bool ExtVectorElementExpr::containsDuplicateElements() const {
2901  // FIXME: Refactor this code to an accessor on the AST node which returns the
2902  // "type" of component access, and share with code below and in Sema.
2903  StringRef Comp = Accessor->getName();
2904
2905  // Halving swizzles do not contain duplicate elements.
2906  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
2907    return false;
2908
2909  // Advance past s-char prefix on hex swizzles.
2910  if (Comp[0] == 's' || Comp[0] == 'S')
2911    Comp = Comp.substr(1);
2912
2913  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2914    if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
2915        return true;
2916
2917  return false;
2918}
2919
2920/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
2921void ExtVectorElementExpr::getEncodedElementAccess(
2922                                  SmallVectorImpl<unsigned> &Elts) const {
2923  StringRef Comp = Accessor->getName();
2924  if (Comp[0] == 's' || Comp[0] == 'S')
2925    Comp = Comp.substr(1);
2926
2927  bool isHi =   Comp == "hi";
2928  bool isLo =   Comp == "lo";
2929  bool isEven = Comp == "even";
2930  bool isOdd  = Comp == "odd";
2931
2932  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2933    uint64_t Index;
2934
2935    if (isHi)
2936      Index = e + i;
2937    else if (isLo)
2938      Index = i;
2939    else if (isEven)
2940      Index = 2 * i;
2941    else if (isOdd)
2942      Index = 2 * i + 1;
2943    else
2944      Index = ExtVectorType::getAccessorIdx(Comp[i]);
2945
2946    Elts.push_back(Index);
2947  }
2948}
2949
2950ObjCMessageExpr::ObjCMessageExpr(QualType T,
2951                                 ExprValueKind VK,
2952                                 SourceLocation LBracLoc,
2953                                 SourceLocation SuperLoc,
2954                                 bool IsInstanceSuper,
2955                                 QualType SuperType,
2956                                 Selector Sel,
2957                                 ArrayRef<SourceLocation> SelLocs,
2958                                 SelectorLocationsKind SelLocsK,
2959                                 ObjCMethodDecl *Method,
2960                                 ArrayRef<Expr *> Args,
2961                                 SourceLocation RBracLoc,
2962                                 bool isImplicit)
2963  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
2964         /*TypeDependent=*/false, /*ValueDependent=*/false,
2965         /*InstantiationDependent=*/false,
2966         /*ContainsUnexpandedParameterPack=*/false),
2967    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2968                                                       : Sel.getAsOpaquePtr())),
2969    Kind(IsInstanceSuper? SuperInstance : SuperClass),
2970    HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
2971    SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2972{
2973  initArgsAndSelLocs(Args, SelLocs, SelLocsK);
2974  setReceiverPointer(SuperType.getAsOpaquePtr());
2975}
2976
2977ObjCMessageExpr::ObjCMessageExpr(QualType T,
2978                                 ExprValueKind VK,
2979                                 SourceLocation LBracLoc,
2980                                 TypeSourceInfo *Receiver,
2981                                 Selector Sel,
2982                                 ArrayRef<SourceLocation> SelLocs,
2983                                 SelectorLocationsKind SelLocsK,
2984                                 ObjCMethodDecl *Method,
2985                                 ArrayRef<Expr *> Args,
2986                                 SourceLocation RBracLoc,
2987                                 bool isImplicit)
2988  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
2989         T->isDependentType(), T->isInstantiationDependentType(),
2990         T->containsUnexpandedParameterPack()),
2991    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2992                                                       : Sel.getAsOpaquePtr())),
2993    Kind(Class),
2994    HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
2995    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2996{
2997  initArgsAndSelLocs(Args, SelLocs, SelLocsK);
2998  setReceiverPointer(Receiver);
2999}
3000
3001ObjCMessageExpr::ObjCMessageExpr(QualType T,
3002                                 ExprValueKind VK,
3003                                 SourceLocation LBracLoc,
3004                                 Expr *Receiver,
3005                                 Selector Sel,
3006                                 ArrayRef<SourceLocation> SelLocs,
3007                                 SelectorLocationsKind SelLocsK,
3008                                 ObjCMethodDecl *Method,
3009                                 ArrayRef<Expr *> Args,
3010                                 SourceLocation RBracLoc,
3011                                 bool isImplicit)
3012  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
3013         Receiver->isTypeDependent(),
3014         Receiver->isInstantiationDependent(),
3015         Receiver->containsUnexpandedParameterPack()),
3016    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3017                                                       : Sel.getAsOpaquePtr())),
3018    Kind(Instance),
3019    HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3020    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3021{
3022  initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3023  setReceiverPointer(Receiver);
3024}
3025
3026void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args,
3027                                         ArrayRef<SourceLocation> SelLocs,
3028                                         SelectorLocationsKind SelLocsK) {
3029  setNumArgs(Args.size());
3030  Expr **MyArgs = getArgs();
3031  for (unsigned I = 0; I != Args.size(); ++I) {
3032    if (Args[I]->isTypeDependent())
3033      ExprBits.TypeDependent = true;
3034    if (Args[I]->isValueDependent())
3035      ExprBits.ValueDependent = true;
3036    if (Args[I]->isInstantiationDependent())
3037      ExprBits.InstantiationDependent = true;
3038    if (Args[I]->containsUnexpandedParameterPack())
3039      ExprBits.ContainsUnexpandedParameterPack = true;
3040
3041    MyArgs[I] = Args[I];
3042  }
3043
3044  SelLocsKind = SelLocsK;
3045  if (!isImplicit()) {
3046    if (SelLocsK == SelLoc_NonStandard)
3047      std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
3048  }
3049}
3050
3051ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3052                                         ExprValueKind VK,
3053                                         SourceLocation LBracLoc,
3054                                         SourceLocation SuperLoc,
3055                                         bool IsInstanceSuper,
3056                                         QualType SuperType,
3057                                         Selector Sel,
3058                                         ArrayRef<SourceLocation> SelLocs,
3059                                         ObjCMethodDecl *Method,
3060                                         ArrayRef<Expr *> Args,
3061                                         SourceLocation RBracLoc,
3062                                         bool isImplicit) {
3063  assert((!SelLocs.empty() || isImplicit) &&
3064         "No selector locs for non-implicit message");
3065  ObjCMessageExpr *Mem;
3066  SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3067  if (isImplicit)
3068    Mem = alloc(Context, Args.size(), 0);
3069  else
3070    Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3071  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
3072                                   SuperType, Sel, SelLocs, SelLocsK,
3073                                   Method, Args, RBracLoc, isImplicit);
3074}
3075
3076ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3077                                         ExprValueKind VK,
3078                                         SourceLocation LBracLoc,
3079                                         TypeSourceInfo *Receiver,
3080                                         Selector Sel,
3081                                         ArrayRef<SourceLocation> SelLocs,
3082                                         ObjCMethodDecl *Method,
3083                                         ArrayRef<Expr *> Args,
3084                                         SourceLocation RBracLoc,
3085                                         bool isImplicit) {
3086  assert((!SelLocs.empty() || isImplicit) &&
3087         "No selector locs for non-implicit message");
3088  ObjCMessageExpr *Mem;
3089  SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3090  if (isImplicit)
3091    Mem = alloc(Context, Args.size(), 0);
3092  else
3093    Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3094  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
3095                                   SelLocs, SelLocsK, Method, Args, RBracLoc,
3096                                   isImplicit);
3097}
3098
3099ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3100                                         ExprValueKind VK,
3101                                         SourceLocation LBracLoc,
3102                                         Expr *Receiver,
3103                                         Selector Sel,
3104                                         ArrayRef<SourceLocation> SelLocs,
3105                                         ObjCMethodDecl *Method,
3106                                         ArrayRef<Expr *> Args,
3107                                         SourceLocation RBracLoc,
3108                                         bool isImplicit) {
3109  assert((!SelLocs.empty() || isImplicit) &&
3110         "No selector locs for non-implicit message");
3111  ObjCMessageExpr *Mem;
3112  SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3113  if (isImplicit)
3114    Mem = alloc(Context, Args.size(), 0);
3115  else
3116    Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3117  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
3118                                   SelLocs, SelLocsK, Method, Args, RBracLoc,
3119                                   isImplicit);
3120}
3121
3122ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
3123                                              unsigned NumArgs,
3124                                              unsigned NumStoredSelLocs) {
3125  ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs);
3126  return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
3127}
3128
3129ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3130                                        ArrayRef<Expr *> Args,
3131                                        SourceLocation RBraceLoc,
3132                                        ArrayRef<SourceLocation> SelLocs,
3133                                        Selector Sel,
3134                                        SelectorLocationsKind &SelLocsK) {
3135  SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc);
3136  unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size()
3137                                                               : 0;
3138  return alloc(C, Args.size(), NumStoredSelLocs);
3139}
3140
3141ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3142                                        unsigned NumArgs,
3143                                        unsigned NumStoredSelLocs) {
3144  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
3145    NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation);
3146  return (ObjCMessageExpr *)C.Allocate(Size,
3147                                     llvm::AlignOf<ObjCMessageExpr>::Alignment);
3148}
3149
3150void ObjCMessageExpr::getSelectorLocs(
3151                               SmallVectorImpl<SourceLocation> &SelLocs) const {
3152  for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
3153    SelLocs.push_back(getSelectorLoc(i));
3154}
3155
3156SourceRange ObjCMessageExpr::getReceiverRange() const {
3157  switch (getReceiverKind()) {
3158  case Instance:
3159    return getInstanceReceiver()->getSourceRange();
3160
3161  case Class:
3162    return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
3163
3164  case SuperInstance:
3165  case SuperClass:
3166    return getSuperLoc();
3167  }
3168
3169  llvm_unreachable("Invalid ReceiverKind!");
3170}
3171
3172Selector ObjCMessageExpr::getSelector() const {
3173  if (HasMethod)
3174    return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
3175                                                               ->getSelector();
3176  return Selector(SelectorOrMethod);
3177}
3178
3179ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
3180  switch (getReceiverKind()) {
3181  case Instance:
3182    if (const ObjCObjectPointerType *Ptr
3183          = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
3184      return Ptr->getInterfaceDecl();
3185    break;
3186
3187  case Class:
3188    if (const ObjCObjectType *Ty
3189          = getClassReceiver()->getAs<ObjCObjectType>())
3190      return Ty->getInterface();
3191    break;
3192
3193  case SuperInstance:
3194    if (const ObjCObjectPointerType *Ptr
3195          = getSuperType()->getAs<ObjCObjectPointerType>())
3196      return Ptr->getInterfaceDecl();
3197    break;
3198
3199  case SuperClass:
3200    if (const ObjCObjectType *Iface
3201          = getSuperType()->getAs<ObjCObjectType>())
3202      return Iface->getInterface();
3203    break;
3204  }
3205
3206  return 0;
3207}
3208
3209StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
3210  switch (getBridgeKind()) {
3211  case OBC_Bridge:
3212    return "__bridge";
3213  case OBC_BridgeTransfer:
3214    return "__bridge_transfer";
3215  case OBC_BridgeRetained:
3216    return "__bridge_retained";
3217  }
3218
3219  llvm_unreachable("Invalid BridgeKind!");
3220}
3221
3222bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
3223  return getCond()->EvaluateKnownConstInt(C) != 0;
3224}
3225
3226ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3227                                     QualType Type, SourceLocation BLoc,
3228                                     SourceLocation RP)
3229   : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3230          Type->isDependentType(), Type->isDependentType(),
3231          Type->isInstantiationDependentType(),
3232          Type->containsUnexpandedParameterPack()),
3233     BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
3234{
3235  SubExprs = new (C) Stmt*[nexpr];
3236  for (unsigned i = 0; i < nexpr; i++) {
3237    if (args[i]->isTypeDependent())
3238      ExprBits.TypeDependent = true;
3239    if (args[i]->isValueDependent())
3240      ExprBits.ValueDependent = true;
3241    if (args[i]->isInstantiationDependent())
3242      ExprBits.InstantiationDependent = true;
3243    if (args[i]->containsUnexpandedParameterPack())
3244      ExprBits.ContainsUnexpandedParameterPack = true;
3245
3246    SubExprs[i] = args[i];
3247  }
3248}
3249
3250void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
3251                                 unsigned NumExprs) {
3252  if (SubExprs) C.Deallocate(SubExprs);
3253
3254  SubExprs = new (C) Stmt* [NumExprs];
3255  this->NumExprs = NumExprs;
3256  memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
3257}
3258
3259GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3260                               SourceLocation GenericLoc, Expr *ControllingExpr,
3261                               TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3262                               unsigned NumAssocs, SourceLocation DefaultLoc,
3263                               SourceLocation RParenLoc,
3264                               bool ContainsUnexpandedParameterPack,
3265                               unsigned ResultIndex)
3266  : Expr(GenericSelectionExprClass,
3267         AssocExprs[ResultIndex]->getType(),
3268         AssocExprs[ResultIndex]->getValueKind(),
3269         AssocExprs[ResultIndex]->getObjectKind(),
3270         AssocExprs[ResultIndex]->isTypeDependent(),
3271         AssocExprs[ResultIndex]->isValueDependent(),
3272         AssocExprs[ResultIndex]->isInstantiationDependent(),
3273         ContainsUnexpandedParameterPack),
3274    AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3275    SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3276    ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3277    RParenLoc(RParenLoc) {
3278  SubExprs[CONTROLLING] = ControllingExpr;
3279  std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3280  std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3281}
3282
3283GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3284                               SourceLocation GenericLoc, Expr *ControllingExpr,
3285                               TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3286                               unsigned NumAssocs, SourceLocation DefaultLoc,
3287                               SourceLocation RParenLoc,
3288                               bool ContainsUnexpandedParameterPack)
3289  : Expr(GenericSelectionExprClass,
3290         Context.DependentTy,
3291         VK_RValue,
3292         OK_Ordinary,
3293         /*isTypeDependent=*/true,
3294         /*isValueDependent=*/true,
3295         /*isInstantiationDependent=*/true,
3296         ContainsUnexpandedParameterPack),
3297    AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3298    SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3299    ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3300    RParenLoc(RParenLoc) {
3301  SubExprs[CONTROLLING] = ControllingExpr;
3302  std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3303  std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3304}
3305
3306//===----------------------------------------------------------------------===//
3307//  DesignatedInitExpr
3308//===----------------------------------------------------------------------===//
3309
3310IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3311  assert(Kind == FieldDesignator && "Only valid on a field designator");
3312  if (Field.NameOrField & 0x01)
3313    return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3314  else
3315    return getField()->getIdentifier();
3316}
3317
3318DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
3319                                       unsigned NumDesignators,
3320                                       const Designator *Designators,
3321                                       SourceLocation EqualOrColonLoc,
3322                                       bool GNUSyntax,
3323                                       Expr **IndexExprs,
3324                                       unsigned NumIndexExprs,
3325                                       Expr *Init)
3326  : Expr(DesignatedInitExprClass, Ty,
3327         Init->getValueKind(), Init->getObjectKind(),
3328         Init->isTypeDependent(), Init->isValueDependent(),
3329         Init->isInstantiationDependent(),
3330         Init->containsUnexpandedParameterPack()),
3331    EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3332    NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
3333  this->Designators = new (C) Designator[NumDesignators];
3334
3335  // Record the initializer itself.
3336  child_range Child = children();
3337  *Child++ = Init;
3338
3339  // Copy the designators and their subexpressions, computing
3340  // value-dependence along the way.
3341  unsigned IndexIdx = 0;
3342  for (unsigned I = 0; I != NumDesignators; ++I) {
3343    this->Designators[I] = Designators[I];
3344
3345    if (this->Designators[I].isArrayDesignator()) {
3346      // Compute type- and value-dependence.
3347      Expr *Index = IndexExprs[IndexIdx];
3348      if (Index->isTypeDependent() || Index->isValueDependent())
3349        ExprBits.ValueDependent = true;
3350      if (Index->isInstantiationDependent())
3351        ExprBits.InstantiationDependent = true;
3352      // Propagate unexpanded parameter packs.
3353      if (Index->containsUnexpandedParameterPack())
3354        ExprBits.ContainsUnexpandedParameterPack = true;
3355
3356      // Copy the index expressions into permanent storage.
3357      *Child++ = IndexExprs[IndexIdx++];
3358    } else if (this->Designators[I].isArrayRangeDesignator()) {
3359      // Compute type- and value-dependence.
3360      Expr *Start = IndexExprs[IndexIdx];
3361      Expr *End = IndexExprs[IndexIdx + 1];
3362      if (Start->isTypeDependent() || Start->isValueDependent() ||
3363          End->isTypeDependent() || End->isValueDependent()) {
3364        ExprBits.ValueDependent = true;
3365        ExprBits.InstantiationDependent = true;
3366      } else if (Start->isInstantiationDependent() ||
3367                 End->isInstantiationDependent()) {
3368        ExprBits.InstantiationDependent = true;
3369      }
3370
3371      // Propagate unexpanded parameter packs.
3372      if (Start->containsUnexpandedParameterPack() ||
3373          End->containsUnexpandedParameterPack())
3374        ExprBits.ContainsUnexpandedParameterPack = true;
3375
3376      // Copy the start/end expressions into permanent storage.
3377      *Child++ = IndexExprs[IndexIdx++];
3378      *Child++ = IndexExprs[IndexIdx++];
3379    }
3380  }
3381
3382  assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
3383}
3384
3385DesignatedInitExpr *
3386DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
3387                           unsigned NumDesignators,
3388                           Expr **IndexExprs, unsigned NumIndexExprs,
3389                           SourceLocation ColonOrEqualLoc,
3390                           bool UsesColonSyntax, Expr *Init) {
3391  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3392                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3393  return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
3394                                      ColonOrEqualLoc, UsesColonSyntax,
3395                                      IndexExprs, NumIndexExprs, Init);
3396}
3397
3398DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
3399                                                    unsigned NumIndexExprs) {
3400  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3401                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3402  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3403}
3404
3405void DesignatedInitExpr::setDesignators(ASTContext &C,
3406                                        const Designator *Desigs,
3407                                        unsigned NumDesigs) {
3408  Designators = new (C) Designator[NumDesigs];
3409  NumDesignators = NumDesigs;
3410  for (unsigned I = 0; I != NumDesigs; ++I)
3411    Designators[I] = Desigs[I];
3412}
3413
3414SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3415  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3416  if (size() == 1)
3417    return DIE->getDesignator(0)->getSourceRange();
3418  return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3419                     DIE->getDesignator(size()-1)->getEndLocation());
3420}
3421
3422SourceRange DesignatedInitExpr::getSourceRange() const {
3423  SourceLocation StartLoc;
3424  Designator &First =
3425    *const_cast<DesignatedInitExpr*>(this)->designators_begin();
3426  if (First.isFieldDesignator()) {
3427    if (GNUSyntax)
3428      StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3429    else
3430      StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3431  } else
3432    StartLoc =
3433      SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3434  return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3435}
3436
3437Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3438  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3439  char* Ptr = static_cast<char*>(static_cast<void *>(this));
3440  Ptr += sizeof(DesignatedInitExpr);
3441  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3442  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3443}
3444
3445Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
3446  assert(D.Kind == Designator::ArrayRangeDesignator &&
3447         "Requires array range designator");
3448  char* Ptr = static_cast<char*>(static_cast<void *>(this));
3449  Ptr += sizeof(DesignatedInitExpr);
3450  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3451  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3452}
3453
3454Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
3455  assert(D.Kind == Designator::ArrayRangeDesignator &&
3456         "Requires array range designator");
3457  char* Ptr = static_cast<char*>(static_cast<void *>(this));
3458  Ptr += sizeof(DesignatedInitExpr);
3459  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3460  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3461}
3462
3463/// \brief Replaces the designator at index @p Idx with the series
3464/// of designators in [First, Last).
3465void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
3466                                          const Designator *First,
3467                                          const Designator *Last) {
3468  unsigned NumNewDesignators = Last - First;
3469  if (NumNewDesignators == 0) {
3470    std::copy_backward(Designators + Idx + 1,
3471                       Designators + NumDesignators,
3472                       Designators + Idx);
3473    --NumNewDesignators;
3474    return;
3475  } else if (NumNewDesignators == 1) {
3476    Designators[Idx] = *First;
3477    return;
3478  }
3479
3480  Designator *NewDesignators
3481    = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3482  std::copy(Designators, Designators + Idx, NewDesignators);
3483  std::copy(First, Last, NewDesignators + Idx);
3484  std::copy(Designators + Idx + 1, Designators + NumDesignators,
3485            NewDesignators + Idx + NumNewDesignators);
3486  Designators = NewDesignators;
3487  NumDesignators = NumDesignators - 1 + NumNewDesignators;
3488}
3489
3490ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
3491                             Expr **exprs, unsigned nexprs,
3492                             SourceLocation rparenloc)
3493  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3494         false, false, false, false),
3495    NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3496  Exprs = new (C) Stmt*[nexprs];
3497  for (unsigned i = 0; i != nexprs; ++i) {
3498    if (exprs[i]->isTypeDependent())
3499      ExprBits.TypeDependent = true;
3500    if (exprs[i]->isValueDependent())
3501      ExprBits.ValueDependent = true;
3502    if (exprs[i]->isInstantiationDependent())
3503      ExprBits.InstantiationDependent = true;
3504    if (exprs[i]->containsUnexpandedParameterPack())
3505      ExprBits.ContainsUnexpandedParameterPack = true;
3506
3507    Exprs[i] = exprs[i];
3508  }
3509}
3510
3511const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3512  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3513    e = ewc->getSubExpr();
3514  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3515    e = m->GetTemporaryExpr();
3516  e = cast<CXXConstructExpr>(e)->getArg(0);
3517  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3518    e = ice->getSubExpr();
3519  return cast<OpaqueValueExpr>(e);
3520}
3521
3522PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh,
3523                                           unsigned numSemanticExprs) {
3524  void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
3525                                    (1 + numSemanticExprs) * sizeof(Expr*),
3526                                  llvm::alignOf<PseudoObjectExpr>());
3527  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3528}
3529
3530PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3531  : Expr(PseudoObjectExprClass, shell) {
3532  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3533}
3534
3535PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax,
3536                                           ArrayRef<Expr*> semantics,
3537                                           unsigned resultIndex) {
3538  assert(syntax && "no syntactic expression!");
3539  assert(semantics.size() && "no semantic expressions!");
3540
3541  QualType type;
3542  ExprValueKind VK;
3543  if (resultIndex == NoResult) {
3544    type = C.VoidTy;
3545    VK = VK_RValue;
3546  } else {
3547    assert(resultIndex < semantics.size());
3548    type = semantics[resultIndex]->getType();
3549    VK = semantics[resultIndex]->getValueKind();
3550    assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3551  }
3552
3553  void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
3554                              (1 + semantics.size()) * sizeof(Expr*),
3555                            llvm::alignOf<PseudoObjectExpr>());
3556  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3557                                      resultIndex);
3558}
3559
3560PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3561                                   Expr *syntax, ArrayRef<Expr*> semantics,
3562                                   unsigned resultIndex)
3563  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3564         /*filled in at end of ctor*/ false, false, false, false) {
3565  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3566  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3567
3568  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3569    Expr *E = (i == 0 ? syntax : semantics[i-1]);
3570    getSubExprsBuffer()[i] = E;
3571
3572    if (E->isTypeDependent())
3573      ExprBits.TypeDependent = true;
3574    if (E->isValueDependent())
3575      ExprBits.ValueDependent = true;
3576    if (E->isInstantiationDependent())
3577      ExprBits.InstantiationDependent = true;
3578    if (E->containsUnexpandedParameterPack())
3579      ExprBits.ContainsUnexpandedParameterPack = true;
3580
3581    if (isa<OpaqueValueExpr>(E))
3582      assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 &&
3583             "opaque-value semantic expressions for pseudo-object "
3584             "operations must have sources");
3585  }
3586}
3587
3588//===----------------------------------------------------------------------===//
3589//  ExprIterator.
3590//===----------------------------------------------------------------------===//
3591
3592Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
3593Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
3594Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
3595const Expr* ConstExprIterator::operator[](size_t idx) const {
3596  return cast<Expr>(I[idx]);
3597}
3598const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
3599const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3600
3601//===----------------------------------------------------------------------===//
3602//  Child Iterators for iterating over subexpressions/substatements
3603//===----------------------------------------------------------------------===//
3604
3605// UnaryExprOrTypeTraitExpr
3606Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3607  // If this is of a type and the type is a VLA type (and not a typedef), the
3608  // size expression of the VLA needs to be treated as an executable expression.
3609  // Why isn't this weirdness documented better in StmtIterator?
3610  if (isArgumentType()) {
3611    if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
3612                                   getArgumentType().getTypePtr()))
3613      return child_range(child_iterator(T), child_iterator());
3614    return child_range();
3615  }
3616  return child_range(&Argument.Ex, &Argument.Ex + 1);
3617}
3618
3619// ObjCMessageExpr
3620Stmt::child_range ObjCMessageExpr::children() {
3621  Stmt **begin;
3622  if (getReceiverKind() == Instance)
3623    begin = reinterpret_cast<Stmt **>(this + 1);
3624  else
3625    begin = reinterpret_cast<Stmt **>(getArgs());
3626  return child_range(begin,
3627                     reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
3628}
3629
3630// Blocks
3631BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
3632                                   SourceLocation l, bool ByRef,
3633                                   bool constAdded)
3634  : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false,
3635         d->isParameterPack()),
3636    D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
3637{
3638  bool TypeDependent = false;
3639  bool ValueDependent = false;
3640  bool InstantiationDependent = false;
3641  computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent,
3642                           InstantiationDependent);
3643  ExprBits.TypeDependent = TypeDependent;
3644  ExprBits.ValueDependent = ValueDependent;
3645  ExprBits.InstantiationDependent = InstantiationDependent;
3646}
3647
3648
3649AtomicExpr::AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr,
3650                       QualType t, AtomicOp op, SourceLocation RP)
3651  : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3652         false, false, false, false),
3653    NumSubExprs(nexpr), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3654{
3655  for (unsigned i = 0; i < nexpr; i++) {
3656    if (args[i]->isTypeDependent())
3657      ExprBits.TypeDependent = true;
3658    if (args[i]->isValueDependent())
3659      ExprBits.ValueDependent = true;
3660    if (args[i]->isInstantiationDependent())
3661      ExprBits.InstantiationDependent = true;
3662    if (args[i]->containsUnexpandedParameterPack())
3663      ExprBits.ContainsUnexpandedParameterPack = true;
3664
3665    SubExprs[i] = args[i];
3666  }
3667}
3668