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