clang API Documentation

Expr.cpp
Go to the documentation of this file.
00001 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Expr class and subclasses.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/APValue.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/Attr.h"
00017 #include "clang/AST/DeclCXX.h"
00018 #include "clang/AST/DeclObjC.h"
00019 #include "clang/AST/DeclTemplate.h"
00020 #include "clang/AST/EvaluatedExprVisitor.h"
00021 #include "clang/AST/Expr.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/Mangle.h"
00024 #include "clang/AST/RecordLayout.h"
00025 #include "clang/AST/StmtVisitor.h"
00026 #include "clang/Basic/Builtins.h"
00027 #include "clang/Basic/CharInfo.h"
00028 #include "clang/Basic/SourceManager.h"
00029 #include "clang/Basic/TargetInfo.h"
00030 #include "clang/Lex/Lexer.h"
00031 #include "clang/Lex/LiteralSupport.h"
00032 #include "clang/Sema/SemaDiagnostic.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include <algorithm>
00036 #include <cstring>
00037 using namespace clang;
00038 
00039 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
00040   const Expr *E = ignoreParenBaseCasts();
00041 
00042   QualType DerivedType = E->getType();
00043   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
00044     DerivedType = PTy->getPointeeType();
00045 
00046   if (DerivedType->isDependentType())
00047     return nullptr;
00048 
00049   const RecordType *Ty = DerivedType->castAs<RecordType>();
00050   Decl *D = Ty->getDecl();
00051   return cast<CXXRecordDecl>(D);
00052 }
00053 
00054 const Expr *Expr::skipRValueSubobjectAdjustments(
00055     SmallVectorImpl<const Expr *> &CommaLHSs,
00056     SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
00057   const Expr *E = this;
00058   while (true) {
00059     E = E->IgnoreParens();
00060 
00061     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
00062       if ((CE->getCastKind() == CK_DerivedToBase ||
00063            CE->getCastKind() == CK_UncheckedDerivedToBase) &&
00064           E->getType()->isRecordType()) {
00065         E = CE->getSubExpr();
00066         CXXRecordDecl *Derived
00067           = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
00068         Adjustments.push_back(SubobjectAdjustment(CE, Derived));
00069         continue;
00070       }
00071 
00072       if (CE->getCastKind() == CK_NoOp) {
00073         E = CE->getSubExpr();
00074         continue;
00075       }
00076     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
00077       if (!ME->isArrow()) {
00078         assert(ME->getBase()->getType()->isRecordType());
00079         if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
00080           if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
00081             E = ME->getBase();
00082             Adjustments.push_back(SubobjectAdjustment(Field));
00083             continue;
00084           }
00085         }
00086       }
00087     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
00088       if (BO->isPtrMemOp()) {
00089         assert(BO->getRHS()->isRValue());
00090         E = BO->getLHS();
00091         const MemberPointerType *MPT =
00092           BO->getRHS()->getType()->getAs<MemberPointerType>();
00093         Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
00094         continue;
00095       } else if (BO->getOpcode() == BO_Comma) {
00096         CommaLHSs.push_back(BO->getLHS());
00097         E = BO->getRHS();
00098         continue;
00099       }
00100     }
00101 
00102     // Nothing changed.
00103     break;
00104   }
00105   return E;
00106 }
00107 
00108 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
00109 /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
00110 /// but also int expressions which are produced by things like comparisons in
00111 /// C.
00112 bool Expr::isKnownToHaveBooleanValue() const {
00113   const Expr *E = IgnoreParens();
00114 
00115   // If this value has _Bool type, it is obvious 0/1.
00116   if (E->getType()->isBooleanType()) return true;
00117   // If this is a non-scalar-integer type, we don't care enough to try. 
00118   if (!E->getType()->isIntegralOrEnumerationType()) return false;
00119   
00120   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
00121     switch (UO->getOpcode()) {
00122     case UO_Plus:
00123       return UO->getSubExpr()->isKnownToHaveBooleanValue();
00124     case UO_LNot:
00125       return true;
00126     default:
00127       return false;
00128     }
00129   }
00130   
00131   // Only look through implicit casts.  If the user writes
00132   // '(int) (a && b)' treat it as an arbitrary int.
00133   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
00134     return CE->getSubExpr()->isKnownToHaveBooleanValue();
00135   
00136   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
00137     switch (BO->getOpcode()) {
00138     default: return false;
00139     case BO_LT:   // Relational operators.
00140     case BO_GT:
00141     case BO_LE:
00142     case BO_GE:
00143     case BO_EQ:   // Equality operators.
00144     case BO_NE:
00145     case BO_LAnd: // AND operator.
00146     case BO_LOr:  // Logical OR operator.
00147       return true;
00148         
00149     case BO_And:  // Bitwise AND operator.
00150     case BO_Xor:  // Bitwise XOR operator.
00151     case BO_Or:   // Bitwise OR operator.
00152       // Handle things like (x==2)|(y==12).
00153       return BO->getLHS()->isKnownToHaveBooleanValue() &&
00154              BO->getRHS()->isKnownToHaveBooleanValue();
00155         
00156     case BO_Comma:
00157     case BO_Assign:
00158       return BO->getRHS()->isKnownToHaveBooleanValue();
00159     }
00160   }
00161   
00162   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
00163     return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
00164            CO->getFalseExpr()->isKnownToHaveBooleanValue();
00165   
00166   return false;
00167 }
00168 
00169 // Amusing macro metaprogramming hack: check whether a class provides
00170 // a more specific implementation of getExprLoc().
00171 //
00172 // See also Stmt.cpp:{getLocStart(),getLocEnd()}.
00173 namespace {
00174   /// This implementation is used when a class provides a custom
00175   /// implementation of getExprLoc.
00176   template <class E, class T>
00177   SourceLocation getExprLocImpl(const Expr *expr,
00178                                 SourceLocation (T::*v)() const) {
00179     return static_cast<const E*>(expr)->getExprLoc();
00180   }
00181 
00182   /// This implementation is used when a class doesn't provide
00183   /// a custom implementation of getExprLoc.  Overload resolution
00184   /// should pick it over the implementation above because it's
00185   /// more specialized according to function template partial ordering.
00186   template <class E>
00187   SourceLocation getExprLocImpl(const Expr *expr,
00188                                 SourceLocation (Expr::*v)() const) {
00189     return static_cast<const E*>(expr)->getLocStart();
00190   }
00191 }
00192 
00193 SourceLocation Expr::getExprLoc() const {
00194   switch (getStmtClass()) {
00195   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
00196 #define ABSTRACT_STMT(type)
00197 #define STMT(type, base) \
00198   case Stmt::type##Class: break;
00199 #define EXPR(type, base) \
00200   case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
00201 #include "clang/AST/StmtNodes.inc"
00202   }
00203   llvm_unreachable("unknown expression kind");
00204 }
00205 
00206 //===----------------------------------------------------------------------===//
00207 // Primary Expressions.
00208 //===----------------------------------------------------------------------===//
00209 
00210 /// \brief Compute the type-, value-, and instantiation-dependence of a 
00211 /// declaration reference
00212 /// based on the declaration being referenced.
00213 static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
00214                                      QualType T, bool &TypeDependent,
00215                                      bool &ValueDependent,
00216                                      bool &InstantiationDependent) {
00217   TypeDependent = false;
00218   ValueDependent = false;
00219   InstantiationDependent = false;
00220 
00221   // (TD) C++ [temp.dep.expr]p3:
00222   //   An id-expression is type-dependent if it contains:
00223   //
00224   // and
00225   //
00226   // (VD) C++ [temp.dep.constexpr]p2:
00227   //  An identifier is value-dependent if it is:
00228 
00229   //  (TD)  - an identifier that was declared with dependent type
00230   //  (VD)  - a name declared with a dependent type,
00231   if (T->isDependentType()) {
00232     TypeDependent = true;
00233     ValueDependent = true;
00234     InstantiationDependent = true;
00235     return;
00236   } else if (T->isInstantiationDependentType()) {
00237     InstantiationDependent = true;
00238   }
00239   
00240   //  (TD)  - a conversion-function-id that specifies a dependent type
00241   if (D->getDeclName().getNameKind() 
00242                                 == DeclarationName::CXXConversionFunctionName) {
00243     QualType T = D->getDeclName().getCXXNameType();
00244     if (T->isDependentType()) {
00245       TypeDependent = true;
00246       ValueDependent = true;
00247       InstantiationDependent = true;
00248       return;
00249     }
00250     
00251     if (T->isInstantiationDependentType())
00252       InstantiationDependent = true;
00253   }
00254   
00255   //  (VD)  - the name of a non-type template parameter,
00256   if (isa<NonTypeTemplateParmDecl>(D)) {
00257     ValueDependent = true;
00258     InstantiationDependent = true;
00259     return;
00260   }
00261   
00262   //  (VD) - a constant with integral or enumeration type and is
00263   //         initialized with an expression that is value-dependent.
00264   //  (VD) - a constant with literal type and is initialized with an
00265   //         expression that is value-dependent [C++11].
00266   //  (VD) - FIXME: Missing from the standard:
00267   //       -  an entity with reference type and is initialized with an
00268   //          expression that is value-dependent [C++11]
00269   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
00270     if ((Ctx.getLangOpts().CPlusPlus11 ?
00271            Var->getType()->isLiteralType(Ctx) :
00272            Var->getType()->isIntegralOrEnumerationType()) &&
00273         (Var->getType().isConstQualified() ||
00274          Var->getType()->isReferenceType())) {
00275       if (const Expr *Init = Var->getAnyInitializer())
00276         if (Init->isValueDependent()) {
00277           ValueDependent = true;
00278           InstantiationDependent = true;
00279         }
00280     }
00281 
00282     // (VD) - FIXME: Missing from the standard: 
00283     //      -  a member function or a static data member of the current 
00284     //         instantiation
00285     if (Var->isStaticDataMember() && 
00286         Var->getDeclContext()->isDependentContext()) {
00287       ValueDependent = true;
00288       InstantiationDependent = true;
00289       TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
00290       if (TInfo->getType()->isIncompleteArrayType())
00291         TypeDependent = true;
00292     }
00293     
00294     return;
00295   }
00296   
00297   // (VD) - FIXME: Missing from the standard: 
00298   //      -  a member function or a static data member of the current 
00299   //         instantiation
00300   if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
00301     ValueDependent = true;
00302     InstantiationDependent = true;
00303   }
00304 }
00305 
00306 void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
00307   bool TypeDependent = false;
00308   bool ValueDependent = false;
00309   bool InstantiationDependent = false;
00310   computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
00311                            ValueDependent, InstantiationDependent);
00312 
00313   ExprBits.TypeDependent |= TypeDependent;
00314   ExprBits.ValueDependent |= ValueDependent;
00315   ExprBits.InstantiationDependent |= InstantiationDependent;
00316 
00317   // Is the declaration a parameter pack?
00318   if (getDecl()->isParameterPack())
00319     ExprBits.ContainsUnexpandedParameterPack = true;
00320 }
00321 
00322 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
00323                          NestedNameSpecifierLoc QualifierLoc,
00324                          SourceLocation TemplateKWLoc,
00325                          ValueDecl *D, bool RefersToEnclosingLocal,
00326                          const DeclarationNameInfo &NameInfo,
00327                          NamedDecl *FoundD,
00328                          const TemplateArgumentListInfo *TemplateArgs,
00329                          QualType T, ExprValueKind VK)
00330   : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
00331     D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
00332   DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
00333   if (QualifierLoc) {
00334     getInternalQualifierLoc() = QualifierLoc;
00335     auto *NNS = QualifierLoc.getNestedNameSpecifier();
00336     if (NNS->isInstantiationDependent())
00337       ExprBits.InstantiationDependent = true;
00338     if (NNS->containsUnexpandedParameterPack())
00339       ExprBits.ContainsUnexpandedParameterPack = true;
00340   }
00341   DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
00342   if (FoundD)
00343     getInternalFoundDecl() = FoundD;
00344   DeclRefExprBits.HasTemplateKWAndArgsInfo
00345     = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
00346   DeclRefExprBits.RefersToEnclosingLocal = RefersToEnclosingLocal;
00347   if (TemplateArgs) {
00348     bool Dependent = false;
00349     bool InstantiationDependent = false;
00350     bool ContainsUnexpandedParameterPack = false;
00351     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
00352                                                Dependent,
00353                                                InstantiationDependent,
00354                                                ContainsUnexpandedParameterPack);
00355     assert(!Dependent && "built a DeclRefExpr with dependent template args");
00356     ExprBits.InstantiationDependent |= InstantiationDependent;
00357     ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
00358   } else if (TemplateKWLoc.isValid()) {
00359     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
00360   }
00361   DeclRefExprBits.HadMultipleCandidates = 0;
00362 
00363   computeDependence(Ctx);
00364 }
00365 
00366 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
00367                                  NestedNameSpecifierLoc QualifierLoc,
00368                                  SourceLocation TemplateKWLoc,
00369                                  ValueDecl *D,
00370                                  bool RefersToEnclosingLocal,
00371                                  SourceLocation NameLoc,
00372                                  QualType T,
00373                                  ExprValueKind VK,
00374                                  NamedDecl *FoundD,
00375                                  const TemplateArgumentListInfo *TemplateArgs) {
00376   return Create(Context, QualifierLoc, TemplateKWLoc, D,
00377                 RefersToEnclosingLocal,
00378                 DeclarationNameInfo(D->getDeclName(), NameLoc),
00379                 T, VK, FoundD, TemplateArgs);
00380 }
00381 
00382 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
00383                                  NestedNameSpecifierLoc QualifierLoc,
00384                                  SourceLocation TemplateKWLoc,
00385                                  ValueDecl *D,
00386                                  bool RefersToEnclosingLocal,
00387                                  const DeclarationNameInfo &NameInfo,
00388                                  QualType T,
00389                                  ExprValueKind VK,
00390                                  NamedDecl *FoundD,
00391                                  const TemplateArgumentListInfo *TemplateArgs) {
00392   // Filter out cases where the found Decl is the same as the value refenenced.
00393   if (D == FoundD)
00394     FoundD = nullptr;
00395 
00396   std::size_t Size = sizeof(DeclRefExpr);
00397   if (QualifierLoc)
00398     Size += sizeof(NestedNameSpecifierLoc);
00399   if (FoundD)
00400     Size += sizeof(NamedDecl *);
00401   if (TemplateArgs)
00402     Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
00403   else if (TemplateKWLoc.isValid())
00404     Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
00405 
00406   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
00407   return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
00408                                RefersToEnclosingLocal,
00409                                NameInfo, FoundD, TemplateArgs, T, VK);
00410 }
00411 
00412 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
00413                                       bool HasQualifier,
00414                                       bool HasFoundDecl,
00415                                       bool HasTemplateKWAndArgsInfo,
00416                                       unsigned NumTemplateArgs) {
00417   std::size_t Size = sizeof(DeclRefExpr);
00418   if (HasQualifier)
00419     Size += sizeof(NestedNameSpecifierLoc);
00420   if (HasFoundDecl)
00421     Size += sizeof(NamedDecl *);
00422   if (HasTemplateKWAndArgsInfo)
00423     Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
00424 
00425   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
00426   return new (Mem) DeclRefExpr(EmptyShell());
00427 }
00428 
00429 SourceLocation DeclRefExpr::getLocStart() const {
00430   if (hasQualifier())
00431     return getQualifierLoc().getBeginLoc();
00432   return getNameInfo().getLocStart();
00433 }
00434 SourceLocation DeclRefExpr::getLocEnd() const {
00435   if (hasExplicitTemplateArgs())
00436     return getRAngleLoc();
00437   return getNameInfo().getLocEnd();
00438 }
00439 
00440 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
00441                                StringLiteral *SL)
00442     : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
00443            FNTy->isDependentType(), FNTy->isDependentType(),
00444            FNTy->isInstantiationDependentType(),
00445            /*ContainsUnexpandedParameterPack=*/false),
00446       Loc(L), Type(IT), FnName(SL) {}
00447 
00448 StringLiteral *PredefinedExpr::getFunctionName() {
00449   return cast_or_null<StringLiteral>(FnName);
00450 }
00451 
00452 StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
00453   switch (IT) {
00454   case Func:
00455     return "__func__";
00456   case Function:
00457     return "__FUNCTION__";
00458   case FuncDName:
00459     return "__FUNCDNAME__";
00460   case LFunction:
00461     return "L__FUNCTION__";
00462   case PrettyFunction:
00463     return "__PRETTY_FUNCTION__";
00464   case FuncSig:
00465     return "__FUNCSIG__";
00466   case PrettyFunctionNoVirtual:
00467     break;
00468   }
00469   llvm_unreachable("Unknown ident type for PredefinedExpr");
00470 }
00471 
00472 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
00473 // expr" policy instead.
00474 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
00475   ASTContext &Context = CurrentDecl->getASTContext();
00476 
00477   if (IT == PredefinedExpr::FuncDName) {
00478     if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
00479       std::unique_ptr<MangleContext> MC;
00480       MC.reset(Context.createMangleContext());
00481 
00482       if (MC->shouldMangleDeclName(ND)) {
00483         SmallString<256> Buffer;
00484         llvm::raw_svector_ostream Out(Buffer);
00485         if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
00486           MC->mangleCXXCtor(CD, Ctor_Base, Out);
00487         else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
00488           MC->mangleCXXDtor(DD, Dtor_Base, Out);
00489         else
00490           MC->mangleName(ND, Out);
00491 
00492         Out.flush();
00493         if (!Buffer.empty() && Buffer.front() == '\01')
00494           return Buffer.substr(1);
00495         return Buffer.str();
00496       } else
00497         return ND->getIdentifier()->getName();
00498     }
00499     return "";
00500   }
00501   if (auto *BD = dyn_cast<BlockDecl>(CurrentDecl)) {
00502     std::unique_ptr<MangleContext> MC;
00503     MC.reset(Context.createMangleContext());
00504     SmallString<256> Buffer;
00505     llvm::raw_svector_ostream Out(Buffer);
00506     auto DC = CurrentDecl->getDeclContext();
00507     if (DC->isFileContext())
00508       MC->mangleGlobalBlock(BD, /*ID*/ nullptr, Out);
00509     else if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
00510       MC->mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
00511     else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
00512       MC->mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
00513     else
00514       MC->mangleBlock(DC, BD, Out);
00515     return Out.str();
00516   }
00517   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
00518     if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
00519       return FD->getNameAsString();
00520 
00521     SmallString<256> Name;
00522     llvm::raw_svector_ostream Out(Name);
00523 
00524     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
00525       if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
00526         Out << "virtual ";
00527       if (MD->isStatic())
00528         Out << "static ";
00529     }
00530 
00531     PrintingPolicy Policy(Context.getLangOpts());
00532     std::string Proto;
00533     llvm::raw_string_ostream POut(Proto);
00534 
00535     const FunctionDecl *Decl = FD;
00536     if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
00537       Decl = Pattern;
00538     const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
00539     const FunctionProtoType *FT = nullptr;
00540     if (FD->hasWrittenPrototype())
00541       FT = dyn_cast<FunctionProtoType>(AFT);
00542 
00543     if (IT == FuncSig) {
00544       switch (FT->getCallConv()) {
00545       case CC_C: POut << "__cdecl "; break;
00546       case CC_X86StdCall: POut << "__stdcall "; break;
00547       case CC_X86FastCall: POut << "__fastcall "; break;
00548       case CC_X86ThisCall: POut << "__thiscall "; break;
00549       case CC_X86VectorCall: POut << "__vectorcall "; break;
00550       // Only bother printing the conventions that MSVC knows about.
00551       default: break;
00552       }
00553     }
00554 
00555     FD->printQualifiedName(POut, Policy);
00556 
00557     POut << "(";
00558     if (FT) {
00559       for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
00560         if (i) POut << ", ";
00561         POut << Decl->getParamDecl(i)->getType().stream(Policy);
00562       }
00563 
00564       if (FT->isVariadic()) {
00565         if (FD->getNumParams()) POut << ", ";
00566         POut << "...";
00567       }
00568     }
00569     POut << ")";
00570 
00571     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
00572       const FunctionType *FT = MD->getType()->castAs<FunctionType>();
00573       if (FT->isConst())
00574         POut << " const";
00575       if (FT->isVolatile())
00576         POut << " volatile";
00577       RefQualifierKind Ref = MD->getRefQualifier();
00578       if (Ref == RQ_LValue)
00579         POut << " &";
00580       else if (Ref == RQ_RValue)
00581         POut << " &&";
00582     }
00583 
00584     typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
00585     SpecsTy Specs;
00586     const DeclContext *Ctx = FD->getDeclContext();
00587     while (Ctx && isa<NamedDecl>(Ctx)) {
00588       const ClassTemplateSpecializationDecl *Spec
00589                                = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
00590       if (Spec && !Spec->isExplicitSpecialization())
00591         Specs.push_back(Spec);
00592       Ctx = Ctx->getParent();
00593     }
00594 
00595     std::string TemplateParams;
00596     llvm::raw_string_ostream TOut(TemplateParams);
00597     for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
00598          I != E; ++I) {
00599       const TemplateParameterList *Params 
00600                   = (*I)->getSpecializedTemplate()->getTemplateParameters();
00601       const TemplateArgumentList &Args = (*I)->getTemplateArgs();
00602       assert(Params->size() == Args.size());
00603       for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
00604         StringRef Param = Params->getParam(i)->getName();
00605         if (Param.empty()) continue;
00606         TOut << Param << " = ";
00607         Args.get(i).print(Policy, TOut);
00608         TOut << ", ";
00609       }
00610     }
00611 
00612     FunctionTemplateSpecializationInfo *FSI 
00613                                           = FD->getTemplateSpecializationInfo();
00614     if (FSI && !FSI->isExplicitSpecialization()) {
00615       const TemplateParameterList* Params 
00616                                   = FSI->getTemplate()->getTemplateParameters();
00617       const TemplateArgumentList* Args = FSI->TemplateArguments;
00618       assert(Params->size() == Args->size());
00619       for (unsigned i = 0, e = Params->size(); i != e; ++i) {
00620         StringRef Param = Params->getParam(i)->getName();
00621         if (Param.empty()) continue;
00622         TOut << Param << " = ";
00623         Args->get(i).print(Policy, TOut);
00624         TOut << ", ";
00625       }
00626     }
00627 
00628     TOut.flush();
00629     if (!TemplateParams.empty()) {
00630       // remove the trailing comma and space
00631       TemplateParams.resize(TemplateParams.size() - 2);
00632       POut << " [" << TemplateParams << "]";
00633     }
00634 
00635     POut.flush();
00636 
00637     // Print "auto" for all deduced return types. This includes C++1y return
00638     // type deduction and lambdas. For trailing return types resolve the
00639     // decltype expression. Otherwise print the real type when this is
00640     // not a constructor or destructor.
00641     if (isa<CXXMethodDecl>(FD) &&
00642          cast<CXXMethodDecl>(FD)->getParent()->isLambda())
00643       Proto = "auto " + Proto;
00644     else if (FT && FT->getReturnType()->getAs<DecltypeType>())
00645       FT->getReturnType()
00646           ->getAs<DecltypeType>()
00647           ->getUnderlyingType()
00648           .getAsStringInternal(Proto, Policy);
00649     else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
00650       AFT->getReturnType().getAsStringInternal(Proto, Policy);
00651 
00652     Out << Proto;
00653 
00654     Out.flush();
00655     return Name.str().str();
00656   }
00657   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
00658     for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
00659       // Skip to its enclosing function or method, but not its enclosing
00660       // CapturedDecl.
00661       if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
00662         const Decl *D = Decl::castFromDeclContext(DC);
00663         return ComputeName(IT, D);
00664       }
00665     llvm_unreachable("CapturedDecl not inside a function or method");
00666   }
00667   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
00668     SmallString<256> Name;
00669     llvm::raw_svector_ostream Out(Name);
00670     Out << (MD->isInstanceMethod() ? '-' : '+');
00671     Out << '[';
00672 
00673     // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
00674     // a null check to avoid a crash.
00675     if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
00676       Out << *ID;
00677 
00678     if (const ObjCCategoryImplDecl *CID =
00679         dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
00680       Out << '(' << *CID << ')';
00681 
00682     Out <<  ' ';
00683     MD->getSelector().print(Out);
00684     Out <<  ']';
00685 
00686     Out.flush();
00687     return Name.str().str();
00688   }
00689   if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
00690     // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
00691     return "top level";
00692   }
00693   return "";
00694 }
00695 
00696 void APNumericStorage::setIntValue(const ASTContext &C,
00697                                    const llvm::APInt &Val) {
00698   if (hasAllocation())
00699     C.Deallocate(pVal);
00700 
00701   BitWidth = Val.getBitWidth();
00702   unsigned NumWords = Val.getNumWords();
00703   const uint64_t* Words = Val.getRawData();
00704   if (NumWords > 1) {
00705     pVal = new (C) uint64_t[NumWords];
00706     std::copy(Words, Words + NumWords, pVal);
00707   } else if (NumWords == 1)
00708     VAL = Words[0];
00709   else
00710     VAL = 0;
00711 }
00712 
00713 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
00714                                QualType type, SourceLocation l)
00715   : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
00716          false, false),
00717     Loc(l) {
00718   assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
00719   assert(V.getBitWidth() == C.getIntWidth(type) &&
00720          "Integer type is not the correct size for constant.");
00721   setValue(C, V);
00722 }
00723 
00724 IntegerLiteral *
00725 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
00726                        QualType type, SourceLocation l) {
00727   return new (C) IntegerLiteral(C, V, type, l);
00728 }
00729 
00730 IntegerLiteral *
00731 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
00732   return new (C) IntegerLiteral(Empty);
00733 }
00734 
00735 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
00736                                  bool isexact, QualType Type, SourceLocation L)
00737   : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
00738          false, false), Loc(L) {
00739   setSemantics(V.getSemantics());
00740   FloatingLiteralBits.IsExact = isexact;
00741   setValue(C, V);
00742 }
00743 
00744 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
00745   : Expr(FloatingLiteralClass, Empty) {
00746   setRawSemantics(IEEEhalf);
00747   FloatingLiteralBits.IsExact = false;
00748 }
00749 
00750 FloatingLiteral *
00751 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
00752                         bool isexact, QualType Type, SourceLocation L) {
00753   return new (C) FloatingLiteral(C, V, isexact, Type, L);
00754 }
00755 
00756 FloatingLiteral *
00757 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
00758   return new (C) FloatingLiteral(C, Empty);
00759 }
00760 
00761 const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
00762   switch(FloatingLiteralBits.Semantics) {
00763   case IEEEhalf:
00764     return llvm::APFloat::IEEEhalf;
00765   case IEEEsingle:
00766     return llvm::APFloat::IEEEsingle;
00767   case IEEEdouble:
00768     return llvm::APFloat::IEEEdouble;
00769   case x87DoubleExtended:
00770     return llvm::APFloat::x87DoubleExtended;
00771   case IEEEquad:
00772     return llvm::APFloat::IEEEquad;
00773   case PPCDoubleDouble:
00774     return llvm::APFloat::PPCDoubleDouble;
00775   }
00776   llvm_unreachable("Unrecognised floating semantics");
00777 }
00778 
00779 void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
00780   if (&Sem == &llvm::APFloat::IEEEhalf)
00781     FloatingLiteralBits.Semantics = IEEEhalf;
00782   else if (&Sem == &llvm::APFloat::IEEEsingle)
00783     FloatingLiteralBits.Semantics = IEEEsingle;
00784   else if (&Sem == &llvm::APFloat::IEEEdouble)
00785     FloatingLiteralBits.Semantics = IEEEdouble;
00786   else if (&Sem == &llvm::APFloat::x87DoubleExtended)
00787     FloatingLiteralBits.Semantics = x87DoubleExtended;
00788   else if (&Sem == &llvm::APFloat::IEEEquad)
00789     FloatingLiteralBits.Semantics = IEEEquad;
00790   else if (&Sem == &llvm::APFloat::PPCDoubleDouble)
00791     FloatingLiteralBits.Semantics = PPCDoubleDouble;
00792   else
00793     llvm_unreachable("Unknown floating semantics");
00794 }
00795 
00796 /// getValueAsApproximateDouble - This returns the value as an inaccurate
00797 /// double.  Note that this may cause loss of precision, but is useful for
00798 /// debugging dumps, etc.
00799 double FloatingLiteral::getValueAsApproximateDouble() const {
00800   llvm::APFloat V = getValue();
00801   bool ignored;
00802   V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
00803             &ignored);
00804   return V.convertToDouble();
00805 }
00806 
00807 int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
00808   int CharByteWidth = 0;
00809   switch(k) {
00810     case Ascii:
00811     case UTF8:
00812       CharByteWidth = target.getCharWidth();
00813       break;
00814     case Wide:
00815       CharByteWidth = target.getWCharWidth();
00816       break;
00817     case UTF16:
00818       CharByteWidth = target.getChar16Width();
00819       break;
00820     case UTF32:
00821       CharByteWidth = target.getChar32Width();
00822       break;
00823   }
00824   assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
00825   CharByteWidth /= 8;
00826   assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
00827          && "character byte widths supported are 1, 2, and 4 only");
00828   return CharByteWidth;
00829 }
00830 
00831 StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
00832                                      StringKind Kind, bool Pascal, QualType Ty,
00833                                      const SourceLocation *Loc,
00834                                      unsigned NumStrs) {
00835   assert(C.getAsConstantArrayType(Ty) &&
00836          "StringLiteral must be of constant array type!");
00837 
00838   // Allocate enough space for the StringLiteral plus an array of locations for
00839   // any concatenated string tokens.
00840   void *Mem = C.Allocate(sizeof(StringLiteral)+
00841                          sizeof(SourceLocation)*(NumStrs-1),
00842                          llvm::alignOf<StringLiteral>());
00843   StringLiteral *SL = new (Mem) StringLiteral(Ty);
00844 
00845   // OPTIMIZE: could allocate this appended to the StringLiteral.
00846   SL->setString(C,Str,Kind,Pascal);
00847 
00848   SL->TokLocs[0] = Loc[0];
00849   SL->NumConcatenated = NumStrs;
00850 
00851   if (NumStrs != 1)
00852     memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
00853   return SL;
00854 }
00855 
00856 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
00857                                           unsigned NumStrs) {
00858   void *Mem = C.Allocate(sizeof(StringLiteral)+
00859                          sizeof(SourceLocation)*(NumStrs-1),
00860                          llvm::alignOf<StringLiteral>());
00861   StringLiteral *SL = new (Mem) StringLiteral(QualType());
00862   SL->CharByteWidth = 0;
00863   SL->Length = 0;
00864   SL->NumConcatenated = NumStrs;
00865   return SL;
00866 }
00867 
00868 void StringLiteral::outputString(raw_ostream &OS) const {
00869   switch (getKind()) {
00870   case Ascii: break; // no prefix.
00871   case Wide:  OS << 'L'; break;
00872   case UTF8:  OS << "u8"; break;
00873   case UTF16: OS << 'u'; break;
00874   case UTF32: OS << 'U'; break;
00875   }
00876   OS << '"';
00877   static const char Hex[] = "0123456789ABCDEF";
00878 
00879   unsigned LastSlashX = getLength();
00880   for (unsigned I = 0, N = getLength(); I != N; ++I) {
00881     switch (uint32_t Char = getCodeUnit(I)) {
00882     default:
00883       // FIXME: Convert UTF-8 back to codepoints before rendering.
00884 
00885       // Convert UTF-16 surrogate pairs back to codepoints before rendering.
00886       // Leave invalid surrogates alone; we'll use \x for those.
00887       if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && 
00888           Char <= 0xdbff) {
00889         uint32_t Trail = getCodeUnit(I + 1);
00890         if (Trail >= 0xdc00 && Trail <= 0xdfff) {
00891           Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
00892           ++I;
00893         }
00894       }
00895 
00896       if (Char > 0xff) {
00897         // If this is a wide string, output characters over 0xff using \x
00898         // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
00899         // codepoint: use \x escapes for invalid codepoints.
00900         if (getKind() == Wide ||
00901             (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
00902           // FIXME: Is this the best way to print wchar_t?
00903           OS << "\\x";
00904           int Shift = 28;
00905           while ((Char >> Shift) == 0)
00906             Shift -= 4;
00907           for (/**/; Shift >= 0; Shift -= 4)
00908             OS << Hex[(Char >> Shift) & 15];
00909           LastSlashX = I;
00910           break;
00911         }
00912 
00913         if (Char > 0xffff)
00914           OS << "\\U00"
00915              << Hex[(Char >> 20) & 15]
00916              << Hex[(Char >> 16) & 15];
00917         else
00918           OS << "\\u";
00919         OS << Hex[(Char >> 12) & 15]
00920            << Hex[(Char >>  8) & 15]
00921            << Hex[(Char >>  4) & 15]
00922            << Hex[(Char >>  0) & 15];
00923         break;
00924       }
00925 
00926       // If we used \x... for the previous character, and this character is a
00927       // hexadecimal digit, prevent it being slurped as part of the \x.
00928       if (LastSlashX + 1 == I) {
00929         switch (Char) {
00930           case '0': case '1': case '2': case '3': case '4':
00931           case '5': case '6': case '7': case '8': case '9':
00932           case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
00933           case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
00934             OS << "\"\"";
00935         }
00936       }
00937 
00938       assert(Char <= 0xff &&
00939              "Characters above 0xff should already have been handled.");
00940 
00941       if (isPrintable(Char))
00942         OS << (char)Char;
00943       else  // Output anything hard as an octal escape.
00944         OS << '\\'
00945            << (char)('0' + ((Char >> 6) & 7))
00946            << (char)('0' + ((Char >> 3) & 7))
00947            << (char)('0' + ((Char >> 0) & 7));
00948       break;
00949     // Handle some common non-printable cases to make dumps prettier.
00950     case '\\': OS << "\\\\"; break;
00951     case '"': OS << "\\\""; break;
00952     case '\n': OS << "\\n"; break;
00953     case '\t': OS << "\\t"; break;
00954     case '\a': OS << "\\a"; break;
00955     case '\b': OS << "\\b"; break;
00956     }
00957   }
00958   OS << '"';
00959 }
00960 
00961 void StringLiteral::setString(const ASTContext &C, StringRef Str,
00962                               StringKind Kind, bool IsPascal) {
00963   //FIXME: we assume that the string data comes from a target that uses the same
00964   // code unit size and endianess for the type of string.
00965   this->Kind = Kind;
00966   this->IsPascal = IsPascal;
00967   
00968   CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
00969   assert((Str.size()%CharByteWidth == 0)
00970          && "size of data must be multiple of CharByteWidth");
00971   Length = Str.size()/CharByteWidth;
00972 
00973   switch(CharByteWidth) {
00974     case 1: {
00975       char *AStrData = new (C) char[Length];
00976       std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
00977       StrData.asChar = AStrData;
00978       break;
00979     }
00980     case 2: {
00981       uint16_t *AStrData = new (C) uint16_t[Length];
00982       std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
00983       StrData.asUInt16 = AStrData;
00984       break;
00985     }
00986     case 4: {
00987       uint32_t *AStrData = new (C) uint32_t[Length];
00988       std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
00989       StrData.asUInt32 = AStrData;
00990       break;
00991     }
00992     default:
00993       assert(false && "unsupported CharByteWidth");
00994   }
00995 }
00996 
00997 /// getLocationOfByte - Return a source location that points to the specified
00998 /// byte of this string literal.
00999 ///
01000 /// Strings are amazingly complex.  They can be formed from multiple tokens and
01001 /// can have escape sequences in them in addition to the usual trigraph and
01002 /// escaped newline business.  This routine handles this complexity.
01003 ///
01004 SourceLocation StringLiteral::
01005 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
01006                   const LangOptions &Features, const TargetInfo &Target) const {
01007   assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
01008          "Only narrow string literals are currently supported");
01009 
01010   // Loop over all of the tokens in this string until we find the one that
01011   // contains the byte we're looking for.
01012   unsigned TokNo = 0;
01013   while (1) {
01014     assert(TokNo < getNumConcatenated() && "Invalid byte number!");
01015     SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
01016     
01017     // Get the spelling of the string so that we can get the data that makes up
01018     // the string literal, not the identifier for the macro it is potentially
01019     // expanded through.
01020     SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
01021     
01022     // Re-lex the token to get its length and original spelling.
01023     std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
01024     bool Invalid = false;
01025     StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
01026     if (Invalid)
01027       return StrTokSpellingLoc;
01028     
01029     const char *StrData = Buffer.data()+LocInfo.second;
01030     
01031     // Create a lexer starting at the beginning of this token.
01032     Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
01033                    Buffer.begin(), StrData, Buffer.end());
01034     Token TheTok;
01035     TheLexer.LexFromRawLexer(TheTok);
01036     
01037     // Use the StringLiteralParser to compute the length of the string in bytes.
01038     StringLiteralParser SLP(TheTok, SM, Features, Target);
01039     unsigned TokNumBytes = SLP.GetStringLength();
01040     
01041     // If the byte is in this token, return the location of the byte.
01042     if (ByteNo < TokNumBytes ||
01043         (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
01044       unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo); 
01045       
01046       // Now that we know the offset of the token in the spelling, use the
01047       // preprocessor to get the offset in the original source.
01048       return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
01049     }
01050     
01051     // Move to the next string token.
01052     ++TokNo;
01053     ByteNo -= TokNumBytes;
01054   }
01055 }
01056 
01057 
01058 
01059 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
01060 /// corresponds to, e.g. "sizeof" or "[pre]++".
01061 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
01062   switch (Op) {
01063   case UO_PostInc: return "++";
01064   case UO_PostDec: return "--";
01065   case UO_PreInc:  return "++";
01066   case UO_PreDec:  return "--";
01067   case UO_AddrOf:  return "&";
01068   case UO_Deref:   return "*";
01069   case UO_Plus:    return "+";
01070   case UO_Minus:   return "-";
01071   case UO_Not:     return "~";
01072   case UO_LNot:    return "!";
01073   case UO_Real:    return "__real";
01074   case UO_Imag:    return "__imag";
01075   case UO_Extension: return "__extension__";
01076   }
01077   llvm_unreachable("Unknown unary operator");
01078 }
01079 
01080 UnaryOperatorKind
01081 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
01082   switch (OO) {
01083   default: llvm_unreachable("No unary operator for overloaded function");
01084   case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
01085   case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
01086   case OO_Amp:        return UO_AddrOf;
01087   case OO_Star:       return UO_Deref;
01088   case OO_Plus:       return UO_Plus;
01089   case OO_Minus:      return UO_Minus;
01090   case OO_Tilde:      return UO_Not;
01091   case OO_Exclaim:    return UO_LNot;
01092   }
01093 }
01094 
01095 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
01096   switch (Opc) {
01097   case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
01098   case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
01099   case UO_AddrOf: return OO_Amp;
01100   case UO_Deref: return OO_Star;
01101   case UO_Plus: return OO_Plus;
01102   case UO_Minus: return OO_Minus;
01103   case UO_Not: return OO_Tilde;
01104   case UO_LNot: return OO_Exclaim;
01105   default: return OO_None;
01106   }
01107 }
01108 
01109 
01110 //===----------------------------------------------------------------------===//
01111 // Postfix Operators.
01112 //===----------------------------------------------------------------------===//
01113 
01114 CallExpr::CallExpr(const ASTContext& C, StmtClass SC, Expr *fn,
01115                    unsigned NumPreArgs, ArrayRef<Expr*> args, QualType t,
01116                    ExprValueKind VK, SourceLocation rparenloc)
01117   : Expr(SC, t, VK, OK_Ordinary,
01118          fn->isTypeDependent(),
01119          fn->isValueDependent(),
01120          fn->isInstantiationDependent(),
01121          fn->containsUnexpandedParameterPack()),
01122     NumArgs(args.size()) {
01123 
01124   SubExprs = new (C) Stmt*[args.size()+PREARGS_START+NumPreArgs];
01125   SubExprs[FN] = fn;
01126   for (unsigned i = 0; i != args.size(); ++i) {
01127     if (args[i]->isTypeDependent())
01128       ExprBits.TypeDependent = true;
01129     if (args[i]->isValueDependent())
01130       ExprBits.ValueDependent = true;
01131     if (args[i]->isInstantiationDependent())
01132       ExprBits.InstantiationDependent = true;
01133     if (args[i]->containsUnexpandedParameterPack())
01134       ExprBits.ContainsUnexpandedParameterPack = true;
01135 
01136     SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
01137   }
01138 
01139   CallExprBits.NumPreArgs = NumPreArgs;
01140   RParenLoc = rparenloc;
01141 }
01142 
01143 CallExpr::CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args,
01144                    QualType t, ExprValueKind VK, SourceLocation rparenloc)
01145   : Expr(CallExprClass, t, VK, OK_Ordinary,
01146          fn->isTypeDependent(),
01147          fn->isValueDependent(),
01148          fn->isInstantiationDependent(),
01149          fn->containsUnexpandedParameterPack()),
01150     NumArgs(args.size()) {
01151 
01152   SubExprs = new (C) Stmt*[args.size()+PREARGS_START];
01153   SubExprs[FN] = fn;
01154   for (unsigned i = 0; i != args.size(); ++i) {
01155     if (args[i]->isTypeDependent())
01156       ExprBits.TypeDependent = true;
01157     if (args[i]->isValueDependent())
01158       ExprBits.ValueDependent = true;
01159     if (args[i]->isInstantiationDependent())
01160       ExprBits.InstantiationDependent = true;
01161     if (args[i]->containsUnexpandedParameterPack())
01162       ExprBits.ContainsUnexpandedParameterPack = true;
01163 
01164     SubExprs[i+PREARGS_START] = args[i];
01165   }
01166 
01167   CallExprBits.NumPreArgs = 0;
01168   RParenLoc = rparenloc;
01169 }
01170 
01171 CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
01172   : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
01173   // FIXME: Why do we allocate this?
01174   SubExprs = new (C) Stmt*[PREARGS_START];
01175   CallExprBits.NumPreArgs = 0;
01176 }
01177 
01178 CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
01179                    EmptyShell Empty)
01180   : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
01181   // FIXME: Why do we allocate this?
01182   SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
01183   CallExprBits.NumPreArgs = NumPreArgs;
01184 }
01185 
01186 Decl *CallExpr::getCalleeDecl() {
01187   Expr *CEE = getCallee()->IgnoreParenImpCasts();
01188     
01189   while (SubstNonTypeTemplateParmExpr *NTTP
01190                                 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
01191     CEE = NTTP->getReplacement()->IgnoreParenCasts();
01192   }
01193   
01194   // If we're calling a dereference, look at the pointer instead.
01195   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
01196     if (BO->isPtrMemOp())
01197       CEE = BO->getRHS()->IgnoreParenCasts();
01198   } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
01199     if (UO->getOpcode() == UO_Deref)
01200       CEE = UO->getSubExpr()->IgnoreParenCasts();
01201   }
01202   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
01203     return DRE->getDecl();
01204   if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
01205     return ME->getMemberDecl();
01206 
01207   return nullptr;
01208 }
01209 
01210 FunctionDecl *CallExpr::getDirectCallee() {
01211   return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
01212 }
01213 
01214 /// setNumArgs - This changes the number of arguments present in this call.
01215 /// Any orphaned expressions are deleted by this, and any new operands are set
01216 /// to null.
01217 void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
01218   // No change, just return.
01219   if (NumArgs == getNumArgs()) return;
01220 
01221   // If shrinking # arguments, just delete the extras and forgot them.
01222   if (NumArgs < getNumArgs()) {
01223     this->NumArgs = NumArgs;
01224     return;
01225   }
01226 
01227   // Otherwise, we are growing the # arguments.  New an bigger argument array.
01228   unsigned NumPreArgs = getNumPreArgs();
01229   Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
01230   // Copy over args.
01231   for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
01232     NewSubExprs[i] = SubExprs[i];
01233   // Null out new args.
01234   for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
01235        i != NumArgs+PREARGS_START+NumPreArgs; ++i)
01236     NewSubExprs[i] = nullptr;
01237 
01238   if (SubExprs) C.Deallocate(SubExprs);
01239   SubExprs = NewSubExprs;
01240   this->NumArgs = NumArgs;
01241 }
01242 
01243 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
01244 /// not, return 0.
01245 unsigned CallExpr::getBuiltinCallee() const {
01246   // All simple function calls (e.g. func()) are implicitly cast to pointer to
01247   // function. As a result, we try and obtain the DeclRefExpr from the
01248   // ImplicitCastExpr.
01249   const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
01250   if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
01251     return 0;
01252 
01253   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
01254   if (!DRE)
01255     return 0;
01256 
01257   const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
01258   if (!FDecl)
01259     return 0;
01260 
01261   if (!FDecl->getIdentifier())
01262     return 0;
01263 
01264   return FDecl->getBuiltinID();
01265 }
01266 
01267 bool CallExpr::isUnevaluatedBuiltinCall(ASTContext &Ctx) const {
01268   if (unsigned BI = getBuiltinCallee())
01269     return Ctx.BuiltinInfo.isUnevaluated(BI);
01270   return false;
01271 }
01272 
01273 QualType CallExpr::getCallReturnType() const {
01274   QualType CalleeType = getCallee()->getType();
01275   if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
01276     CalleeType = FnTypePtr->getPointeeType();
01277   else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
01278     CalleeType = BPT->getPointeeType();
01279   else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
01280     // This should never be overloaded and so should never return null.
01281     CalleeType = Expr::findBoundMemberType(getCallee());
01282     
01283   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
01284   return FnType->getReturnType();
01285 }
01286 
01287 SourceLocation CallExpr::getLocStart() const {
01288   if (isa<CXXOperatorCallExpr>(this))
01289     return cast<CXXOperatorCallExpr>(this)->getLocStart();
01290 
01291   SourceLocation begin = getCallee()->getLocStart();
01292   if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
01293     begin = getArg(0)->getLocStart();
01294   return begin;
01295 }
01296 SourceLocation CallExpr::getLocEnd() const {
01297   if (isa<CXXOperatorCallExpr>(this))
01298     return cast<CXXOperatorCallExpr>(this)->getLocEnd();
01299 
01300   SourceLocation end = getRParenLoc();
01301   if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
01302     end = getArg(getNumArgs() - 1)->getLocEnd();
01303   return end;
01304 }
01305 
01306 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
01307                                    SourceLocation OperatorLoc,
01308                                    TypeSourceInfo *tsi, 
01309                                    ArrayRef<OffsetOfNode> comps,
01310                                    ArrayRef<Expr*> exprs,
01311                                    SourceLocation RParenLoc) {
01312   void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
01313                          sizeof(OffsetOfNode) * comps.size() +
01314                          sizeof(Expr*) * exprs.size());
01315 
01316   return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
01317                                 RParenLoc);
01318 }
01319 
01320 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
01321                                         unsigned numComps, unsigned numExprs) {
01322   void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
01323                          sizeof(OffsetOfNode) * numComps +
01324                          sizeof(Expr*) * numExprs);
01325   return new (Mem) OffsetOfExpr(numComps, numExprs);
01326 }
01327 
01328 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
01329                            SourceLocation OperatorLoc, TypeSourceInfo *tsi,
01330                            ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
01331                            SourceLocation RParenLoc)
01332   : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
01333          /*TypeDependent=*/false, 
01334          /*ValueDependent=*/tsi->getType()->isDependentType(),
01335          tsi->getType()->isInstantiationDependentType(),
01336          tsi->getType()->containsUnexpandedParameterPack()),
01337     OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), 
01338     NumComps(comps.size()), NumExprs(exprs.size())
01339 {
01340   for (unsigned i = 0; i != comps.size(); ++i) {
01341     setComponent(i, comps[i]);
01342   }
01343   
01344   for (unsigned i = 0; i != exprs.size(); ++i) {
01345     if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
01346       ExprBits.ValueDependent = true;
01347     if (exprs[i]->containsUnexpandedParameterPack())
01348       ExprBits.ContainsUnexpandedParameterPack = true;
01349 
01350     setIndexExpr(i, exprs[i]);
01351   }
01352 }
01353 
01354 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
01355   assert(getKind() == Field || getKind() == Identifier);
01356   if (getKind() == Field)
01357     return getField()->getIdentifier();
01358   
01359   return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
01360 }
01361 
01362 MemberExpr *MemberExpr::Create(const ASTContext &C, Expr *base, bool isarrow,
01363                                NestedNameSpecifierLoc QualifierLoc,
01364                                SourceLocation TemplateKWLoc,
01365                                ValueDecl *memberdecl,
01366                                DeclAccessPair founddecl,
01367                                DeclarationNameInfo nameinfo,
01368                                const TemplateArgumentListInfo *targs,
01369                                QualType ty,
01370                                ExprValueKind vk,
01371                                ExprObjectKind ok) {
01372   std::size_t Size = sizeof(MemberExpr);
01373 
01374   bool hasQualOrFound = (QualifierLoc ||
01375                          founddecl.getDecl() != memberdecl ||
01376                          founddecl.getAccess() != memberdecl->getAccess());
01377   if (hasQualOrFound)
01378     Size += sizeof(MemberNameQualifier);
01379 
01380   if (targs)
01381     Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
01382   else if (TemplateKWLoc.isValid())
01383     Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
01384 
01385   void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
01386   MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
01387                                        ty, vk, ok);
01388 
01389   if (hasQualOrFound) {
01390     // FIXME: Wrong. We should be looking at the member declaration we found.
01391     if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
01392       E->setValueDependent(true);
01393       E->setTypeDependent(true);
01394       E->setInstantiationDependent(true);
01395     } 
01396     else if (QualifierLoc && 
01397              QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) 
01398       E->setInstantiationDependent(true);
01399     
01400     E->HasQualifierOrFoundDecl = true;
01401 
01402     MemberNameQualifier *NQ = E->getMemberQualifier();
01403     NQ->QualifierLoc = QualifierLoc;
01404     NQ->FoundDecl = founddecl;
01405   }
01406 
01407   E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
01408 
01409   if (targs) {
01410     bool Dependent = false;
01411     bool InstantiationDependent = false;
01412     bool ContainsUnexpandedParameterPack = false;
01413     E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
01414                                                   Dependent,
01415                                                   InstantiationDependent,
01416                                              ContainsUnexpandedParameterPack);
01417     if (InstantiationDependent)
01418       E->setInstantiationDependent(true);
01419   } else if (TemplateKWLoc.isValid()) {
01420     E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
01421   }
01422 
01423   return E;
01424 }
01425 
01426 SourceLocation MemberExpr::getLocStart() const {
01427   if (isImplicitAccess()) {
01428     if (hasQualifier())
01429       return getQualifierLoc().getBeginLoc();
01430     return MemberLoc;
01431   }
01432 
01433   // FIXME: We don't want this to happen. Rather, we should be able to
01434   // detect all kinds of implicit accesses more cleanly.
01435   SourceLocation BaseStartLoc = getBase()->getLocStart();
01436   if (BaseStartLoc.isValid())
01437     return BaseStartLoc;
01438   return MemberLoc;
01439 }
01440 SourceLocation MemberExpr::getLocEnd() const {
01441   SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
01442   if (hasExplicitTemplateArgs())
01443     EndLoc = getRAngleLoc();
01444   else if (EndLoc.isInvalid())
01445     EndLoc = getBase()->getLocEnd();
01446   return EndLoc;
01447 }
01448 
01449 bool CastExpr::CastConsistency() const {
01450   switch (getCastKind()) {
01451   case CK_DerivedToBase:
01452   case CK_UncheckedDerivedToBase:
01453   case CK_DerivedToBaseMemberPointer:
01454   case CK_BaseToDerived:
01455   case CK_BaseToDerivedMemberPointer:
01456     assert(!path_empty() && "Cast kind should have a base path!");
01457     break;
01458 
01459   case CK_CPointerToObjCPointerCast:
01460     assert(getType()->isObjCObjectPointerType());
01461     assert(getSubExpr()->getType()->isPointerType());
01462     goto CheckNoBasePath;
01463 
01464   case CK_BlockPointerToObjCPointerCast:
01465     assert(getType()->isObjCObjectPointerType());
01466     assert(getSubExpr()->getType()->isBlockPointerType());
01467     goto CheckNoBasePath;
01468 
01469   case CK_ReinterpretMemberPointer:
01470     assert(getType()->isMemberPointerType());
01471     assert(getSubExpr()->getType()->isMemberPointerType());
01472     goto CheckNoBasePath;
01473 
01474   case CK_BitCast:
01475     // Arbitrary casts to C pointer types count as bitcasts.
01476     // Otherwise, we should only have block and ObjC pointer casts
01477     // here if they stay within the type kind.
01478     if (!getType()->isPointerType()) {
01479       assert(getType()->isObjCObjectPointerType() == 
01480              getSubExpr()->getType()->isObjCObjectPointerType());
01481       assert(getType()->isBlockPointerType() == 
01482              getSubExpr()->getType()->isBlockPointerType());
01483     }
01484     goto CheckNoBasePath;
01485 
01486   case CK_AnyPointerToBlockPointerCast:
01487     assert(getType()->isBlockPointerType());
01488     assert(getSubExpr()->getType()->isAnyPointerType() &&
01489            !getSubExpr()->getType()->isBlockPointerType());
01490     goto CheckNoBasePath;
01491 
01492   case CK_CopyAndAutoreleaseBlockObject:
01493     assert(getType()->isBlockPointerType());
01494     assert(getSubExpr()->getType()->isBlockPointerType());
01495     goto CheckNoBasePath;
01496 
01497   case CK_FunctionToPointerDecay:
01498     assert(getType()->isPointerType());
01499     assert(getSubExpr()->getType()->isFunctionType());
01500     goto CheckNoBasePath;
01501 
01502   case CK_AddressSpaceConversion:
01503     assert(getType()->isPointerType());
01504     assert(getSubExpr()->getType()->isPointerType());
01505     assert(getType()->getPointeeType().getAddressSpace() !=
01506            getSubExpr()->getType()->getPointeeType().getAddressSpace());
01507   // These should not have an inheritance path.
01508   case CK_Dynamic:
01509   case CK_ToUnion:
01510   case CK_ArrayToPointerDecay:
01511   case CK_NullToMemberPointer:
01512   case CK_NullToPointer:
01513   case CK_ConstructorConversion:
01514   case CK_IntegralToPointer:
01515   case CK_PointerToIntegral:
01516   case CK_ToVoid:
01517   case CK_VectorSplat:
01518   case CK_IntegralCast:
01519   case CK_IntegralToFloating:
01520   case CK_FloatingToIntegral:
01521   case CK_FloatingCast:
01522   case CK_ObjCObjectLValueCast:
01523   case CK_FloatingRealToComplex:
01524   case CK_FloatingComplexToReal:
01525   case CK_FloatingComplexCast:
01526   case CK_FloatingComplexToIntegralComplex:
01527   case CK_IntegralRealToComplex:
01528   case CK_IntegralComplexToReal:
01529   case CK_IntegralComplexCast:
01530   case CK_IntegralComplexToFloatingComplex:
01531   case CK_ARCProduceObject:
01532   case CK_ARCConsumeObject:
01533   case CK_ARCReclaimReturnedObject:
01534   case CK_ARCExtendBlockObject:
01535   case CK_ZeroToOCLEvent:
01536     assert(!getType()->isBooleanType() && "unheralded conversion to bool");
01537     goto CheckNoBasePath;
01538 
01539   case CK_Dependent:
01540   case CK_LValueToRValue:
01541   case CK_NoOp:
01542   case CK_AtomicToNonAtomic:
01543   case CK_NonAtomicToAtomic:
01544   case CK_PointerToBoolean:
01545   case CK_IntegralToBoolean:
01546   case CK_FloatingToBoolean:
01547   case CK_MemberPointerToBoolean:
01548   case CK_FloatingComplexToBoolean:
01549   case CK_IntegralComplexToBoolean:
01550   case CK_LValueBitCast:            // -> bool&
01551   case CK_UserDefinedConversion:    // operator bool()
01552   case CK_BuiltinFnToFnPtr:
01553   CheckNoBasePath:
01554     assert(path_empty() && "Cast kind should not have a base path!");
01555     break;
01556   }
01557   return true;
01558 }
01559 
01560 const char *CastExpr::getCastKindName() const {
01561   switch (getCastKind()) {
01562   case CK_Dependent:
01563     return "Dependent";
01564   case CK_BitCast:
01565     return "BitCast";
01566   case CK_LValueBitCast:
01567     return "LValueBitCast";
01568   case CK_LValueToRValue:
01569     return "LValueToRValue";
01570   case CK_NoOp:
01571     return "NoOp";
01572   case CK_BaseToDerived:
01573     return "BaseToDerived";
01574   case CK_DerivedToBase:
01575     return "DerivedToBase";
01576   case CK_UncheckedDerivedToBase:
01577     return "UncheckedDerivedToBase";
01578   case CK_Dynamic:
01579     return "Dynamic";
01580   case CK_ToUnion:
01581     return "ToUnion";
01582   case CK_ArrayToPointerDecay:
01583     return "ArrayToPointerDecay";
01584   case CK_FunctionToPointerDecay:
01585     return "FunctionToPointerDecay";
01586   case CK_NullToMemberPointer:
01587     return "NullToMemberPointer";
01588   case CK_NullToPointer:
01589     return "NullToPointer";
01590   case CK_BaseToDerivedMemberPointer:
01591     return "BaseToDerivedMemberPointer";
01592   case CK_DerivedToBaseMemberPointer:
01593     return "DerivedToBaseMemberPointer";
01594   case CK_ReinterpretMemberPointer:
01595     return "ReinterpretMemberPointer";
01596   case CK_UserDefinedConversion:
01597     return "UserDefinedConversion";
01598   case CK_ConstructorConversion:
01599     return "ConstructorConversion";
01600   case CK_IntegralToPointer:
01601     return "IntegralToPointer";
01602   case CK_PointerToIntegral:
01603     return "PointerToIntegral";
01604   case CK_PointerToBoolean:
01605     return "PointerToBoolean";
01606   case CK_ToVoid:
01607     return "ToVoid";
01608   case CK_VectorSplat:
01609     return "VectorSplat";
01610   case CK_IntegralCast:
01611     return "IntegralCast";
01612   case CK_IntegralToBoolean:
01613     return "IntegralToBoolean";
01614   case CK_IntegralToFloating:
01615     return "IntegralToFloating";
01616   case CK_FloatingToIntegral:
01617     return "FloatingToIntegral";
01618   case CK_FloatingCast:
01619     return "FloatingCast";
01620   case CK_FloatingToBoolean:
01621     return "FloatingToBoolean";
01622   case CK_MemberPointerToBoolean:
01623     return "MemberPointerToBoolean";
01624   case CK_CPointerToObjCPointerCast:
01625     return "CPointerToObjCPointerCast";
01626   case CK_BlockPointerToObjCPointerCast:
01627     return "BlockPointerToObjCPointerCast";
01628   case CK_AnyPointerToBlockPointerCast:
01629     return "AnyPointerToBlockPointerCast";
01630   case CK_ObjCObjectLValueCast:
01631     return "ObjCObjectLValueCast";
01632   case CK_FloatingRealToComplex:
01633     return "FloatingRealToComplex";
01634   case CK_FloatingComplexToReal:
01635     return "FloatingComplexToReal";
01636   case CK_FloatingComplexToBoolean:
01637     return "FloatingComplexToBoolean";
01638   case CK_FloatingComplexCast:
01639     return "FloatingComplexCast";
01640   case CK_FloatingComplexToIntegralComplex:
01641     return "FloatingComplexToIntegralComplex";
01642   case CK_IntegralRealToComplex:
01643     return "IntegralRealToComplex";
01644   case CK_IntegralComplexToReal:
01645     return "IntegralComplexToReal";
01646   case CK_IntegralComplexToBoolean:
01647     return "IntegralComplexToBoolean";
01648   case CK_IntegralComplexCast:
01649     return "IntegralComplexCast";
01650   case CK_IntegralComplexToFloatingComplex:
01651     return "IntegralComplexToFloatingComplex";
01652   case CK_ARCConsumeObject:
01653     return "ARCConsumeObject";
01654   case CK_ARCProduceObject:
01655     return "ARCProduceObject";
01656   case CK_ARCReclaimReturnedObject:
01657     return "ARCReclaimReturnedObject";
01658   case CK_ARCExtendBlockObject:
01659     return "ARCExtendBlockObject";
01660   case CK_AtomicToNonAtomic:
01661     return "AtomicToNonAtomic";
01662   case CK_NonAtomicToAtomic:
01663     return "NonAtomicToAtomic";
01664   case CK_CopyAndAutoreleaseBlockObject:
01665     return "CopyAndAutoreleaseBlockObject";
01666   case CK_BuiltinFnToFnPtr:
01667     return "BuiltinFnToFnPtr";
01668   case CK_ZeroToOCLEvent:
01669     return "ZeroToOCLEvent";
01670   case CK_AddressSpaceConversion:
01671     return "AddressSpaceConversion";
01672   }
01673 
01674   llvm_unreachable("Unhandled cast kind!");
01675 }
01676 
01677 Expr *CastExpr::getSubExprAsWritten() {
01678   Expr *SubExpr = nullptr;
01679   CastExpr *E = this;
01680   do {
01681     SubExpr = E->getSubExpr();
01682 
01683     // Skip through reference binding to temporary.
01684     if (MaterializeTemporaryExpr *Materialize 
01685                                   = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
01686       SubExpr = Materialize->GetTemporaryExpr();
01687         
01688     // Skip any temporary bindings; they're implicit.
01689     if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
01690       SubExpr = Binder->getSubExpr();
01691     
01692     // Conversions by constructor and conversion functions have a
01693     // subexpression describing the call; strip it off.
01694     if (E->getCastKind() == CK_ConstructorConversion)
01695       SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
01696     else if (E->getCastKind() == CK_UserDefinedConversion)
01697       SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
01698     
01699     // If the subexpression we're left with is an implicit cast, look
01700     // through that, too.
01701   } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));  
01702   
01703   return SubExpr;
01704 }
01705 
01706 CXXBaseSpecifier **CastExpr::path_buffer() {
01707   switch (getStmtClass()) {
01708 #define ABSTRACT_STMT(x)
01709 #define CASTEXPR(Type, Base) \
01710   case Stmt::Type##Class: \
01711     return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
01712 #define STMT(Type, Base)
01713 #include "clang/AST/StmtNodes.inc"
01714   default:
01715     llvm_unreachable("non-cast expressions not possible here");
01716   }
01717 }
01718 
01719 void CastExpr::setCastPath(const CXXCastPath &Path) {
01720   assert(Path.size() == path_size());
01721   memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
01722 }
01723 
01724 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
01725                                            CastKind Kind, Expr *Operand,
01726                                            const CXXCastPath *BasePath,
01727                                            ExprValueKind VK) {
01728   unsigned PathSize = (BasePath ? BasePath->size() : 0);
01729   void *Buffer =
01730     C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
01731   ImplicitCastExpr *E =
01732     new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
01733   if (PathSize) E->setCastPath(*BasePath);
01734   return E;
01735 }
01736 
01737 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
01738                                                 unsigned PathSize) {
01739   void *Buffer =
01740     C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
01741   return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
01742 }
01743 
01744 
01745 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
01746                                        ExprValueKind VK, CastKind K, Expr *Op,
01747                                        const CXXCastPath *BasePath,
01748                                        TypeSourceInfo *WrittenTy,
01749                                        SourceLocation L, SourceLocation R) {
01750   unsigned PathSize = (BasePath ? BasePath->size() : 0);
01751   void *Buffer =
01752     C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
01753   CStyleCastExpr *E =
01754     new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
01755   if (PathSize) E->setCastPath(*BasePath);
01756   return E;
01757 }
01758 
01759 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
01760                                             unsigned PathSize) {
01761   void *Buffer =
01762     C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
01763   return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
01764 }
01765 
01766 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
01767 /// corresponds to, e.g. "<<=".
01768 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
01769   switch (Op) {
01770   case BO_PtrMemD:   return ".*";
01771   case BO_PtrMemI:   return "->*";
01772   case BO_Mul:       return "*";
01773   case BO_Div:       return "/";
01774   case BO_Rem:       return "%";
01775   case BO_Add:       return "+";
01776   case BO_Sub:       return "-";
01777   case BO_Shl:       return "<<";
01778   case BO_Shr:       return ">>";
01779   case BO_LT:        return "<";
01780   case BO_GT:        return ">";
01781   case BO_LE:        return "<=";
01782   case BO_GE:        return ">=";
01783   case BO_EQ:        return "==";
01784   case BO_NE:        return "!=";
01785   case BO_And:       return "&";
01786   case BO_Xor:       return "^";
01787   case BO_Or:        return "|";
01788   case BO_LAnd:      return "&&";
01789   case BO_LOr:       return "||";
01790   case BO_Assign:    return "=";
01791   case BO_MulAssign: return "*=";
01792   case BO_DivAssign: return "/=";
01793   case BO_RemAssign: return "%=";
01794   case BO_AddAssign: return "+=";
01795   case BO_SubAssign: return "-=";
01796   case BO_ShlAssign: return "<<=";
01797   case BO_ShrAssign: return ">>=";
01798   case BO_AndAssign: return "&=";
01799   case BO_XorAssign: return "^=";
01800   case BO_OrAssign:  return "|=";
01801   case BO_Comma:     return ",";
01802   }
01803 
01804   llvm_unreachable("Invalid OpCode!");
01805 }
01806 
01807 BinaryOperatorKind
01808 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
01809   switch (OO) {
01810   default: llvm_unreachable("Not an overloadable binary operator");
01811   case OO_Plus: return BO_Add;
01812   case OO_Minus: return BO_Sub;
01813   case OO_Star: return BO_Mul;
01814   case OO_Slash: return BO_Div;
01815   case OO_Percent: return BO_Rem;
01816   case OO_Caret: return BO_Xor;
01817   case OO_Amp: return BO_And;
01818   case OO_Pipe: return BO_Or;
01819   case OO_Equal: return BO_Assign;
01820   case OO_Less: return BO_LT;
01821   case OO_Greater: return BO_GT;
01822   case OO_PlusEqual: return BO_AddAssign;
01823   case OO_MinusEqual: return BO_SubAssign;
01824   case OO_StarEqual: return BO_MulAssign;
01825   case OO_SlashEqual: return BO_DivAssign;
01826   case OO_PercentEqual: return BO_RemAssign;
01827   case OO_CaretEqual: return BO_XorAssign;
01828   case OO_AmpEqual: return BO_AndAssign;
01829   case OO_PipeEqual: return BO_OrAssign;
01830   case OO_LessLess: return BO_Shl;
01831   case OO_GreaterGreater: return BO_Shr;
01832   case OO_LessLessEqual: return BO_ShlAssign;
01833   case OO_GreaterGreaterEqual: return BO_ShrAssign;
01834   case OO_EqualEqual: return BO_EQ;
01835   case OO_ExclaimEqual: return BO_NE;
01836   case OO_LessEqual: return BO_LE;
01837   case OO_GreaterEqual: return BO_GE;
01838   case OO_AmpAmp: return BO_LAnd;
01839   case OO_PipePipe: return BO_LOr;
01840   case OO_Comma: return BO_Comma;
01841   case OO_ArrowStar: return BO_PtrMemI;
01842   }
01843 }
01844 
01845 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
01846   static const OverloadedOperatorKind OverOps[] = {
01847     /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
01848     OO_Star, OO_Slash, OO_Percent,
01849     OO_Plus, OO_Minus,
01850     OO_LessLess, OO_GreaterGreater,
01851     OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
01852     OO_EqualEqual, OO_ExclaimEqual,
01853     OO_Amp,
01854     OO_Caret,
01855     OO_Pipe,
01856     OO_AmpAmp,
01857     OO_PipePipe,
01858     OO_Equal, OO_StarEqual,
01859     OO_SlashEqual, OO_PercentEqual,
01860     OO_PlusEqual, OO_MinusEqual,
01861     OO_LessLessEqual, OO_GreaterGreaterEqual,
01862     OO_AmpEqual, OO_CaretEqual,
01863     OO_PipeEqual,
01864     OO_Comma
01865   };
01866   return OverOps[Opc];
01867 }
01868 
01869 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
01870                            ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
01871   : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
01872          false, false),
01873     InitExprs(C, initExprs.size()),
01874     LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
01875 {
01876   sawArrayRangeDesignator(false);
01877   for (unsigned I = 0; I != initExprs.size(); ++I) {
01878     if (initExprs[I]->isTypeDependent())
01879       ExprBits.TypeDependent = true;
01880     if (initExprs[I]->isValueDependent())
01881       ExprBits.ValueDependent = true;
01882     if (initExprs[I]->isInstantiationDependent())
01883       ExprBits.InstantiationDependent = true;
01884     if (initExprs[I]->containsUnexpandedParameterPack())
01885       ExprBits.ContainsUnexpandedParameterPack = true;
01886   }
01887       
01888   InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
01889 }
01890 
01891 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
01892   if (NumInits > InitExprs.size())
01893     InitExprs.reserve(C, NumInits);
01894 }
01895 
01896 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
01897   InitExprs.resize(C, NumInits, nullptr);
01898 }
01899 
01900 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
01901   if (Init >= InitExprs.size()) {
01902     InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
01903     setInit(Init, expr);
01904     return nullptr;
01905   }
01906 
01907   Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
01908   setInit(Init, expr);
01909   return Result;
01910 }
01911 
01912 void InitListExpr::setArrayFiller(Expr *filler) {
01913   assert(!hasArrayFiller() && "Filler already set!");
01914   ArrayFillerOrUnionFieldInit = filler;
01915   // Fill out any "holes" in the array due to designated initializers.
01916   Expr **inits = getInits();
01917   for (unsigned i = 0, e = getNumInits(); i != e; ++i)
01918     if (inits[i] == nullptr)
01919       inits[i] = filler;
01920 }
01921 
01922 bool InitListExpr::isStringLiteralInit() const {
01923   if (getNumInits() != 1)
01924     return false;
01925   const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
01926   if (!AT || !AT->getElementType()->isIntegerType())
01927     return false;
01928   // It is possible for getInit() to return null.
01929   const Expr *Init = getInit(0);
01930   if (!Init)
01931     return false;
01932   Init = Init->IgnoreParens();
01933   return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
01934 }
01935 
01936 SourceLocation InitListExpr::getLocStart() const {
01937   if (InitListExpr *SyntacticForm = getSyntacticForm())
01938     return SyntacticForm->getLocStart();
01939   SourceLocation Beg = LBraceLoc;
01940   if (Beg.isInvalid()) {
01941     // Find the first non-null initializer.
01942     for (InitExprsTy::const_iterator I = InitExprs.begin(),
01943                                      E = InitExprs.end(); 
01944       I != E; ++I) {
01945       if (Stmt *S = *I) {
01946         Beg = S->getLocStart();
01947         break;
01948       }  
01949     }
01950   }
01951   return Beg;
01952 }
01953 
01954 SourceLocation InitListExpr::getLocEnd() const {
01955   if (InitListExpr *SyntacticForm = getSyntacticForm())
01956     return SyntacticForm->getLocEnd();
01957   SourceLocation End = RBraceLoc;
01958   if (End.isInvalid()) {
01959     // Find the first non-null initializer from the end.
01960     for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
01961          E = InitExprs.rend();
01962          I != E; ++I) {
01963       if (Stmt *S = *I) {
01964         End = S->getLocEnd();
01965         break;
01966       }
01967     }
01968   }
01969   return End;
01970 }
01971 
01972 /// getFunctionType - Return the underlying function type for this block.
01973 ///
01974 const FunctionProtoType *BlockExpr::getFunctionType() const {
01975   // The block pointer is never sugared, but the function type might be.
01976   return cast<BlockPointerType>(getType())
01977            ->getPointeeType()->castAs<FunctionProtoType>();
01978 }
01979 
01980 SourceLocation BlockExpr::getCaretLocation() const {
01981   return TheBlock->getCaretLocation();
01982 }
01983 const Stmt *BlockExpr::getBody() const {
01984   return TheBlock->getBody();
01985 }
01986 Stmt *BlockExpr::getBody() {
01987   return TheBlock->getBody();
01988 }
01989 
01990 
01991 //===----------------------------------------------------------------------===//
01992 // Generic Expression Routines
01993 //===----------------------------------------------------------------------===//
01994 
01995 /// isUnusedResultAWarning - Return true if this immediate expression should
01996 /// be warned about if the result is unused.  If so, fill in Loc and Ranges
01997 /// with location to warn on and the source range[s] to report with the
01998 /// warning.
01999 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, 
02000                                   SourceRange &R1, SourceRange &R2,
02001                                   ASTContext &Ctx) const {
02002   // Don't warn if the expr is type dependent. The type could end up
02003   // instantiating to void.
02004   if (isTypeDependent())
02005     return false;
02006 
02007   switch (getStmtClass()) {
02008   default:
02009     if (getType()->isVoidType())
02010       return false;
02011     WarnE = this;
02012     Loc = getExprLoc();
02013     R1 = getSourceRange();
02014     return true;
02015   case ParenExprClass:
02016     return cast<ParenExpr>(this)->getSubExpr()->
02017       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02018   case GenericSelectionExprClass:
02019     return cast<GenericSelectionExpr>(this)->getResultExpr()->
02020       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02021   case ChooseExprClass:
02022     return cast<ChooseExpr>(this)->getChosenSubExpr()->
02023       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02024   case UnaryOperatorClass: {
02025     const UnaryOperator *UO = cast<UnaryOperator>(this);
02026 
02027     switch (UO->getOpcode()) {
02028     case UO_Plus:
02029     case UO_Minus:
02030     case UO_AddrOf:
02031     case UO_Not:
02032     case UO_LNot:
02033     case UO_Deref:
02034       break;
02035     case UO_PostInc:
02036     case UO_PostDec:
02037     case UO_PreInc:
02038     case UO_PreDec:                 // ++/--
02039       return false;  // Not a warning.
02040     case UO_Real:
02041     case UO_Imag:
02042       // accessing a piece of a volatile complex is a side-effect.
02043       if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
02044           .isVolatileQualified())
02045         return false;
02046       break;
02047     case UO_Extension:
02048       return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02049     }
02050     WarnE = this;
02051     Loc = UO->getOperatorLoc();
02052     R1 = UO->getSubExpr()->getSourceRange();
02053     return true;
02054   }
02055   case BinaryOperatorClass: {
02056     const BinaryOperator *BO = cast<BinaryOperator>(this);
02057     switch (BO->getOpcode()) {
02058       default:
02059         break;
02060       // Consider the RHS of comma for side effects. LHS was checked by
02061       // Sema::CheckCommaOperands.
02062       case BO_Comma:
02063         // ((foo = <blah>), 0) is an idiom for hiding the result (and
02064         // lvalue-ness) of an assignment written in a macro.
02065         if (IntegerLiteral *IE =
02066               dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
02067           if (IE->getValue() == 0)
02068             return false;
02069         return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02070       // Consider '||', '&&' to have side effects if the LHS or RHS does.
02071       case BO_LAnd:
02072       case BO_LOr:
02073         if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
02074             !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
02075           return false;
02076         break;
02077     }
02078     if (BO->isAssignmentOp())
02079       return false;
02080     WarnE = this;
02081     Loc = BO->getOperatorLoc();
02082     R1 = BO->getLHS()->getSourceRange();
02083     R2 = BO->getRHS()->getSourceRange();
02084     return true;
02085   }
02086   case CompoundAssignOperatorClass:
02087   case VAArgExprClass:
02088   case AtomicExprClass:
02089     return false;
02090 
02091   case ConditionalOperatorClass: {
02092     // If only one of the LHS or RHS is a warning, the operator might
02093     // be being used for control flow. Only warn if both the LHS and
02094     // RHS are warnings.
02095     const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
02096     if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
02097       return false;
02098     if (!Exp->getLHS())
02099       return true;
02100     return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02101   }
02102 
02103   case MemberExprClass:
02104     WarnE = this;
02105     Loc = cast<MemberExpr>(this)->getMemberLoc();
02106     R1 = SourceRange(Loc, Loc);
02107     R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
02108     return true;
02109 
02110   case ArraySubscriptExprClass:
02111     WarnE = this;
02112     Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
02113     R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
02114     R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
02115     return true;
02116 
02117   case CXXOperatorCallExprClass: {
02118     // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
02119     // overloads as there is no reasonable way to define these such that they
02120     // have non-trivial, desirable side-effects. See the -Wunused-comparison
02121     // warning: operators == and != are commonly typo'ed, and so warning on them
02122     // provides additional value as well. If this list is updated,
02123     // DiagnoseUnusedComparison should be as well.
02124     const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
02125     switch (Op->getOperator()) {
02126     default:
02127       break;
02128     case OO_EqualEqual:
02129     case OO_ExclaimEqual:
02130     case OO_Less:
02131     case OO_Greater:
02132     case OO_GreaterEqual:
02133     case OO_LessEqual:
02134       if (Op->getCallReturnType()->isReferenceType() ||
02135           Op->getCallReturnType()->isVoidType())
02136         break;
02137       WarnE = this;
02138       Loc = Op->getOperatorLoc();
02139       R1 = Op->getSourceRange();
02140       return true;
02141     }
02142 
02143     // Fallthrough for generic call handling.
02144   }
02145   case CallExprClass:
02146   case CXXMemberCallExprClass:
02147   case UserDefinedLiteralClass: {
02148     // If this is a direct call, get the callee.
02149     const CallExpr *CE = cast<CallExpr>(this);
02150     if (const Decl *FD = CE->getCalleeDecl()) {
02151       // If the callee has attribute pure, const, or warn_unused_result, warn
02152       // about it. void foo() { strlen("bar"); } should warn.
02153       //
02154       // Note: If new cases are added here, DiagnoseUnusedExprResult should be
02155       // updated to match for QoI.
02156       if (FD->hasAttr<WarnUnusedResultAttr>() ||
02157           FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
02158         WarnE = this;
02159         Loc = CE->getCallee()->getLocStart();
02160         R1 = CE->getCallee()->getSourceRange();
02161 
02162         if (unsigned NumArgs = CE->getNumArgs())
02163           R2 = SourceRange(CE->getArg(0)->getLocStart(),
02164                            CE->getArg(NumArgs-1)->getLocEnd());
02165         return true;
02166       }
02167     }
02168     return false;
02169   }
02170 
02171   // If we don't know precisely what we're looking at, let's not warn.
02172   case UnresolvedLookupExprClass:
02173   case CXXUnresolvedConstructExprClass:
02174     return false;
02175 
02176   case CXXTemporaryObjectExprClass:
02177   case CXXConstructExprClass: {
02178     if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
02179       if (Type->hasAttr<WarnUnusedAttr>()) {
02180         WarnE = this;
02181         Loc = getLocStart();
02182         R1 = getSourceRange();
02183         return true;
02184       }
02185     }
02186     return false;
02187   }
02188 
02189   case ObjCMessageExprClass: {
02190     const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
02191     if (Ctx.getLangOpts().ObjCAutoRefCount &&
02192         ME->isInstanceMessage() &&
02193         !ME->getType()->isVoidType() &&
02194         ME->getMethodFamily() == OMF_init) {
02195       WarnE = this;
02196       Loc = getExprLoc();
02197       R1 = ME->getSourceRange();
02198       return true;
02199     }
02200 
02201     if (const ObjCMethodDecl *MD = ME->getMethodDecl())
02202       if (MD->hasAttr<WarnUnusedResultAttr>() ||
02203           (MD->isPropertyAccessor() && !MD->getReturnType()->isVoidType() &&
02204            !ME->getReceiverType()->isObjCIdType())) {
02205         WarnE = this;
02206         Loc = getExprLoc();
02207         return true;
02208       }
02209 
02210     return false;
02211   }
02212 
02213   case ObjCPropertyRefExprClass:
02214     WarnE = this;
02215     Loc = getExprLoc();
02216     R1 = getSourceRange();
02217     return true;
02218 
02219   case PseudoObjectExprClass: {
02220     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
02221 
02222     // Only complain about things that have the form of a getter.
02223     if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
02224         isa<BinaryOperator>(PO->getSyntacticForm()))
02225       return false;
02226 
02227     WarnE = this;
02228     Loc = getExprLoc();
02229     R1 = getSourceRange();
02230     return true;
02231   }
02232 
02233   case StmtExprClass: {
02234     // Statement exprs don't logically have side effects themselves, but are
02235     // sometimes used in macros in ways that give them a type that is unused.
02236     // For example ({ blah; foo(); }) will end up with a type if foo has a type.
02237     // however, if the result of the stmt expr is dead, we don't want to emit a
02238     // warning.
02239     const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
02240     if (!CS->body_empty()) {
02241       if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
02242         return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02243       if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
02244         if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
02245           return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02246     }
02247 
02248     if (getType()->isVoidType())
02249       return false;
02250     WarnE = this;
02251     Loc = cast<StmtExpr>(this)->getLParenLoc();
02252     R1 = getSourceRange();
02253     return true;
02254   }
02255   case CXXFunctionalCastExprClass:
02256   case CStyleCastExprClass: {
02257     // Ignore an explicit cast to void unless the operand is a non-trivial
02258     // volatile lvalue.
02259     const CastExpr *CE = cast<CastExpr>(this);
02260     if (CE->getCastKind() == CK_ToVoid) {
02261       if (CE->getSubExpr()->isGLValue() &&
02262           CE->getSubExpr()->getType().isVolatileQualified()) {
02263         const DeclRefExpr *DRE =
02264             dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
02265         if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
02266               cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
02267           return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
02268                                                           R1, R2, Ctx);
02269         }
02270       }
02271       return false;
02272     }
02273 
02274     // If this is a cast to a constructor conversion, check the operand.
02275     // Otherwise, the result of the cast is unused.
02276     if (CE->getCastKind() == CK_ConstructorConversion)
02277       return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02278 
02279     WarnE = this;
02280     if (const CXXFunctionalCastExpr *CXXCE =
02281             dyn_cast<CXXFunctionalCastExpr>(this)) {
02282       Loc = CXXCE->getLocStart();
02283       R1 = CXXCE->getSubExpr()->getSourceRange();
02284     } else {
02285       const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
02286       Loc = CStyleCE->getLParenLoc();
02287       R1 = CStyleCE->getSubExpr()->getSourceRange();
02288     }
02289     return true;
02290   }
02291   case ImplicitCastExprClass: {
02292     const CastExpr *ICE = cast<ImplicitCastExpr>(this);
02293 
02294     // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
02295     if (ICE->getCastKind() == CK_LValueToRValue &&
02296         ICE->getSubExpr()->getType().isVolatileQualified())
02297       return false;
02298 
02299     return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
02300   }
02301   case CXXDefaultArgExprClass:
02302     return (cast<CXXDefaultArgExpr>(this)
02303             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
02304   case CXXDefaultInitExprClass:
02305     return (cast<CXXDefaultInitExpr>(this)
02306             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
02307 
02308   case CXXNewExprClass:
02309     // FIXME: In theory, there might be new expressions that don't have side
02310     // effects (e.g. a placement new with an uninitialized POD).
02311   case CXXDeleteExprClass:
02312     return false;
02313   case CXXBindTemporaryExprClass:
02314     return (cast<CXXBindTemporaryExpr>(this)
02315             ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
02316   case ExprWithCleanupsClass:
02317     return (cast<ExprWithCleanups>(this)
02318             ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
02319   }
02320 }
02321 
02322 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
02323 /// returns true, if it is; false otherwise.
02324 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
02325   const Expr *E = IgnoreParens();
02326   switch (E->getStmtClass()) {
02327   default:
02328     return false;
02329   case ObjCIvarRefExprClass:
02330     return true;
02331   case Expr::UnaryOperatorClass:
02332     return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
02333   case ImplicitCastExprClass:
02334     return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
02335   case MaterializeTemporaryExprClass:
02336     return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
02337                                                       ->isOBJCGCCandidate(Ctx);
02338   case CStyleCastExprClass:
02339     return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
02340   case DeclRefExprClass: {
02341     const Decl *D = cast<DeclRefExpr>(E)->getDecl();
02342         
02343     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
02344       if (VD->hasGlobalStorage())
02345         return true;
02346       QualType T = VD->getType();
02347       // dereferencing to a  pointer is always a gc'able candidate,
02348       // unless it is __weak.
02349       return T->isPointerType() &&
02350              (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
02351     }
02352     return false;
02353   }
02354   case MemberExprClass: {
02355     const MemberExpr *M = cast<MemberExpr>(E);
02356     return M->getBase()->isOBJCGCCandidate(Ctx);
02357   }
02358   case ArraySubscriptExprClass:
02359     return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
02360   }
02361 }
02362 
02363 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
02364   if (isTypeDependent())
02365     return false;
02366   return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
02367 }
02368 
02369 QualType Expr::findBoundMemberType(const Expr *expr) {
02370   assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
02371 
02372   // Bound member expressions are always one of these possibilities:
02373   //   x->m      x.m      x->*y      x.*y
02374   // (possibly parenthesized)
02375 
02376   expr = expr->IgnoreParens();
02377   if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
02378     assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
02379     return mem->getMemberDecl()->getType();
02380   }
02381 
02382   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
02383     QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
02384                       ->getPointeeType();
02385     assert(type->isFunctionType());
02386     return type;
02387   }
02388 
02389   assert(isa<UnresolvedMemberExpr>(expr));
02390   return QualType();
02391 }
02392 
02393 Expr* Expr::IgnoreParens() {
02394   Expr* E = this;
02395   while (true) {
02396     if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
02397       E = P->getSubExpr();
02398       continue;
02399     }
02400     if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
02401       if (P->getOpcode() == UO_Extension) {
02402         E = P->getSubExpr();
02403         continue;
02404       }
02405     }
02406     if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
02407       if (!P->isResultDependent()) {
02408         E = P->getResultExpr();
02409         continue;
02410       }
02411     }
02412     if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
02413       if (!P->isConditionDependent()) {
02414         E = P->getChosenSubExpr();
02415         continue;
02416       }
02417     }
02418     return E;
02419   }
02420 }
02421 
02422 /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
02423 /// or CastExprs or ImplicitCastExprs, returning their operand.
02424 Expr *Expr::IgnoreParenCasts() {
02425   Expr *E = this;
02426   while (true) {
02427     E = E->IgnoreParens();
02428     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
02429       E = P->getSubExpr();
02430       continue;
02431     }
02432     if (MaterializeTemporaryExpr *Materialize 
02433                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
02434       E = Materialize->GetTemporaryExpr();
02435       continue;
02436     }
02437     if (SubstNonTypeTemplateParmExpr *NTTP
02438                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
02439       E = NTTP->getReplacement();
02440       continue;
02441     }      
02442     return E;
02443   }
02444 }
02445 
02446 Expr *Expr::IgnoreCasts() {
02447   Expr *E = this;
02448   while (true) {
02449     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
02450       E = P->getSubExpr();
02451       continue;
02452     }
02453     if (MaterializeTemporaryExpr *Materialize
02454         = dyn_cast<MaterializeTemporaryExpr>(E)) {
02455       E = Materialize->GetTemporaryExpr();
02456       continue;
02457     }
02458     if (SubstNonTypeTemplateParmExpr *NTTP
02459         = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
02460       E = NTTP->getReplacement();
02461       continue;
02462     }
02463     return E;
02464   }
02465 }
02466 
02467 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
02468 /// casts.  This is intended purely as a temporary workaround for code
02469 /// that hasn't yet been rewritten to do the right thing about those
02470 /// casts, and may disappear along with the last internal use.
02471 Expr *Expr::IgnoreParenLValueCasts() {
02472   Expr *E = this;
02473   while (true) {
02474     E = E->IgnoreParens();
02475     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
02476       if (P->getCastKind() == CK_LValueToRValue) {
02477         E = P->getSubExpr();
02478         continue;
02479       }
02480     } else if (MaterializeTemporaryExpr *Materialize 
02481                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
02482       E = Materialize->GetTemporaryExpr();
02483       continue;
02484     } else if (SubstNonTypeTemplateParmExpr *NTTP
02485                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
02486       E = NTTP->getReplacement();
02487       continue;
02488     }
02489     break;
02490   }
02491   return E;
02492 }
02493 
02494 Expr *Expr::ignoreParenBaseCasts() {
02495   Expr *E = this;
02496   while (true) {
02497     E = E->IgnoreParens();
02498     if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
02499       if (CE->getCastKind() == CK_DerivedToBase ||
02500           CE->getCastKind() == CK_UncheckedDerivedToBase ||
02501           CE->getCastKind() == CK_NoOp) {
02502         E = CE->getSubExpr();
02503         continue;
02504       }
02505     }
02506 
02507     return E;
02508   }
02509 }
02510 
02511 Expr *Expr::IgnoreParenImpCasts() {
02512   Expr *E = this;
02513   while (true) {
02514     E = E->IgnoreParens();
02515     if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
02516       E = P->getSubExpr();
02517       continue;
02518     }
02519     if (MaterializeTemporaryExpr *Materialize 
02520                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
02521       E = Materialize->GetTemporaryExpr();
02522       continue;
02523     }
02524     if (SubstNonTypeTemplateParmExpr *NTTP
02525                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
02526       E = NTTP->getReplacement();
02527       continue;
02528     }
02529     return E;
02530   }
02531 }
02532 
02533 Expr *Expr::IgnoreConversionOperator() {
02534   if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
02535     if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
02536       return MCE->getImplicitObjectArgument();
02537   }
02538   return this;
02539 }
02540 
02541 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
02542 /// value (including ptr->int casts of the same size).  Strip off any
02543 /// ParenExpr or CastExprs, returning their operand.
02544 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
02545   Expr *E = this;
02546   while (true) {
02547     E = E->IgnoreParens();
02548 
02549     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
02550       // We ignore integer <-> casts that are of the same width, ptr<->ptr and
02551       // ptr<->int casts of the same width.  We also ignore all identity casts.
02552       Expr *SE = P->getSubExpr();
02553 
02554       if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
02555         E = SE;
02556         continue;
02557       }
02558 
02559       if ((E->getType()->isPointerType() ||
02560            E->getType()->isIntegralType(Ctx)) &&
02561           (SE->getType()->isPointerType() ||
02562            SE->getType()->isIntegralType(Ctx)) &&
02563           Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
02564         E = SE;
02565         continue;
02566       }
02567     }
02568 
02569     if (SubstNonTypeTemplateParmExpr *NTTP
02570                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
02571       E = NTTP->getReplacement();
02572       continue;
02573     }
02574     
02575     return E;
02576   }
02577 }
02578 
02579 bool Expr::isDefaultArgument() const {
02580   const Expr *E = this;
02581   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
02582     E = M->GetTemporaryExpr();
02583 
02584   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
02585     E = ICE->getSubExprAsWritten();
02586   
02587   return isa<CXXDefaultArgExpr>(E);
02588 }
02589 
02590 /// \brief Skip over any no-op casts and any temporary-binding
02591 /// expressions.
02592 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
02593   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
02594     E = M->GetTemporaryExpr();
02595 
02596   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
02597     if (ICE->getCastKind() == CK_NoOp)
02598       E = ICE->getSubExpr();
02599     else
02600       break;
02601   }
02602 
02603   while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
02604     E = BE->getSubExpr();
02605 
02606   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
02607     if (ICE->getCastKind() == CK_NoOp)
02608       E = ICE->getSubExpr();
02609     else
02610       break;
02611   }
02612 
02613   return E->IgnoreParens();
02614 }
02615 
02616 /// isTemporaryObject - Determines if this expression produces a
02617 /// temporary of the given class type.
02618 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
02619   if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
02620     return false;
02621 
02622   const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
02623 
02624   // Temporaries are by definition pr-values of class type.
02625   if (!E->Classify(C).isPRValue()) {
02626     // In this context, property reference is a message call and is pr-value.
02627     if (!isa<ObjCPropertyRefExpr>(E))
02628       return false;
02629   }
02630 
02631   // Black-list a few cases which yield pr-values of class type that don't
02632   // refer to temporaries of that type:
02633 
02634   // - implicit derived-to-base conversions
02635   if (isa<ImplicitCastExpr>(E)) {
02636     switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
02637     case CK_DerivedToBase:
02638     case CK_UncheckedDerivedToBase:
02639       return false;
02640     default:
02641       break;
02642     }
02643   }
02644 
02645   // - member expressions (all)
02646   if (isa<MemberExpr>(E))
02647     return false;
02648 
02649   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
02650     if (BO->isPtrMemOp())
02651       return false;
02652 
02653   // - opaque values (all)
02654   if (isa<OpaqueValueExpr>(E))
02655     return false;
02656 
02657   return true;
02658 }
02659 
02660 bool Expr::isImplicitCXXThis() const {
02661   const Expr *E = this;
02662   
02663   // Strip away parentheses and casts we don't care about.
02664   while (true) {
02665     if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
02666       E = Paren->getSubExpr();
02667       continue;
02668     }
02669     
02670     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
02671       if (ICE->getCastKind() == CK_NoOp ||
02672           ICE->getCastKind() == CK_LValueToRValue ||
02673           ICE->getCastKind() == CK_DerivedToBase || 
02674           ICE->getCastKind() == CK_UncheckedDerivedToBase) {
02675         E = ICE->getSubExpr();
02676         continue;
02677       }
02678     }
02679     
02680     if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
02681       if (UnOp->getOpcode() == UO_Extension) {
02682         E = UnOp->getSubExpr();
02683         continue;
02684       }
02685     }
02686     
02687     if (const MaterializeTemporaryExpr *M
02688                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
02689       E = M->GetTemporaryExpr();
02690       continue;
02691     }
02692     
02693     break;
02694   }
02695   
02696   if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
02697     return This->isImplicit();
02698   
02699   return false;
02700 }
02701 
02702 /// hasAnyTypeDependentArguments - Determines if any of the expressions
02703 /// in Exprs is type-dependent.
02704 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
02705   for (unsigned I = 0; I < Exprs.size(); ++I)
02706     if (Exprs[I]->isTypeDependent())
02707       return true;
02708 
02709   return false;
02710 }
02711 
02712 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
02713                                  const Expr **Culprit) const {
02714   // This function is attempting whether an expression is an initializer
02715   // which can be evaluated at compile-time. It very closely parallels
02716   // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
02717   // will lead to unexpected results.  Like ConstExprEmitter, it falls back
02718   // to isEvaluatable most of the time.
02719   //
02720   // If we ever capture reference-binding directly in the AST, we can
02721   // kill the second parameter.
02722 
02723   if (IsForRef) {
02724     EvalResult Result;
02725     if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
02726       return true;
02727     if (Culprit)
02728       *Culprit = this;
02729     return false;
02730   }
02731 
02732   switch (getStmtClass()) {
02733   default: break;
02734   case StringLiteralClass:
02735   case ObjCEncodeExprClass:
02736     return true;
02737   case CXXTemporaryObjectExprClass:
02738   case CXXConstructExprClass: {
02739     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
02740 
02741     if (CE->getConstructor()->isTrivial() &&
02742         CE->getConstructor()->getParent()->hasTrivialDestructor()) {
02743       // Trivial default constructor
02744       if (!CE->getNumArgs()) return true;
02745 
02746       // Trivial copy constructor
02747       assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
02748       return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
02749     }
02750 
02751     break;
02752   }
02753   case CompoundLiteralExprClass: {
02754     // This handles gcc's extension that allows global initializers like
02755     // "struct x {int x;} x = (struct x) {};".
02756     // FIXME: This accepts other cases it shouldn't!
02757     const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
02758     return Exp->isConstantInitializer(Ctx, false, Culprit);
02759   }
02760   case InitListExprClass: {
02761     const InitListExpr *ILE = cast<InitListExpr>(this);
02762     if (ILE->getType()->isArrayType()) {
02763       unsigned numInits = ILE->getNumInits();
02764       for (unsigned i = 0; i < numInits; i++) {
02765         if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
02766           return false;
02767       }
02768       return true;
02769     }
02770 
02771     if (ILE->getType()->isRecordType()) {
02772       unsigned ElementNo = 0;
02773       RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
02774       for (const auto *Field : RD->fields()) {
02775         // If this is a union, skip all the fields that aren't being initialized.
02776         if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
02777           continue;
02778 
02779         // Don't emit anonymous bitfields, they just affect layout.
02780         if (Field->isUnnamedBitfield())
02781           continue;
02782 
02783         if (ElementNo < ILE->getNumInits()) {
02784           const Expr *Elt = ILE->getInit(ElementNo++);
02785           if (Field->isBitField()) {
02786             // Bitfields have to evaluate to an integer.
02787             llvm::APSInt ResultTmp;
02788             if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
02789               if (Culprit)
02790                 *Culprit = Elt;
02791               return false;
02792             }
02793           } else {
02794             bool RefType = Field->getType()->isReferenceType();
02795             if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
02796               return false;
02797           }
02798         }
02799       }
02800       return true;
02801     }
02802 
02803     break;
02804   }
02805   case ImplicitValueInitExprClass:
02806     return true;
02807   case ParenExprClass:
02808     return cast<ParenExpr>(this)->getSubExpr()
02809       ->isConstantInitializer(Ctx, IsForRef, Culprit);
02810   case GenericSelectionExprClass:
02811     return cast<GenericSelectionExpr>(this)->getResultExpr()
02812       ->isConstantInitializer(Ctx, IsForRef, Culprit);
02813   case ChooseExprClass:
02814     if (cast<ChooseExpr>(this)->isConditionDependent()) {
02815       if (Culprit)
02816         *Culprit = this;
02817       return false;
02818     }
02819     return cast<ChooseExpr>(this)->getChosenSubExpr()
02820       ->isConstantInitializer(Ctx, IsForRef, Culprit);
02821   case UnaryOperatorClass: {
02822     const UnaryOperator* Exp = cast<UnaryOperator>(this);
02823     if (Exp->getOpcode() == UO_Extension)
02824       return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
02825     break;
02826   }
02827   case CXXFunctionalCastExprClass:
02828   case CXXStaticCastExprClass:
02829   case ImplicitCastExprClass:
02830   case CStyleCastExprClass:
02831   case ObjCBridgedCastExprClass:
02832   case CXXDynamicCastExprClass:
02833   case CXXReinterpretCastExprClass:
02834   case CXXConstCastExprClass: {
02835     const CastExpr *CE = cast<CastExpr>(this);
02836 
02837     // Handle misc casts we want to ignore.
02838     if (CE->getCastKind() == CK_NoOp ||
02839         CE->getCastKind() == CK_LValueToRValue ||
02840         CE->getCastKind() == CK_ToUnion ||
02841         CE->getCastKind() == CK_ConstructorConversion ||
02842         CE->getCastKind() == CK_NonAtomicToAtomic ||
02843         CE->getCastKind() == CK_AtomicToNonAtomic)
02844       return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
02845 
02846     break;
02847   }
02848   case MaterializeTemporaryExprClass:
02849     return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
02850       ->isConstantInitializer(Ctx, false, Culprit);
02851 
02852   case SubstNonTypeTemplateParmExprClass:
02853     return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
02854       ->isConstantInitializer(Ctx, false, Culprit);
02855   case CXXDefaultArgExprClass:
02856     return cast<CXXDefaultArgExpr>(this)->getExpr()
02857       ->isConstantInitializer(Ctx, false, Culprit);
02858   case CXXDefaultInitExprClass:
02859     return cast<CXXDefaultInitExpr>(this)->getExpr()
02860       ->isConstantInitializer(Ctx, false, Culprit);
02861   }
02862   if (isEvaluatable(Ctx))
02863     return true;
02864   if (Culprit)
02865     *Culprit = this;
02866   return false;
02867 }
02868 
02869 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
02870   if (isInstantiationDependent())
02871     return true;
02872 
02873   switch (getStmtClass()) {
02874   case NoStmtClass:
02875   #define ABSTRACT_STMT(Type)
02876   #define STMT(Type, Base) case Type##Class:
02877   #define EXPR(Type, Base)
02878   #include "clang/AST/StmtNodes.inc"
02879     llvm_unreachable("unexpected Expr kind");
02880 
02881   case DependentScopeDeclRefExprClass:
02882   case CXXUnresolvedConstructExprClass:
02883   case CXXDependentScopeMemberExprClass:
02884   case UnresolvedLookupExprClass:
02885   case UnresolvedMemberExprClass:
02886   case PackExpansionExprClass:
02887   case SubstNonTypeTemplateParmPackExprClass:
02888   case FunctionParmPackExprClass:
02889   case TypoExprClass:
02890   case CXXFoldExprClass:
02891     llvm_unreachable("shouldn't see dependent / unresolved nodes here");
02892 
02893   case DeclRefExprClass:
02894   case ObjCIvarRefExprClass:
02895   case PredefinedExprClass:
02896   case IntegerLiteralClass:
02897   case FloatingLiteralClass:
02898   case ImaginaryLiteralClass:
02899   case StringLiteralClass:
02900   case CharacterLiteralClass:
02901   case OffsetOfExprClass:
02902   case ImplicitValueInitExprClass:
02903   case UnaryExprOrTypeTraitExprClass:
02904   case AddrLabelExprClass:
02905   case GNUNullExprClass:
02906   case CXXBoolLiteralExprClass:
02907   case CXXNullPtrLiteralExprClass:
02908   case CXXThisExprClass:
02909   case CXXScalarValueInitExprClass:
02910   case TypeTraitExprClass:
02911   case ArrayTypeTraitExprClass:
02912   case ExpressionTraitExprClass:
02913   case CXXNoexceptExprClass:
02914   case SizeOfPackExprClass:
02915   case ObjCStringLiteralClass:
02916   case ObjCEncodeExprClass:
02917   case ObjCBoolLiteralExprClass:
02918   case CXXUuidofExprClass:
02919   case OpaqueValueExprClass:
02920     // These never have a side-effect.
02921     return false;
02922 
02923   case CallExprClass:
02924   case MSPropertyRefExprClass:
02925   case CompoundAssignOperatorClass:
02926   case VAArgExprClass:
02927   case AtomicExprClass:
02928   case StmtExprClass:
02929   case CXXOperatorCallExprClass:
02930   case CXXMemberCallExprClass:
02931   case UserDefinedLiteralClass:
02932   case CXXThrowExprClass:
02933   case CXXNewExprClass:
02934   case CXXDeleteExprClass:
02935   case ExprWithCleanupsClass:
02936   case CXXBindTemporaryExprClass:
02937   case BlockExprClass:
02938   case CUDAKernelCallExprClass:
02939     // These always have a side-effect.
02940     return true;
02941 
02942   case ParenExprClass:
02943   case ArraySubscriptExprClass:
02944   case MemberExprClass:
02945   case ConditionalOperatorClass:
02946   case BinaryConditionalOperatorClass:
02947   case CompoundLiteralExprClass:
02948   case ExtVectorElementExprClass:
02949   case DesignatedInitExprClass:
02950   case ParenListExprClass:
02951   case CXXPseudoDestructorExprClass:
02952   case CXXStdInitializerListExprClass:
02953   case SubstNonTypeTemplateParmExprClass:
02954   case MaterializeTemporaryExprClass:
02955   case ShuffleVectorExprClass:
02956   case ConvertVectorExprClass:
02957   case AsTypeExprClass:
02958     // These have a side-effect if any subexpression does.
02959     break;
02960 
02961   case UnaryOperatorClass:
02962     if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
02963       return true;
02964     break;
02965 
02966   case BinaryOperatorClass:
02967     if (cast<BinaryOperator>(this)->isAssignmentOp())
02968       return true;
02969     break;
02970 
02971   case InitListExprClass:
02972     // FIXME: The children for an InitListExpr doesn't include the array filler.
02973     if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
02974       if (E->HasSideEffects(Ctx))
02975         return true;
02976     break;
02977 
02978   case GenericSelectionExprClass:
02979     return cast<GenericSelectionExpr>(this)->getResultExpr()->
02980         HasSideEffects(Ctx);
02981 
02982   case ChooseExprClass:
02983     return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(Ctx);
02984 
02985   case CXXDefaultArgExprClass:
02986     return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(Ctx);
02987 
02988   case CXXDefaultInitExprClass: {
02989     const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
02990     if (const Expr *E = FD->getInClassInitializer())
02991       return E->HasSideEffects(Ctx);
02992     // If we've not yet parsed the initializer, assume it has side-effects.
02993     return true;
02994   }
02995 
02996   case CXXDynamicCastExprClass: {
02997     // A dynamic_cast expression has side-effects if it can throw.
02998     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
02999     if (DCE->getTypeAsWritten()->isReferenceType() &&
03000         DCE->getCastKind() == CK_Dynamic)
03001       return true;
03002   } // Fall through.
03003   case ImplicitCastExprClass:
03004   case CStyleCastExprClass:
03005   case CXXStaticCastExprClass:
03006   case CXXReinterpretCastExprClass:
03007   case CXXConstCastExprClass:
03008   case CXXFunctionalCastExprClass: {
03009     const CastExpr *CE = cast<CastExpr>(this);
03010     if (CE->getCastKind() == CK_LValueToRValue &&
03011         CE->getSubExpr()->getType().isVolatileQualified())
03012       return true;
03013     break;
03014   }
03015 
03016   case CXXTypeidExprClass:
03017     // typeid might throw if its subexpression is potentially-evaluated, so has
03018     // side-effects in that case whether or not its subexpression does.
03019     return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
03020 
03021   case CXXConstructExprClass:
03022   case CXXTemporaryObjectExprClass: {
03023     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
03024     if (!CE->getConstructor()->isTrivial())
03025       return true;
03026     // A trivial constructor does not add any side-effects of its own. Just look
03027     // at its arguments.
03028     break;
03029   }
03030 
03031   case LambdaExprClass: {
03032     const LambdaExpr *LE = cast<LambdaExpr>(this);
03033     for (LambdaExpr::capture_iterator I = LE->capture_begin(),
03034                                       E = LE->capture_end(); I != E; ++I)
03035       if (I->getCaptureKind() == LCK_ByCopy)
03036         // FIXME: Only has a side-effect if the variable is volatile or if
03037         // the copy would invoke a non-trivial copy constructor.
03038         return true;
03039     return false;
03040   }
03041 
03042   case PseudoObjectExprClass: {
03043     // Only look for side-effects in the semantic form, and look past
03044     // OpaqueValueExpr bindings in that form.
03045     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
03046     for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
03047                                                     E = PO->semantics_end();
03048          I != E; ++I) {
03049       const Expr *Subexpr = *I;
03050       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
03051         Subexpr = OVE->getSourceExpr();
03052       if (Subexpr->HasSideEffects(Ctx))
03053         return true;
03054     }
03055     return false;
03056   }
03057 
03058   case ObjCBoxedExprClass:
03059   case ObjCArrayLiteralClass:
03060   case ObjCDictionaryLiteralClass:
03061   case ObjCMessageExprClass:
03062   case ObjCSelectorExprClass:
03063   case ObjCProtocolExprClass:
03064   case ObjCPropertyRefExprClass:
03065   case ObjCIsaExprClass:
03066   case ObjCIndirectCopyRestoreExprClass:
03067   case ObjCSubscriptRefExprClass:
03068   case ObjCBridgedCastExprClass:
03069     // FIXME: Classify these cases better.
03070     return true;
03071   }
03072 
03073   // Recurse to children.
03074   for (const_child_range SubStmts = children(); SubStmts; ++SubStmts)
03075     if (const Stmt *S = *SubStmts)
03076       if (cast<Expr>(S)->HasSideEffects(Ctx))
03077         return true;
03078 
03079   return false;
03080 }
03081 
03082 namespace {
03083   /// \brief Look for a call to a non-trivial function within an expression.
03084   class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder>
03085   {
03086     typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
03087     
03088     bool NonTrivial;
03089     
03090   public:
03091     explicit NonTrivialCallFinder(ASTContext &Context) 
03092       : Inherited(Context), NonTrivial(false) { }
03093     
03094     bool hasNonTrivialCall() const { return NonTrivial; }
03095     
03096     void VisitCallExpr(CallExpr *E) {
03097       if (CXXMethodDecl *Method
03098           = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
03099         if (Method->isTrivial()) {
03100           // Recurse to children of the call.
03101           Inherited::VisitStmt(E);
03102           return;
03103         }
03104       }
03105       
03106       NonTrivial = true;
03107     }
03108     
03109     void VisitCXXConstructExpr(CXXConstructExpr *E) {
03110       if (E->getConstructor()->isTrivial()) {
03111         // Recurse to children of the call.
03112         Inherited::VisitStmt(E);
03113         return;
03114       }
03115       
03116       NonTrivial = true;
03117     }
03118     
03119     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
03120       if (E->getTemporary()->getDestructor()->isTrivial()) {
03121         Inherited::VisitStmt(E);
03122         return;
03123       }
03124       
03125       NonTrivial = true;
03126     }
03127   };
03128 }
03129 
03130 bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
03131   NonTrivialCallFinder Finder(Ctx);
03132   Finder.Visit(this);
03133   return Finder.hasNonTrivialCall();  
03134 }
03135 
03136 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null 
03137 /// pointer constant or not, as well as the specific kind of constant detected.
03138 /// Null pointer constants can be integer constant expressions with the
03139 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
03140 /// (a GNU extension).
03141 Expr::NullPointerConstantKind
03142 Expr::isNullPointerConstant(ASTContext &Ctx,
03143                             NullPointerConstantValueDependence NPC) const {
03144   if (isValueDependent() &&
03145       (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
03146     switch (NPC) {
03147     case NPC_NeverValueDependent:
03148       llvm_unreachable("Unexpected value dependent expression!");
03149     case NPC_ValueDependentIsNull:
03150       if (isTypeDependent() || getType()->isIntegralType(Ctx))
03151         return NPCK_ZeroExpression;
03152       else
03153         return NPCK_NotNull;
03154         
03155     case NPC_ValueDependentIsNotNull:
03156       return NPCK_NotNull;
03157     }
03158   }
03159 
03160   // Strip off a cast to void*, if it exists. Except in C++.
03161   if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
03162     if (!Ctx.getLangOpts().CPlusPlus) {
03163       // Check that it is a cast to void*.
03164       if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
03165         QualType Pointee = PT->getPointeeType();
03166         if (!Pointee.hasQualifiers() &&
03167             Pointee->isVoidType() &&                              // to void*
03168             CE->getSubExpr()->getType()->isIntegerType())         // from int.
03169           return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
03170       }
03171     }
03172   } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
03173     // Ignore the ImplicitCastExpr type entirely.
03174     return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
03175   } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
03176     // Accept ((void*)0) as a null pointer constant, as many other
03177     // implementations do.
03178     return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
03179   } else if (const GenericSelectionExpr *GE =
03180                dyn_cast<GenericSelectionExpr>(this)) {
03181     if (GE->isResultDependent())
03182       return NPCK_NotNull;
03183     return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
03184   } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
03185     if (CE->isConditionDependent())
03186       return NPCK_NotNull;
03187     return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
03188   } else if (const CXXDefaultArgExpr *DefaultArg
03189                = dyn_cast<CXXDefaultArgExpr>(this)) {
03190     // See through default argument expressions.
03191     return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
03192   } else if (const CXXDefaultInitExpr *DefaultInit
03193                = dyn_cast<CXXDefaultInitExpr>(this)) {
03194     // See through default initializer expressions.
03195     return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
03196   } else if (isa<GNUNullExpr>(this)) {
03197     // The GNU __null extension is always a null pointer constant.
03198     return NPCK_GNUNull;
03199   } else if (const MaterializeTemporaryExpr *M 
03200                                    = dyn_cast<MaterializeTemporaryExpr>(this)) {
03201     return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
03202   } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
03203     if (const Expr *Source = OVE->getSourceExpr())
03204       return Source->isNullPointerConstant(Ctx, NPC);
03205   }
03206 
03207   // C++11 nullptr_t is always a null pointer constant.
03208   if (getType()->isNullPtrType())
03209     return NPCK_CXX11_nullptr;
03210 
03211   if (const RecordType *UT = getType()->getAsUnionType())
03212     if (!Ctx.getLangOpts().CPlusPlus11 &&
03213         UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
03214       if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
03215         const Expr *InitExpr = CLE->getInitializer();
03216         if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
03217           return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
03218       }
03219   // This expression must be an integer type.
03220   if (!getType()->isIntegerType() || 
03221       (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
03222     return NPCK_NotNull;
03223 
03224   if (Ctx.getLangOpts().CPlusPlus11) {
03225     // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
03226     // value zero or a prvalue of type std::nullptr_t.
03227     // Microsoft mode permits C++98 rules reflecting MSVC behavior.
03228     const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
03229     if (Lit && !Lit->getValue())
03230       return NPCK_ZeroLiteral;
03231     else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
03232       return NPCK_NotNull;
03233   } else {
03234     // If we have an integer constant expression, we need to *evaluate* it and
03235     // test for the value 0.
03236     if (!isIntegerConstantExpr(Ctx))
03237       return NPCK_NotNull;
03238   }
03239 
03240   if (EvaluateKnownConstInt(Ctx) != 0)
03241     return NPCK_NotNull;
03242 
03243   if (isa<IntegerLiteral>(this))
03244     return NPCK_ZeroLiteral;
03245   return NPCK_ZeroExpression;
03246 }
03247 
03248 /// \brief If this expression is an l-value for an Objective C
03249 /// property, find the underlying property reference expression.
03250 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
03251   const Expr *E = this;
03252   while (true) {
03253     assert((E->getValueKind() == VK_LValue &&
03254             E->getObjectKind() == OK_ObjCProperty) &&
03255            "expression is not a property reference");
03256     E = E->IgnoreParenCasts();
03257     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
03258       if (BO->getOpcode() == BO_Comma) {
03259         E = BO->getRHS();
03260         continue;
03261       }
03262     }
03263 
03264     break;
03265   }
03266 
03267   return cast<ObjCPropertyRefExpr>(E);
03268 }
03269 
03270 bool Expr::isObjCSelfExpr() const {
03271   const Expr *E = IgnoreParenImpCasts();
03272 
03273   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
03274   if (!DRE)
03275     return false;
03276 
03277   const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
03278   if (!Param)
03279     return false;
03280 
03281   const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
03282   if (!M)
03283     return false;
03284 
03285   return M->getSelfDecl() == Param;
03286 }
03287 
03288 FieldDecl *Expr::getSourceBitField() {
03289   Expr *E = this->IgnoreParens();
03290 
03291   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
03292     if (ICE->getCastKind() == CK_LValueToRValue ||
03293         (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
03294       E = ICE->getSubExpr()->IgnoreParens();
03295     else
03296       break;
03297   }
03298 
03299   if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
03300     if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
03301       if (Field->isBitField())
03302         return Field;
03303 
03304   if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
03305     if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
03306       if (Ivar->isBitField())
03307         return Ivar;
03308 
03309   if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
03310     if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
03311       if (Field->isBitField())
03312         return Field;
03313 
03314   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
03315     if (BinOp->isAssignmentOp() && BinOp->getLHS())
03316       return BinOp->getLHS()->getSourceBitField();
03317 
03318     if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
03319       return BinOp->getRHS()->getSourceBitField();
03320   }
03321 
03322   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
03323     if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
03324       return UnOp->getSubExpr()->getSourceBitField();
03325 
03326   return nullptr;
03327 }
03328 
03329 bool Expr::refersToVectorElement() const {
03330   const Expr *E = this->IgnoreParens();
03331   
03332   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
03333     if (ICE->getValueKind() != VK_RValue &&
03334         ICE->getCastKind() == CK_NoOp)
03335       E = ICE->getSubExpr()->IgnoreParens();
03336     else
03337       break;
03338   }
03339   
03340   if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
03341     return ASE->getBase()->getType()->isVectorType();
03342 
03343   if (isa<ExtVectorElementExpr>(E))
03344     return true;
03345 
03346   return false;
03347 }
03348 
03349 /// isArrow - Return true if the base expression is a pointer to vector,
03350 /// return false if the base expression is a vector.
03351 bool ExtVectorElementExpr::isArrow() const {
03352   return getBase()->getType()->isPointerType();
03353 }
03354 
03355 unsigned ExtVectorElementExpr::getNumElements() const {
03356   if (const VectorType *VT = getType()->getAs<VectorType>())
03357     return VT->getNumElements();
03358   return 1;
03359 }
03360 
03361 /// containsDuplicateElements - Return true if any element access is repeated.
03362 bool ExtVectorElementExpr::containsDuplicateElements() const {
03363   // FIXME: Refactor this code to an accessor on the AST node which returns the
03364   // "type" of component access, and share with code below and in Sema.
03365   StringRef Comp = Accessor->getName();
03366 
03367   // Halving swizzles do not contain duplicate elements.
03368   if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
03369     return false;
03370 
03371   // Advance past s-char prefix on hex swizzles.
03372   if (Comp[0] == 's' || Comp[0] == 'S')
03373     Comp = Comp.substr(1);
03374 
03375   for (unsigned i = 0, e = Comp.size(); i != e; ++i)
03376     if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
03377         return true;
03378 
03379   return false;
03380 }
03381 
03382 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
03383 void ExtVectorElementExpr::getEncodedElementAccess(
03384                                   SmallVectorImpl<unsigned> &Elts) const {
03385   StringRef Comp = Accessor->getName();
03386   if (Comp[0] == 's' || Comp[0] == 'S')
03387     Comp = Comp.substr(1);
03388 
03389   bool isHi =   Comp == "hi";
03390   bool isLo =   Comp == "lo";
03391   bool isEven = Comp == "even";
03392   bool isOdd  = Comp == "odd";
03393 
03394   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
03395     uint64_t Index;
03396 
03397     if (isHi)
03398       Index = e + i;
03399     else if (isLo)
03400       Index = i;
03401     else if (isEven)
03402       Index = 2 * i;
03403     else if (isOdd)
03404       Index = 2 * i + 1;
03405     else
03406       Index = ExtVectorType::getAccessorIdx(Comp[i]);
03407 
03408     Elts.push_back(Index);
03409   }
03410 }
03411 
03412 ObjCMessageExpr::ObjCMessageExpr(QualType T,
03413                                  ExprValueKind VK,
03414                                  SourceLocation LBracLoc,
03415                                  SourceLocation SuperLoc,
03416                                  bool IsInstanceSuper,
03417                                  QualType SuperType,
03418                                  Selector Sel, 
03419                                  ArrayRef<SourceLocation> SelLocs,
03420                                  SelectorLocationsKind SelLocsK,
03421                                  ObjCMethodDecl *Method,
03422                                  ArrayRef<Expr *> Args,
03423                                  SourceLocation RBracLoc,
03424                                  bool isImplicit)
03425   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
03426          /*TypeDependent=*/false, /*ValueDependent=*/false,
03427          /*InstantiationDependent=*/false,
03428          /*ContainsUnexpandedParameterPack=*/false),
03429     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
03430                                                        : Sel.getAsOpaquePtr())),
03431     Kind(IsInstanceSuper? SuperInstance : SuperClass),
03432     HasMethod(Method != nullptr), IsDelegateInitCall(false),
03433     IsImplicit(isImplicit), SuperLoc(SuperLoc), LBracLoc(LBracLoc),
03434     RBracLoc(RBracLoc)
03435 {
03436   initArgsAndSelLocs(Args, SelLocs, SelLocsK);
03437   setReceiverPointer(SuperType.getAsOpaquePtr());
03438 }
03439 
03440 ObjCMessageExpr::ObjCMessageExpr(QualType T,
03441                                  ExprValueKind VK,
03442                                  SourceLocation LBracLoc,
03443                                  TypeSourceInfo *Receiver,
03444                                  Selector Sel,
03445                                  ArrayRef<SourceLocation> SelLocs,
03446                                  SelectorLocationsKind SelLocsK,
03447                                  ObjCMethodDecl *Method,
03448                                  ArrayRef<Expr *> Args,
03449                                  SourceLocation RBracLoc,
03450                                  bool isImplicit)
03451   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
03452          T->isDependentType(), T->isInstantiationDependentType(),
03453          T->containsUnexpandedParameterPack()),
03454     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
03455                                                        : Sel.getAsOpaquePtr())),
03456     Kind(Class),
03457     HasMethod(Method != nullptr), IsDelegateInitCall(false),
03458     IsImplicit(isImplicit), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
03459 {
03460   initArgsAndSelLocs(Args, SelLocs, SelLocsK);
03461   setReceiverPointer(Receiver);
03462 }
03463 
03464 ObjCMessageExpr::ObjCMessageExpr(QualType T,
03465                                  ExprValueKind VK,
03466                                  SourceLocation LBracLoc,
03467                                  Expr *Receiver,
03468                                  Selector Sel, 
03469                                  ArrayRef<SourceLocation> SelLocs,
03470                                  SelectorLocationsKind SelLocsK,
03471                                  ObjCMethodDecl *Method,
03472                                  ArrayRef<Expr *> Args,
03473                                  SourceLocation RBracLoc,
03474                                  bool isImplicit)
03475   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
03476          Receiver->isTypeDependent(),
03477          Receiver->isInstantiationDependent(),
03478          Receiver->containsUnexpandedParameterPack()),
03479     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
03480                                                        : Sel.getAsOpaquePtr())),
03481     Kind(Instance),
03482     HasMethod(Method != nullptr), IsDelegateInitCall(false),
03483     IsImplicit(isImplicit), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
03484 {
03485   initArgsAndSelLocs(Args, SelLocs, SelLocsK);
03486   setReceiverPointer(Receiver);
03487 }
03488 
03489 void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args,
03490                                          ArrayRef<SourceLocation> SelLocs,
03491                                          SelectorLocationsKind SelLocsK) {
03492   setNumArgs(Args.size());
03493   Expr **MyArgs = getArgs();
03494   for (unsigned I = 0; I != Args.size(); ++I) {
03495     if (Args[I]->isTypeDependent())
03496       ExprBits.TypeDependent = true;
03497     if (Args[I]->isValueDependent())
03498       ExprBits.ValueDependent = true;
03499     if (Args[I]->isInstantiationDependent())
03500       ExprBits.InstantiationDependent = true;
03501     if (Args[I]->containsUnexpandedParameterPack())
03502       ExprBits.ContainsUnexpandedParameterPack = true;
03503   
03504     MyArgs[I] = Args[I];
03505   }
03506 
03507   SelLocsKind = SelLocsK;
03508   if (!isImplicit()) {
03509     if (SelLocsK == SelLoc_NonStandard)
03510       std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
03511   }
03512 }
03513 
03514 ObjCMessageExpr *ObjCMessageExpr::Create(const ASTContext &Context, QualType T,
03515                                          ExprValueKind VK,
03516                                          SourceLocation LBracLoc,
03517                                          SourceLocation SuperLoc,
03518                                          bool IsInstanceSuper,
03519                                          QualType SuperType,
03520                                          Selector Sel, 
03521                                          ArrayRef<SourceLocation> SelLocs,
03522                                          ObjCMethodDecl *Method,
03523                                          ArrayRef<Expr *> Args,
03524                                          SourceLocation RBracLoc,
03525                                          bool isImplicit) {
03526   assert((!SelLocs.empty() || isImplicit) &&
03527          "No selector locs for non-implicit message");
03528   ObjCMessageExpr *Mem;
03529   SelectorLocationsKind SelLocsK = SelectorLocationsKind();
03530   if (isImplicit)
03531     Mem = alloc(Context, Args.size(), 0);
03532   else
03533     Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
03534   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
03535                                    SuperType, Sel, SelLocs, SelLocsK,
03536                                    Method, Args, RBracLoc, isImplicit);
03537 }
03538 
03539 ObjCMessageExpr *ObjCMessageExpr::Create(const ASTContext &Context, QualType T,
03540                                          ExprValueKind VK,
03541                                          SourceLocation LBracLoc,
03542                                          TypeSourceInfo *Receiver,
03543                                          Selector Sel, 
03544                                          ArrayRef<SourceLocation> SelLocs,
03545                                          ObjCMethodDecl *Method,
03546                                          ArrayRef<Expr *> Args,
03547                                          SourceLocation RBracLoc,
03548                                          bool isImplicit) {
03549   assert((!SelLocs.empty() || isImplicit) &&
03550          "No selector locs for non-implicit message");
03551   ObjCMessageExpr *Mem;
03552   SelectorLocationsKind SelLocsK = SelectorLocationsKind();
03553   if (isImplicit)
03554     Mem = alloc(Context, Args.size(), 0);
03555   else
03556     Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
03557   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
03558                                    SelLocs, SelLocsK, Method, Args, RBracLoc,
03559                                    isImplicit);
03560 }
03561 
03562 ObjCMessageExpr *ObjCMessageExpr::Create(const ASTContext &Context, QualType T,
03563                                          ExprValueKind VK,
03564                                          SourceLocation LBracLoc,
03565                                          Expr *Receiver,
03566                                          Selector Sel,
03567                                          ArrayRef<SourceLocation> SelLocs,
03568                                          ObjCMethodDecl *Method,
03569                                          ArrayRef<Expr *> Args,
03570                                          SourceLocation RBracLoc,
03571                                          bool isImplicit) {
03572   assert((!SelLocs.empty() || isImplicit) &&
03573          "No selector locs for non-implicit message");
03574   ObjCMessageExpr *Mem;
03575   SelectorLocationsKind SelLocsK = SelectorLocationsKind();
03576   if (isImplicit)
03577     Mem = alloc(Context, Args.size(), 0);
03578   else
03579     Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
03580   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
03581                                    SelLocs, SelLocsK, Method, Args, RBracLoc,
03582                                    isImplicit);
03583 }
03584 
03585 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(const ASTContext &Context,
03586                                               unsigned NumArgs,
03587                                               unsigned NumStoredSelLocs) {
03588   ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs);
03589   return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
03590 }
03591 
03592 ObjCMessageExpr *ObjCMessageExpr::alloc(const ASTContext &C,
03593                                         ArrayRef<Expr *> Args,
03594                                         SourceLocation RBraceLoc,
03595                                         ArrayRef<SourceLocation> SelLocs,
03596                                         Selector Sel,
03597                                         SelectorLocationsKind &SelLocsK) {
03598   SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc);
03599   unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size()
03600                                                                : 0;
03601   return alloc(C, Args.size(), NumStoredSelLocs);
03602 }
03603 
03604 ObjCMessageExpr *ObjCMessageExpr::alloc(const ASTContext &C,
03605                                         unsigned NumArgs,
03606                                         unsigned NumStoredSelLocs) {
03607   unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 
03608     NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation);
03609   return (ObjCMessageExpr *)C.Allocate(Size,
03610                                      llvm::AlignOf<ObjCMessageExpr>::Alignment);
03611 }
03612 
03613 void ObjCMessageExpr::getSelectorLocs(
03614                                SmallVectorImpl<SourceLocation> &SelLocs) const {
03615   for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
03616     SelLocs.push_back(getSelectorLoc(i));
03617 }
03618 
03619 SourceRange ObjCMessageExpr::getReceiverRange() const {
03620   switch (getReceiverKind()) {
03621   case Instance:
03622     return getInstanceReceiver()->getSourceRange();
03623 
03624   case Class:
03625     return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
03626 
03627   case SuperInstance:
03628   case SuperClass:
03629     return getSuperLoc();
03630   }
03631 
03632   llvm_unreachable("Invalid ReceiverKind!");
03633 }
03634 
03635 Selector ObjCMessageExpr::getSelector() const {
03636   if (HasMethod)
03637     return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
03638                                                                ->getSelector();
03639   return Selector(SelectorOrMethod); 
03640 }
03641 
03642 QualType ObjCMessageExpr::getReceiverType() const {
03643   switch (getReceiverKind()) {
03644   case Instance:
03645     return getInstanceReceiver()->getType();
03646   case Class:
03647     return getClassReceiver();
03648   case SuperInstance:
03649   case SuperClass:
03650     return getSuperType();
03651   }
03652 
03653   llvm_unreachable("unexpected receiver kind");
03654 }
03655 
03656 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
03657   QualType T = getReceiverType();
03658 
03659   if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
03660     return Ptr->getInterfaceDecl();
03661 
03662   if (const ObjCObjectType *Ty = T->getAs<ObjCObjectType>())
03663     return Ty->getInterface();
03664 
03665   return nullptr;
03666 }
03667 
03668 StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
03669   switch (getBridgeKind()) {
03670   case OBC_Bridge:
03671     return "__bridge";
03672   case OBC_BridgeTransfer:
03673     return "__bridge_transfer";
03674   case OBC_BridgeRetained:
03675     return "__bridge_retained";
03676   }
03677 
03678   llvm_unreachable("Invalid BridgeKind!");
03679 }
03680 
03681 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
03682                                      QualType Type, SourceLocation BLoc,
03683                                      SourceLocation RP) 
03684    : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
03685           Type->isDependentType(), Type->isDependentType(),
03686           Type->isInstantiationDependentType(),
03687           Type->containsUnexpandedParameterPack()),
03688      BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
03689 {
03690   SubExprs = new (C) Stmt*[args.size()];
03691   for (unsigned i = 0; i != args.size(); i++) {
03692     if (args[i]->isTypeDependent())
03693       ExprBits.TypeDependent = true;
03694     if (args[i]->isValueDependent())
03695       ExprBits.ValueDependent = true;
03696     if (args[i]->isInstantiationDependent())
03697       ExprBits.InstantiationDependent = true;
03698     if (args[i]->containsUnexpandedParameterPack())
03699       ExprBits.ContainsUnexpandedParameterPack = true;
03700 
03701     SubExprs[i] = args[i];
03702   }
03703 }
03704 
03705 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
03706   if (SubExprs) C.Deallocate(SubExprs);
03707 
03708   this->NumExprs = Exprs.size();
03709   SubExprs = new (C) Stmt*[NumExprs];
03710   memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
03711 }
03712 
03713 GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
03714                                SourceLocation GenericLoc, Expr *ControllingExpr,
03715                                ArrayRef<TypeSourceInfo*> AssocTypes,
03716                                ArrayRef<Expr*> AssocExprs,
03717                                SourceLocation DefaultLoc,
03718                                SourceLocation RParenLoc,
03719                                bool ContainsUnexpandedParameterPack,
03720                                unsigned ResultIndex)
03721   : Expr(GenericSelectionExprClass,
03722          AssocExprs[ResultIndex]->getType(),
03723          AssocExprs[ResultIndex]->getValueKind(),
03724          AssocExprs[ResultIndex]->getObjectKind(),
03725          AssocExprs[ResultIndex]->isTypeDependent(),
03726          AssocExprs[ResultIndex]->isValueDependent(),
03727          AssocExprs[ResultIndex]->isInstantiationDependent(),
03728          ContainsUnexpandedParameterPack),
03729     AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
03730     SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
03731     NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
03732     GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
03733   SubExprs[CONTROLLING] = ControllingExpr;
03734   assert(AssocTypes.size() == AssocExprs.size());
03735   std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
03736   std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
03737 }
03738 
03739 GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
03740                                SourceLocation GenericLoc, Expr *ControllingExpr,
03741                                ArrayRef<TypeSourceInfo*> AssocTypes,
03742                                ArrayRef<Expr*> AssocExprs,
03743                                SourceLocation DefaultLoc,
03744                                SourceLocation RParenLoc,
03745                                bool ContainsUnexpandedParameterPack)
03746   : Expr(GenericSelectionExprClass,
03747          Context.DependentTy,
03748          VK_RValue,
03749          OK_Ordinary,
03750          /*isTypeDependent=*/true,
03751          /*isValueDependent=*/true,
03752          /*isInstantiationDependent=*/true,
03753          ContainsUnexpandedParameterPack),
03754     AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
03755     SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
03756     NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
03757     DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
03758   SubExprs[CONTROLLING] = ControllingExpr;
03759   assert(AssocTypes.size() == AssocExprs.size());
03760   std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
03761   std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
03762 }
03763 
03764 //===----------------------------------------------------------------------===//
03765 //  DesignatedInitExpr
03766 //===----------------------------------------------------------------------===//
03767 
03768 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
03769   assert(Kind == FieldDesignator && "Only valid on a field designator");
03770   if (Field.NameOrField & 0x01)
03771     return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
03772   else
03773     return getField()->getIdentifier();
03774 }
03775 
03776 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
03777                                        unsigned NumDesignators,
03778                                        const Designator *Designators,
03779                                        SourceLocation EqualOrColonLoc,
03780                                        bool GNUSyntax,
03781                                        ArrayRef<Expr*> IndexExprs,
03782                                        Expr *Init)
03783   : Expr(DesignatedInitExprClass, Ty,
03784          Init->getValueKind(), Init->getObjectKind(),
03785          Init->isTypeDependent(), Init->isValueDependent(),
03786          Init->isInstantiationDependent(),
03787          Init->containsUnexpandedParameterPack()),
03788     EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
03789     NumDesignators(NumDesignators), NumSubExprs(IndexExprs.size() + 1) {
03790   this->Designators = new (C) Designator[NumDesignators];
03791 
03792   // Record the initializer itself.
03793   child_range Child = children();
03794   *Child++ = Init;
03795 
03796   // Copy the designators and their subexpressions, computing
03797   // value-dependence along the way.
03798   unsigned IndexIdx = 0;
03799   for (unsigned I = 0; I != NumDesignators; ++I) {
03800     this->Designators[I] = Designators[I];
03801 
03802     if (this->Designators[I].isArrayDesignator()) {
03803       // Compute type- and value-dependence.
03804       Expr *Index = IndexExprs[IndexIdx];
03805       if (Index->isTypeDependent() || Index->isValueDependent())
03806         ExprBits.ValueDependent = true;
03807       if (Index->isInstantiationDependent())
03808         ExprBits.InstantiationDependent = true;
03809       // Propagate unexpanded parameter packs.
03810       if (Index->containsUnexpandedParameterPack())
03811         ExprBits.ContainsUnexpandedParameterPack = true;
03812 
03813       // Copy the index expressions into permanent storage.
03814       *Child++ = IndexExprs[IndexIdx++];
03815     } else if (this->Designators[I].isArrayRangeDesignator()) {
03816       // Compute type- and value-dependence.
03817       Expr *Start = IndexExprs[IndexIdx];
03818       Expr *End = IndexExprs[IndexIdx + 1];
03819       if (Start->isTypeDependent() || Start->isValueDependent() ||
03820           End->isTypeDependent() || End->isValueDependent()) {
03821         ExprBits.ValueDependent = true;
03822         ExprBits.InstantiationDependent = true;
03823       } else if (Start->isInstantiationDependent() || 
03824                  End->isInstantiationDependent()) {
03825         ExprBits.InstantiationDependent = true;
03826       }
03827                  
03828       // Propagate unexpanded parameter packs.
03829       if (Start->containsUnexpandedParameterPack() ||
03830           End->containsUnexpandedParameterPack())
03831         ExprBits.ContainsUnexpandedParameterPack = true;
03832 
03833       // Copy the start/end expressions into permanent storage.
03834       *Child++ = IndexExprs[IndexIdx++];
03835       *Child++ = IndexExprs[IndexIdx++];
03836     }
03837   }
03838 
03839   assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
03840 }
03841 
03842 DesignatedInitExpr *
03843 DesignatedInitExpr::Create(const ASTContext &C, Designator *Designators,
03844                            unsigned NumDesignators,
03845                            ArrayRef<Expr*> IndexExprs,
03846                            SourceLocation ColonOrEqualLoc,
03847                            bool UsesColonSyntax, Expr *Init) {
03848   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
03849                          sizeof(Stmt *) * (IndexExprs.size() + 1), 8);
03850   return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
03851                                       ColonOrEqualLoc, UsesColonSyntax,
03852                                       IndexExprs, Init);
03853 }
03854 
03855 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
03856                                                     unsigned NumIndexExprs) {
03857   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
03858                          sizeof(Stmt *) * (NumIndexExprs + 1), 8);
03859   return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
03860 }
03861 
03862 void DesignatedInitExpr::setDesignators(const ASTContext &C,
03863                                         const Designator *Desigs,
03864                                         unsigned NumDesigs) {
03865   Designators = new (C) Designator[NumDesigs];
03866   NumDesignators = NumDesigs;
03867   for (unsigned I = 0; I != NumDesigs; ++I)
03868     Designators[I] = Desigs[I];
03869 }
03870 
03871 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
03872   DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
03873   if (size() == 1)
03874     return DIE->getDesignator(0)->getSourceRange();
03875   return SourceRange(DIE->getDesignator(0)->getLocStart(),
03876                      DIE->getDesignator(size()-1)->getLocEnd());
03877 }
03878 
03879 SourceLocation DesignatedInitExpr::getLocStart() const {
03880   SourceLocation StartLoc;
03881   Designator &First =
03882     *const_cast<DesignatedInitExpr*>(this)->designators_begin();
03883   if (First.isFieldDesignator()) {
03884     if (GNUSyntax)
03885       StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
03886     else
03887       StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
03888   } else
03889     StartLoc =
03890       SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
03891   return StartLoc;
03892 }
03893 
03894 SourceLocation DesignatedInitExpr::getLocEnd() const {
03895   return getInit()->getLocEnd();
03896 }
03897 
03898 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
03899   assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
03900   Stmt *const *SubExprs = reinterpret_cast<Stmt *const *>(this + 1);
03901   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
03902 }
03903 
03904 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
03905   assert(D.Kind == Designator::ArrayRangeDesignator &&
03906          "Requires array range designator");
03907   Stmt *const *SubExprs = reinterpret_cast<Stmt *const *>(this + 1);
03908   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
03909 }
03910 
03911 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
03912   assert(D.Kind == Designator::ArrayRangeDesignator &&
03913          "Requires array range designator");
03914   Stmt *const *SubExprs = reinterpret_cast<Stmt *const *>(this + 1);
03915   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
03916 }
03917 
03918 /// \brief Replaces the designator at index @p Idx with the series
03919 /// of designators in [First, Last).
03920 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
03921                                           const Designator *First,
03922                                           const Designator *Last) {
03923   unsigned NumNewDesignators = Last - First;
03924   if (NumNewDesignators == 0) {
03925     std::copy_backward(Designators + Idx + 1,
03926                        Designators + NumDesignators,
03927                        Designators + Idx);
03928     --NumNewDesignators;
03929     return;
03930   } else if (NumNewDesignators == 1) {
03931     Designators[Idx] = *First;
03932     return;
03933   }
03934 
03935   Designator *NewDesignators
03936     = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
03937   std::copy(Designators, Designators + Idx, NewDesignators);
03938   std::copy(First, Last, NewDesignators + Idx);
03939   std::copy(Designators + Idx + 1, Designators + NumDesignators,
03940             NewDesignators + Idx + NumNewDesignators);
03941   Designators = NewDesignators;
03942   NumDesignators = NumDesignators - 1 + NumNewDesignators;
03943 }
03944 
03945 ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
03946                              ArrayRef<Expr*> exprs,
03947                              SourceLocation rparenloc)
03948   : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
03949          false, false, false, false),
03950     NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
03951   Exprs = new (C) Stmt*[exprs.size()];
03952   for (unsigned i = 0; i != exprs.size(); ++i) {
03953     if (exprs[i]->isTypeDependent())
03954       ExprBits.TypeDependent = true;
03955     if (exprs[i]->isValueDependent())
03956       ExprBits.ValueDependent = true;
03957     if (exprs[i]->isInstantiationDependent())
03958       ExprBits.InstantiationDependent = true;
03959     if (exprs[i]->containsUnexpandedParameterPack())
03960       ExprBits.ContainsUnexpandedParameterPack = true;
03961 
03962     Exprs[i] = exprs[i];
03963   }
03964 }
03965 
03966 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
03967   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
03968     e = ewc->getSubExpr();
03969   if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
03970     e = m->GetTemporaryExpr();
03971   e = cast<CXXConstructExpr>(e)->getArg(0);
03972   while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
03973     e = ice->getSubExpr();
03974   return cast<OpaqueValueExpr>(e);
03975 }
03976 
03977 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
03978                                            EmptyShell sh,
03979                                            unsigned numSemanticExprs) {
03980   void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
03981                                     (1 + numSemanticExprs) * sizeof(Expr*),
03982                                   llvm::alignOf<PseudoObjectExpr>());
03983   return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
03984 }
03985 
03986 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
03987   : Expr(PseudoObjectExprClass, shell) {
03988   PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
03989 }
03990 
03991 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
03992                                            ArrayRef<Expr*> semantics,
03993                                            unsigned resultIndex) {
03994   assert(syntax && "no syntactic expression!");
03995   assert(semantics.size() && "no semantic expressions!");
03996 
03997   QualType type;
03998   ExprValueKind VK;
03999   if (resultIndex == NoResult) {
04000     type = C.VoidTy;
04001     VK = VK_RValue;
04002   } else {
04003     assert(resultIndex < semantics.size());
04004     type = semantics[resultIndex]->getType();
04005     VK = semantics[resultIndex]->getValueKind();
04006     assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
04007   }
04008 
04009   void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
04010                               (1 + semantics.size()) * sizeof(Expr*),
04011                             llvm::alignOf<PseudoObjectExpr>());
04012   return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
04013                                       resultIndex);
04014 }
04015 
04016 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
04017                                    Expr *syntax, ArrayRef<Expr*> semantics,
04018                                    unsigned resultIndex)
04019   : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
04020          /*filled in at end of ctor*/ false, false, false, false) {
04021   PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
04022   PseudoObjectExprBits.ResultIndex = resultIndex + 1;
04023 
04024   for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
04025     Expr *E = (i == 0 ? syntax : semantics[i-1]);
04026     getSubExprsBuffer()[i] = E;
04027 
04028     if (E->isTypeDependent())
04029       ExprBits.TypeDependent = true;
04030     if (E->isValueDependent())
04031       ExprBits.ValueDependent = true;
04032     if (E->isInstantiationDependent())
04033       ExprBits.InstantiationDependent = true;
04034     if (E->containsUnexpandedParameterPack())
04035       ExprBits.ContainsUnexpandedParameterPack = true;
04036 
04037     if (isa<OpaqueValueExpr>(E))
04038       assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
04039              "opaque-value semantic expressions for pseudo-object "
04040              "operations must have sources");
04041   }
04042 }
04043 
04044 //===----------------------------------------------------------------------===//
04045 //  ExprIterator.
04046 //===----------------------------------------------------------------------===//
04047 
04048 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
04049 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
04050 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
04051 const Expr* ConstExprIterator::operator[](size_t idx) const {
04052   return cast<Expr>(I[idx]);
04053 }
04054 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
04055 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
04056 
04057 //===----------------------------------------------------------------------===//
04058 //  Child Iterators for iterating over subexpressions/substatements
04059 //===----------------------------------------------------------------------===//
04060 
04061 // UnaryExprOrTypeTraitExpr
04062 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
04063   // If this is of a type and the type is a VLA type (and not a typedef), the
04064   // size expression of the VLA needs to be treated as an executable expression.
04065   // Why isn't this weirdness documented better in StmtIterator?
04066   if (isArgumentType()) {
04067     if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
04068                                    getArgumentType().getTypePtr()))
04069       return child_range(child_iterator(T), child_iterator());
04070     return child_range();
04071   }
04072   return child_range(&Argument.Ex, &Argument.Ex + 1);
04073 }
04074 
04075 // ObjCMessageExpr
04076 Stmt::child_range ObjCMessageExpr::children() {
04077   Stmt **begin;
04078   if (getReceiverKind() == Instance)
04079     begin = reinterpret_cast<Stmt **>(this + 1);
04080   else
04081     begin = reinterpret_cast<Stmt **>(getArgs());
04082   return child_range(begin,
04083                      reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
04084 }
04085 
04086 ObjCArrayLiteral::ObjCArrayLiteral(ArrayRef<Expr *> Elements, 
04087                                    QualType T, ObjCMethodDecl *Method,
04088                                    SourceRange SR)
04089   : Expr(ObjCArrayLiteralClass, T, VK_RValue, OK_Ordinary, 
04090          false, false, false, false), 
04091     NumElements(Elements.size()), Range(SR), ArrayWithObjectsMethod(Method)
04092 {
04093   Expr **SaveElements = getElements();
04094   for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
04095     if (Elements[I]->isTypeDependent() || Elements[I]->isValueDependent())
04096       ExprBits.ValueDependent = true;
04097     if (Elements[I]->isInstantiationDependent())
04098       ExprBits.InstantiationDependent = true;
04099     if (Elements[I]->containsUnexpandedParameterPack())
04100       ExprBits.ContainsUnexpandedParameterPack = true;
04101     
04102     SaveElements[I] = Elements[I];
04103   }
04104 }
04105 
04106 ObjCArrayLiteral *ObjCArrayLiteral::Create(const ASTContext &C,
04107                                            ArrayRef<Expr *> Elements,
04108                                            QualType T, ObjCMethodDecl * Method,
04109                                            SourceRange SR) {
04110   void *Mem = C.Allocate(sizeof(ObjCArrayLiteral) 
04111                          + Elements.size() * sizeof(Expr *));
04112   return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR);
04113 }
04114 
04115 ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(const ASTContext &C,
04116                                                 unsigned NumElements) {
04117   
04118   void *Mem = C.Allocate(sizeof(ObjCArrayLiteral) 
04119                          + NumElements * sizeof(Expr *));
04120   return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements);
04121 }
04122 
04123 ObjCDictionaryLiteral::ObjCDictionaryLiteral(
04124                                              ArrayRef<ObjCDictionaryElement> VK, 
04125                                              bool HasPackExpansions,
04126                                              QualType T, ObjCMethodDecl *method,
04127                                              SourceRange SR)
04128   : Expr(ObjCDictionaryLiteralClass, T, VK_RValue, OK_Ordinary, false, false,
04129          false, false),
04130     NumElements(VK.size()), HasPackExpansions(HasPackExpansions), Range(SR), 
04131     DictWithObjectsMethod(method)
04132 {
04133   KeyValuePair *KeyValues = getKeyValues();
04134   ExpansionData *Expansions = getExpansionData();
04135   for (unsigned I = 0; I < NumElements; I++) {
04136     if (VK[I].Key->isTypeDependent() || VK[I].Key->isValueDependent() ||
04137         VK[I].Value->isTypeDependent() || VK[I].Value->isValueDependent())
04138       ExprBits.ValueDependent = true;
04139     if (VK[I].Key->isInstantiationDependent() ||
04140         VK[I].Value->isInstantiationDependent())
04141       ExprBits.InstantiationDependent = true;
04142     if (VK[I].EllipsisLoc.isInvalid() &&
04143         (VK[I].Key->containsUnexpandedParameterPack() ||
04144          VK[I].Value->containsUnexpandedParameterPack()))
04145       ExprBits.ContainsUnexpandedParameterPack = true;
04146 
04147     KeyValues[I].Key = VK[I].Key;
04148     KeyValues[I].Value = VK[I].Value; 
04149     if (Expansions) {
04150       Expansions[I].EllipsisLoc = VK[I].EllipsisLoc;
04151       if (VK[I].NumExpansions)
04152         Expansions[I].NumExpansionsPlusOne = *VK[I].NumExpansions + 1;
04153       else
04154         Expansions[I].NumExpansionsPlusOne = 0;
04155     }
04156   }
04157 }
04158 
04159 ObjCDictionaryLiteral *
04160 ObjCDictionaryLiteral::Create(const ASTContext &C,
04161                               ArrayRef<ObjCDictionaryElement> VK, 
04162                               bool HasPackExpansions,
04163                               QualType T, ObjCMethodDecl *method,
04164                               SourceRange SR) {
04165   unsigned ExpansionsSize = 0;
04166   if (HasPackExpansions)
04167     ExpansionsSize = sizeof(ExpansionData) * VK.size();
04168     
04169   void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) + 
04170                          sizeof(KeyValuePair) * VK.size() + ExpansionsSize);
04171   return new (Mem) ObjCDictionaryLiteral(VK, HasPackExpansions, T, method, SR);
04172 }
04173 
04174 ObjCDictionaryLiteral *
04175 ObjCDictionaryLiteral::CreateEmpty(const ASTContext &C, unsigned NumElements,
04176                                    bool HasPackExpansions) {
04177   unsigned ExpansionsSize = 0;
04178   if (HasPackExpansions)
04179     ExpansionsSize = sizeof(ExpansionData) * NumElements;
04180   void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) + 
04181                          sizeof(KeyValuePair) * NumElements + ExpansionsSize);
04182   return new (Mem) ObjCDictionaryLiteral(EmptyShell(), NumElements, 
04183                                          HasPackExpansions);
04184 }
04185 
04186 ObjCSubscriptRefExpr *ObjCSubscriptRefExpr::Create(const ASTContext &C,
04187                                                    Expr *base,
04188                                                    Expr *key, QualType T, 
04189                                                    ObjCMethodDecl *getMethod,
04190                                                    ObjCMethodDecl *setMethod, 
04191                                                    SourceLocation RB) {
04192   void *Mem = C.Allocate(sizeof(ObjCSubscriptRefExpr));
04193   return new (Mem) ObjCSubscriptRefExpr(base, key, T, VK_LValue, 
04194                                         OK_ObjCSubscript,
04195                                         getMethod, setMethod, RB);
04196 }
04197 
04198 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
04199                        QualType t, AtomicOp op, SourceLocation RP)
04200   : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
04201          false, false, false, false),
04202     NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
04203 {
04204   assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
04205   for (unsigned i = 0; i != args.size(); i++) {
04206     if (args[i]->isTypeDependent())
04207       ExprBits.TypeDependent = true;
04208     if (args[i]->isValueDependent())
04209       ExprBits.ValueDependent = true;
04210     if (args[i]->isInstantiationDependent())
04211       ExprBits.InstantiationDependent = true;
04212     if (args[i]->containsUnexpandedParameterPack())
04213       ExprBits.ContainsUnexpandedParameterPack = true;
04214 
04215     SubExprs[i] = args[i];
04216   }
04217 }
04218 
04219 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
04220   switch (Op) {
04221   case AO__c11_atomic_init:
04222   case AO__c11_atomic_load:
04223   case AO__atomic_load_n:
04224     return 2;
04225 
04226   case AO__c11_atomic_store:
04227   case AO__c11_atomic_exchange:
04228   case AO__atomic_load:
04229   case AO__atomic_store:
04230   case AO__atomic_store_n:
04231   case AO__atomic_exchange_n:
04232   case AO__c11_atomic_fetch_add:
04233   case AO__c11_atomic_fetch_sub:
04234   case AO__c11_atomic_fetch_and:
04235   case AO__c11_atomic_fetch_or:
04236   case AO__c11_atomic_fetch_xor:
04237   case AO__atomic_fetch_add:
04238   case AO__atomic_fetch_sub:
04239   case AO__atomic_fetch_and:
04240   case AO__atomic_fetch_or:
04241   case AO__atomic_fetch_xor:
04242   case AO__atomic_fetch_nand:
04243   case AO__atomic_add_fetch:
04244   case AO__atomic_sub_fetch:
04245   case AO__atomic_and_fetch:
04246   case AO__atomic_or_fetch:
04247   case AO__atomic_xor_fetch:
04248   case AO__atomic_nand_fetch:
04249     return 3;
04250 
04251   case AO__atomic_exchange:
04252     return 4;
04253 
04254   case AO__c11_atomic_compare_exchange_strong:
04255   case AO__c11_atomic_compare_exchange_weak:
04256     return 5;
04257 
04258   case AO__atomic_compare_exchange:
04259   case AO__atomic_compare_exchange_n:
04260     return 6;
04261   }
04262   llvm_unreachable("unknown atomic op");
04263 }