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