Home | History | Annotate | Download | only in Sema
      1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file defines the Sema class, which performs semantic analysis and
     11 // builds ASTs.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CLANG_SEMA_SEMA_H
     16 #define LLVM_CLANG_SEMA_SEMA_H
     17 
     18 #include "clang/Sema/Ownership.h"
     19 #include "clang/Sema/AnalysisBasedWarnings.h"
     20 #include "clang/Sema/IdentifierResolver.h"
     21 #include "clang/Sema/ObjCMethodList.h"
     22 #include "clang/Sema/DeclSpec.h"
     23 #include "clang/Sema/ExternalSemaSource.h"
     24 #include "clang/Sema/LocInfoType.h"
     25 #include "clang/Sema/MultiInitializer.h"
     26 #include "clang/Sema/TypoCorrection.h"
     27 #include "clang/Sema/Weak.h"
     28 #include "clang/AST/Expr.h"
     29 #include "clang/AST/DeclarationName.h"
     30 #include "clang/AST/ExternalASTSource.h"
     31 #include "clang/AST/TypeLoc.h"
     32 #include "clang/Basic/Specifiers.h"
     33 #include "clang/Basic/TemplateKinds.h"
     34 #include "clang/Basic/TypeTraits.h"
     35 #include "clang/Basic/ExpressionTraits.h"
     36 #include "llvm/ADT/ArrayRef.h"
     37 #include "llvm/ADT/OwningPtr.h"
     38 #include "llvm/ADT/SmallPtrSet.h"
     39 #include "llvm/ADT/SmallVector.h"
     40 #include <deque>
     41 #include <string>
     42 
     43 namespace llvm {
     44   class APSInt;
     45   template <typename ValueT> struct DenseMapInfo;
     46   template <typename ValueT, typename ValueInfoT> class DenseSet;
     47 }
     48 
     49 namespace clang {
     50   class ADLResult;
     51   class ASTConsumer;
     52   class ASTContext;
     53   class ASTMutationListener;
     54   class ASTReader;
     55   class ASTWriter;
     56   class ArrayType;
     57   class AttributeList;
     58   class BlockDecl;
     59   class CXXBasePath;
     60   class CXXBasePaths;
     61   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
     62   class CXXConstructorDecl;
     63   class CXXConversionDecl;
     64   class CXXDestructorDecl;
     65   class CXXFieldCollector;
     66   class CXXMemberCallExpr;
     67   class CXXMethodDecl;
     68   class CXXScopeSpec;
     69   class CXXTemporary;
     70   class CXXTryStmt;
     71   class CallExpr;
     72   class ClassTemplateDecl;
     73   class ClassTemplatePartialSpecializationDecl;
     74   class ClassTemplateSpecializationDecl;
     75   class CodeCompleteConsumer;
     76   class CodeCompletionAllocator;
     77   class CodeCompletionResult;
     78   class Decl;
     79   class DeclAccessPair;
     80   class DeclContext;
     81   class DeclRefExpr;
     82   class DeclaratorDecl;
     83   class DeducedTemplateArgument;
     84   class DependentDiagnostic;
     85   class DesignatedInitExpr;
     86   class Designation;
     87   class EnumConstantDecl;
     88   class Expr;
     89   class ExtVectorType;
     90   class ExternalSemaSource;
     91   class FormatAttr;
     92   class FriendDecl;
     93   class FunctionDecl;
     94   class FunctionProtoType;
     95   class FunctionTemplateDecl;
     96   class ImplicitConversionSequence;
     97   class InitListExpr;
     98   class InitializationKind;
     99   class InitializationSequence;
    100   class InitializedEntity;
    101   class IntegerLiteral;
    102   class LabelStmt;
    103   class LangOptions;
    104   class LocalInstantiationScope;
    105   class LookupResult;
    106   class MacroInfo;
    107   class MultiLevelTemplateArgumentList;
    108   class NamedDecl;
    109   class NonNullAttr;
    110   class ObjCCategoryDecl;
    111   class ObjCCategoryImplDecl;
    112   class ObjCCompatibleAliasDecl;
    113   class ObjCContainerDecl;
    114   class ObjCImplDecl;
    115   class ObjCImplementationDecl;
    116   class ObjCInterfaceDecl;
    117   class ObjCIvarDecl;
    118   template <class T> class ObjCList;
    119   class ObjCMessageExpr;
    120   class ObjCMethodDecl;
    121   class ObjCPropertyDecl;
    122   class ObjCProtocolDecl;
    123   class OverloadCandidateSet;
    124   class OverloadExpr;
    125   class ParenListExpr;
    126   class ParmVarDecl;
    127   class Preprocessor;
    128   class PseudoDestructorTypeStorage;
    129   class QualType;
    130   class StandardConversionSequence;
    131   class Stmt;
    132   class StringLiteral;
    133   class SwitchStmt;
    134   class TargetAttributesSema;
    135   class TemplateArgument;
    136   class TemplateArgumentList;
    137   class TemplateArgumentLoc;
    138   class TemplateDecl;
    139   class TemplateParameterList;
    140   class TemplatePartialOrderingContext;
    141   class TemplateTemplateParmDecl;
    142   class Token;
    143   class TypeAliasDecl;
    144   class TypedefDecl;
    145   class TypedefNameDecl;
    146   class TypeLoc;
    147   class UnqualifiedId;
    148   class UnresolvedLookupExpr;
    149   class UnresolvedMemberExpr;
    150   class UnresolvedSetImpl;
    151   class UnresolvedSetIterator;
    152   class UsingDecl;
    153   class UsingShadowDecl;
    154   class ValueDecl;
    155   class VarDecl;
    156   class VisibilityAttr;
    157   class VisibleDeclConsumer;
    158   class IndirectFieldDecl;
    159 
    160 namespace sema {
    161   class AccessedEntity;
    162   class BlockScopeInfo;
    163   class DelayedDiagnostic;
    164   class FunctionScopeInfo;
    165   class TemplateDeductionInfo;
    166 }
    167 
    168 // FIXME: No way to easily map from TemplateTypeParmTypes to
    169 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
    170 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
    171                   SourceLocation> UnexpandedParameterPack;
    172 
    173 /// Sema - This implements semantic analysis and AST building for C.
    174 class Sema {
    175   Sema(const Sema&);           // DO NOT IMPLEMENT
    176   void operator=(const Sema&); // DO NOT IMPLEMENT
    177   mutable const TargetAttributesSema* TheTargetAttributesSema;
    178 public:
    179   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
    180   typedef OpaquePtr<TemplateName> TemplateTy;
    181   typedef OpaquePtr<QualType> TypeTy;
    182 
    183   OpenCLOptions OpenCLFeatures;
    184   FPOptions FPFeatures;
    185 
    186   const LangOptions &LangOpts;
    187   Preprocessor &PP;
    188   ASTContext &Context;
    189   ASTConsumer &Consumer;
    190   DiagnosticsEngine &Diags;
    191   SourceManager &SourceMgr;
    192 
    193   /// \brief Flag indicating whether or not to collect detailed statistics.
    194   bool CollectStats;
    195 
    196   /// \brief Source of additional semantic information.
    197   ExternalSemaSource *ExternalSource;
    198 
    199   /// \brief Code-completion consumer.
    200   CodeCompleteConsumer *CodeCompleter;
    201 
    202   /// CurContext - This is the current declaration context of parsing.
    203   DeclContext *CurContext;
    204 
    205   /// \brief Generally null except when we temporarily switch decl contexts,
    206   /// like in \see ActOnObjCTemporaryExitContainerContext.
    207   DeclContext *OriginalLexicalContext;
    208 
    209   /// VAListTagName - The declaration name corresponding to __va_list_tag.
    210   /// This is used as part of a hack to omit that class from ADL results.
    211   DeclarationName VAListTagName;
    212 
    213   /// PackContext - Manages the stack for #pragma pack. An alignment
    214   /// of 0 indicates default alignment.
    215   void *PackContext; // Really a "PragmaPackStack*"
    216 
    217   bool MSStructPragmaOn; // True when #pragma ms_struct on
    218 
    219   /// VisContext - Manages the stack for #pragma GCC visibility.
    220   void *VisContext; // Really a "PragmaVisStack*"
    221 
    222   /// ExprNeedsCleanups - True if the current evaluation context
    223   /// requires cleanups to be run at its conclusion.
    224   bool ExprNeedsCleanups;
    225 
    226   /// \brief Stack containing information about each of the nested
    227   /// function, block, and method scopes that are currently active.
    228   ///
    229   /// This array is never empty.  Clients should ignore the first
    230   /// element, which is used to cache a single FunctionScopeInfo
    231   /// that's used to parse every top-level function.
    232   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
    233 
    234   /// ExprTemporaries - This is the stack of temporaries that are created by
    235   /// the current full expression.
    236   SmallVector<CXXTemporary*, 8> ExprTemporaries;
    237 
    238   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
    239                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
    240     ExtVectorDeclsType;
    241 
    242   /// ExtVectorDecls - This is a list all the extended vector types. This allows
    243   /// us to associate a raw vector type with one of the ext_vector type names.
    244   /// This is only necessary for issuing pretty diagnostics.
    245   ExtVectorDeclsType ExtVectorDecls;
    246 
    247   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
    248   llvm::OwningPtr<CXXFieldCollector> FieldCollector;
    249 
    250   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
    251 
    252   /// PureVirtualClassDiagSet - a set of class declarations which we have
    253   /// emitted a list of pure virtual functions. Used to prevent emitting the
    254   /// same list more than once.
    255   llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
    256 
    257   /// ParsingInitForAutoVars - a set of declarations with auto types for which
    258   /// we are currently parsing the initializer.
    259   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
    260 
    261   /// \brief A mapping from external names to the most recent
    262   /// locally-scoped external declaration with that name.
    263   ///
    264   /// This map contains external declarations introduced in local
    265   /// scoped, e.g.,
    266   ///
    267   /// \code
    268   /// void f() {
    269   ///   void foo(int, int);
    270   /// }
    271   /// \endcode
    272   ///
    273   /// Here, the name "foo" will be associated with the declaration on
    274   /// "foo" within f. This name is not visible outside of
    275   /// "f". However, we still find it in two cases:
    276   ///
    277   ///   - If we are declaring another external with the name "foo", we
    278   ///     can find "foo" as a previous declaration, so that the types
    279   ///     of this external declaration can be checked for
    280   ///     compatibility.
    281   ///
    282   ///   - If we would implicitly declare "foo" (e.g., due to a call to
    283   ///     "foo" in C when no prototype or definition is visible), then
    284   ///     we find this declaration of "foo" and complain that it is
    285   ///     not visible.
    286   llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls;
    287 
    288   /// \brief Look for a locally scoped external declaration by the given name.
    289   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
    290   findLocallyScopedExternalDecl(DeclarationName Name);
    291 
    292   typedef LazyVector<VarDecl *, ExternalSemaSource,
    293                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
    294     TentativeDefinitionsType;
    295 
    296   /// \brief All the tentative definitions encountered in the TU.
    297   TentativeDefinitionsType TentativeDefinitions;
    298 
    299   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
    300                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
    301     UnusedFileScopedDeclsType;
    302 
    303   /// \brief The set of file scoped decls seen so far that have not been used
    304   /// and must warn if not used. Only contains the first declaration.
    305   UnusedFileScopedDeclsType UnusedFileScopedDecls;
    306 
    307   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
    308                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
    309     DelegatingCtorDeclsType;
    310 
    311   /// \brief All the delegating constructors seen so far in the file, used for
    312   /// cycle detection at the end of the TU.
    313   DelegatingCtorDeclsType DelegatingCtorDecls;
    314 
    315   /// \brief All the overriding destructors seen during a class definition
    316   /// (there could be multiple due to nested classes) that had their exception
    317   /// spec checks delayed, plus the overridden destructor.
    318   SmallVector<std::pair<const CXXDestructorDecl*,
    319                               const CXXDestructorDecl*>, 2>
    320       DelayedDestructorExceptionSpecChecks;
    321 
    322   /// \brief Callback to the parser to parse templated functions when needed.
    323   typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
    324   LateTemplateParserCB *LateTemplateParser;
    325   void *OpaqueParser;
    326 
    327   void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
    328     LateTemplateParser = LTP;
    329     OpaqueParser = P;
    330   }
    331 
    332   class DelayedDiagnostics;
    333 
    334   class ParsingDeclState {
    335     unsigned SavedStackSize;
    336     friend class Sema::DelayedDiagnostics;
    337   };
    338 
    339   class ProcessingContextState {
    340     unsigned SavedParsingDepth;
    341     unsigned SavedActiveStackBase;
    342     friend class Sema::DelayedDiagnostics;
    343   };
    344 
    345   /// A class which encapsulates the logic for delaying diagnostics
    346   /// during parsing and other processing.
    347   class DelayedDiagnostics {
    348     /// \brief The stack of diagnostics that were delayed due to being
    349     /// produced during the parsing of a declaration.
    350     sema::DelayedDiagnostic *Stack;
    351 
    352     /// \brief The number of objects on the delayed-diagnostics stack.
    353     unsigned StackSize;
    354 
    355     /// \brief The current capacity of the delayed-diagnostics stack.
    356     unsigned StackCapacity;
    357 
    358     /// \brief The index of the first "active" delayed diagnostic in
    359     /// the stack.  When parsing class definitions, we ignore active
    360     /// delayed diagnostics from the surrounding context.
    361     unsigned ActiveStackBase;
    362 
    363     /// \brief The depth of the declarations we're currently parsing.
    364     /// This gets saved and reset whenever we enter a class definition.
    365     unsigned ParsingDepth;
    366 
    367   public:
    368     DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0),
    369       ActiveStackBase(0), ParsingDepth(0) {}
    370 
    371     ~DelayedDiagnostics() {
    372       delete[] reinterpret_cast<char*>(Stack);
    373     }
    374 
    375     /// Adds a delayed diagnostic.
    376     void add(const sema::DelayedDiagnostic &diag);
    377 
    378     /// Determines whether diagnostics should be delayed.
    379     bool shouldDelayDiagnostics() { return ParsingDepth > 0; }
    380 
    381     /// Observe that we've started parsing a declaration.  Access and
    382     /// deprecation diagnostics will be delayed; when the declaration
    383     /// is completed, all active delayed diagnostics will be evaluated
    384     /// in its context, and then active diagnostics stack will be
    385     /// popped down to the saved depth.
    386     ParsingDeclState pushParsingDecl() {
    387       ParsingDepth++;
    388 
    389       ParsingDeclState state;
    390       state.SavedStackSize = StackSize;
    391       return state;
    392     }
    393 
    394     /// Observe that we're completed parsing a declaration.
    395     static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl);
    396 
    397     /// Observe that we've started processing a different context, the
    398     /// contents of which are semantically separate from the
    399     /// declarations it may lexically appear in.  This sets aside the
    400     /// current stack of active diagnostics and starts afresh.
    401     ProcessingContextState pushContext() {
    402       assert(StackSize >= ActiveStackBase);
    403 
    404       ProcessingContextState state;
    405       state.SavedParsingDepth = ParsingDepth;
    406       state.SavedActiveStackBase = ActiveStackBase;
    407 
    408       ActiveStackBase = StackSize;
    409       ParsingDepth = 0;
    410 
    411       return state;
    412     }
    413 
    414     /// Observe that we've stopped processing a context.  This
    415     /// restores the previous stack of active diagnostics.
    416     void popContext(ProcessingContextState state) {
    417       assert(ActiveStackBase == StackSize);
    418       assert(ParsingDepth == 0);
    419       ActiveStackBase = state.SavedActiveStackBase;
    420       ParsingDepth = state.SavedParsingDepth;
    421     }
    422   } DelayedDiagnostics;
    423 
    424   /// A RAII object to temporarily push a declaration context.
    425   class ContextRAII {
    426   private:
    427     Sema &S;
    428     DeclContext *SavedContext;
    429     ProcessingContextState SavedContextState;
    430 
    431   public:
    432     ContextRAII(Sema &S, DeclContext *ContextToPush)
    433       : S(S), SavedContext(S.CurContext),
    434         SavedContextState(S.DelayedDiagnostics.pushContext())
    435     {
    436       assert(ContextToPush && "pushing null context");
    437       S.CurContext = ContextToPush;
    438     }
    439 
    440     void pop() {
    441       if (!SavedContext) return;
    442       S.CurContext = SavedContext;
    443       S.DelayedDiagnostics.popContext(SavedContextState);
    444       SavedContext = 0;
    445     }
    446 
    447     ~ContextRAII() {
    448       pop();
    449     }
    450   };
    451 
    452   /// WeakUndeclaredIdentifiers - Identifiers contained in
    453   /// #pragma weak before declared. rare. may alias another
    454   /// identifier, declared or undeclared
    455   llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
    456 
    457   /// \brief Load weak undeclared identifiers from the external source.
    458   void LoadExternalWeakUndeclaredIdentifiers();
    459 
    460   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
    461   /// #pragma weak during processing of other Decls.
    462   /// I couldn't figure out a clean way to generate these in-line, so
    463   /// we store them here and handle separately -- which is a hack.
    464   /// It would be best to refactor this.
    465   SmallVector<Decl*,2> WeakTopLevelDecl;
    466 
    467   IdentifierResolver IdResolver;
    468 
    469   /// Translation Unit Scope - useful to Objective-C actions that need
    470   /// to lookup file scope declarations in the "ordinary" C decl namespace.
    471   /// For example, user-defined classes, built-in "id" type, etc.
    472   Scope *TUScope;
    473 
    474   /// \brief The C++ "std" namespace, where the standard library resides.
    475   LazyDeclPtr StdNamespace;
    476 
    477   /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
    478   /// standard library.
    479   LazyDeclPtr StdBadAlloc;
    480 
    481   /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>.
    482   RecordDecl *CXXTypeInfoDecl;
    483 
    484   /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
    485   RecordDecl *MSVCGuidDecl;
    486 
    487   /// A flag to remember whether the implicit forms of operator new and delete
    488   /// have been declared.
    489   bool GlobalNewDeleteDeclared;
    490 
    491 
    492   /// A flag that is set when parsing a -dealloc method and no [super dealloc]
    493   /// call was found yet.
    494   bool ObjCShouldCallSuperDealloc;
    495   /// A flag that is set when parsing a -finalize method and no [super finalize]
    496   /// call was found yet.
    497   bool ObjCShouldCallSuperFinalize;
    498 
    499   /// \brief The set of declarations that have been referenced within
    500   /// a potentially evaluated expression.
    501   typedef SmallVector<std::pair<SourceLocation, Decl *>, 10>
    502     PotentiallyReferencedDecls;
    503 
    504   /// \brief A set of diagnostics that may be emitted.
    505   typedef SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10>
    506     PotentiallyEmittedDiagnostics;
    507 
    508   /// \brief Describes how the expressions currently being parsed are
    509   /// evaluated at run-time, if at all.
    510   enum ExpressionEvaluationContext {
    511     /// \brief The current expression and its subexpressions occur within an
    512     /// unevaluated operand (C++0x [expr]p8), such as a constant expression
    513     /// or the subexpression of \c sizeof, where the type or the value of the
    514     /// expression may be significant but no code will be generated to evaluate
    515     /// the value of the expression at run time.
    516     Unevaluated,
    517 
    518     /// \brief The current expression is potentially evaluated at run time,
    519     /// which means that code may be generated to evaluate the value of the
    520     /// expression at run time.
    521     PotentiallyEvaluated,
    522 
    523     /// \brief The current expression may be potentially evaluated or it may
    524     /// be unevaluated, but it is impossible to tell from the lexical context.
    525     /// This evaluation context is used primary for the operand of the C++
    526     /// \c typeid expression, whose argument is potentially evaluated only when
    527     /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2).
    528     PotentiallyPotentiallyEvaluated,
    529 
    530     /// \brief The current expression is potentially evaluated, but any
    531     /// declarations referenced inside that expression are only used if
    532     /// in fact the current expression is used.
    533     ///
    534     /// This value is used when parsing default function arguments, for which
    535     /// we would like to provide diagnostics (e.g., passing non-POD arguments
    536     /// through varargs) but do not want to mark declarations as "referenced"
    537     /// until the default argument is used.
    538     PotentiallyEvaluatedIfUsed
    539   };
    540 
    541   /// \brief Data structure used to record current or nested
    542   /// expression evaluation contexts.
    543   struct ExpressionEvaluationContextRecord {
    544     /// \brief The expression evaluation context.
    545     ExpressionEvaluationContext Context;
    546 
    547     /// \brief Whether the enclosing context needed a cleanup.
    548     bool ParentNeedsCleanups;
    549 
    550     /// \brief The number of temporaries that were active when we
    551     /// entered this expression evaluation context.
    552     unsigned NumTemporaries;
    553 
    554     /// \brief The set of declarations referenced within a
    555     /// potentially potentially-evaluated context.
    556     ///
    557     /// When leaving a potentially potentially-evaluated context, each
    558     /// of these elements will be as referenced if the corresponding
    559     /// potentially potentially evaluated expression is potentially
    560     /// evaluated.
    561     PotentiallyReferencedDecls *PotentiallyReferenced;
    562 
    563     /// \brief The set of diagnostics to emit should this potentially
    564     /// potentially-evaluated context become evaluated.
    565     PotentiallyEmittedDiagnostics *PotentiallyDiagnosed;
    566 
    567     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
    568                                       unsigned NumTemporaries,
    569                                       bool ParentNeedsCleanups)
    570       : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
    571         NumTemporaries(NumTemporaries),
    572         PotentiallyReferenced(0), PotentiallyDiagnosed(0) { }
    573 
    574     void addReferencedDecl(SourceLocation Loc, Decl *Decl) {
    575       if (!PotentiallyReferenced)
    576         PotentiallyReferenced = new PotentiallyReferencedDecls;
    577       PotentiallyReferenced->push_back(std::make_pair(Loc, Decl));
    578     }
    579 
    580     void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) {
    581       if (!PotentiallyDiagnosed)
    582         PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics;
    583       PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD));
    584     }
    585 
    586     void Destroy() {
    587       delete PotentiallyReferenced;
    588       delete PotentiallyDiagnosed;
    589       PotentiallyReferenced = 0;
    590       PotentiallyDiagnosed = 0;
    591     }
    592   };
    593 
    594   /// A stack of expression evaluation contexts.
    595   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
    596 
    597   /// SpecialMemberOverloadResult - The overloading result for a special member
    598   /// function.
    599   ///
    600   /// This is basically a wrapper around PointerIntPair. The lowest bit of the
    601   /// integer is used to determine whether we have a parameter qualification
    602   /// match, the second-lowest is whether we had success in resolving the
    603   /// overload to a unique non-deleted function.
    604   ///
    605   /// The ConstParamMatch bit represents whether, when looking up a copy
    606   /// constructor or assignment operator, we found a potential copy
    607   /// constructor/assignment operator whose first parameter is const-qualified.
    608   /// This is used for determining parameter types of other objects and is
    609   /// utterly meaningless on other types of special members.
    610   class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
    611     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
    612   public:
    613     SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
    614       : FastFoldingSetNode(ID)
    615     {}
    616 
    617     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
    618     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
    619 
    620     bool hasSuccess() const { return Pair.getInt() & 0x1; }
    621     void setSuccess(bool B) {
    622       Pair.setInt(unsigned(B) | hasConstParamMatch() << 1);
    623     }
    624 
    625     bool hasConstParamMatch() const { return Pair.getInt() & 0x2; }
    626     void setConstParamMatch(bool B) {
    627       Pair.setInt(B << 1 | unsigned(hasSuccess()));
    628     }
    629   };
    630 
    631   /// \brief A cache of special member function overload resolution results
    632   /// for C++ records.
    633   llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
    634 
    635   /// \brief The kind of translation unit we are processing.
    636   ///
    637   /// When we're processing a complete translation unit, Sema will perform
    638   /// end-of-translation-unit semantic tasks (such as creating
    639   /// initializers for tentative definitions in C) once parsing has
    640   /// completed. Modules and precompiled headers perform different kinds of
    641   /// checks.
    642   TranslationUnitKind TUKind;
    643 
    644   llvm::BumpPtrAllocator BumpAlloc;
    645 
    646   /// \brief The number of SFINAE diagnostics that have been trapped.
    647   unsigned NumSFINAEErrors;
    648 
    649   typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
    650     UnparsedDefaultArgInstantiationsMap;
    651 
    652   /// \brief A mapping from parameters with unparsed default arguments to the
    653   /// set of instantiations of each parameter.
    654   ///
    655   /// This mapping is a temporary data structure used when parsing
    656   /// nested class templates or nested classes of class templates,
    657   /// where we might end up instantiating an inner class before the
    658   /// default arguments of its methods have been parsed.
    659   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
    660 
    661   // Contains the locations of the beginning of unparsed default
    662   // argument locations.
    663   llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs;
    664 
    665   /// UndefinedInternals - all the used, undefined objects with
    666   /// internal linkage in this translation unit.
    667   llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals;
    668 
    669   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
    670   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
    671 
    672   /// Method Pool - allows efficient lookup when typechecking messages to "id".
    673   /// We need to maintain a list, since selectors can have differing signatures
    674   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
    675   /// of selectors are "overloaded").
    676   GlobalMethodPool MethodPool;
    677 
    678   /// Method selectors used in a @selector expression. Used for implementation
    679   /// of -Wselector.
    680   llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
    681 
    682   GlobalMethodPool::iterator ReadMethodPool(Selector Sel);
    683 
    684   /// Private Helper predicate to check for 'self'.
    685   bool isSelfExpr(Expr *RExpr);
    686 public:
    687   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
    688        TranslationUnitKind TUKind = TU_Complete,
    689        CodeCompleteConsumer *CompletionConsumer = 0);
    690   ~Sema();
    691 
    692   /// \brief Perform initialization that occurs after the parser has been
    693   /// initialized but before it parses anything.
    694   void Initialize();
    695 
    696   const LangOptions &getLangOptions() const { return LangOpts; }
    697   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
    698   FPOptions     &getFPOptions() { return FPFeatures; }
    699 
    700   DiagnosticsEngine &getDiagnostics() const { return Diags; }
    701   SourceManager &getSourceManager() const { return SourceMgr; }
    702   const TargetAttributesSema &getTargetAttributesSema() const;
    703   Preprocessor &getPreprocessor() const { return PP; }
    704   ASTContext &getASTContext() const { return Context; }
    705   ASTConsumer &getASTConsumer() const { return Consumer; }
    706   ASTMutationListener *getASTMutationListener() const;
    707 
    708   void PrintStats() const;
    709 
    710   /// \brief Helper class that creates diagnostics with optional
    711   /// template instantiation stacks.
    712   ///
    713   /// This class provides a wrapper around the basic DiagnosticBuilder
    714   /// class that emits diagnostics. SemaDiagnosticBuilder is
    715   /// responsible for emitting the diagnostic (as DiagnosticBuilder
    716   /// does) and, if the diagnostic comes from inside a template
    717   /// instantiation, printing the template instantiation stack as
    718   /// well.
    719   class SemaDiagnosticBuilder : public DiagnosticBuilder {
    720     Sema &SemaRef;
    721     unsigned DiagID;
    722 
    723   public:
    724     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
    725       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
    726 
    727     explicit SemaDiagnosticBuilder(Sema &SemaRef)
    728       : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { }
    729 
    730     ~SemaDiagnosticBuilder();
    731   };
    732 
    733   /// \brief Emit a diagnostic.
    734   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
    735 
    736   /// \brief Emit a partial diagnostic.
    737   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
    738 
    739   /// \brief Build a partial diagnostic.
    740   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
    741 
    742   bool findMacroSpelling(SourceLocation &loc, StringRef name);
    743 
    744   ExprResult Owned(Expr* E) { return E; }
    745   ExprResult Owned(ExprResult R) { return R; }
    746   StmtResult Owned(Stmt* S) { return S; }
    747 
    748   void ActOnEndOfTranslationUnit();
    749 
    750   void CheckDelegatingCtorCycles();
    751 
    752   Scope *getScopeForContext(DeclContext *Ctx);
    753 
    754   void PushFunctionScope();
    755   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
    756   void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0,
    757                                const Decl *D = 0, const BlockExpr *blkExpr = 0);
    758 
    759   sema::FunctionScopeInfo *getCurFunction() const {
    760     return FunctionScopes.back();
    761   }
    762 
    763   bool hasAnyUnrecoverableErrorsInThisFunction() const;
    764 
    765   /// \brief Retrieve the current block, if any.
    766   sema::BlockScopeInfo *getCurBlock();
    767 
    768   /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls
    769   SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
    770 
    771   //===--------------------------------------------------------------------===//
    772   // Type Analysis / Processing: SemaType.cpp.
    773   //
    774 
    775   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs);
    776   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) {
    777     return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR));
    778   }
    779   QualType BuildPointerType(QualType T,
    780                             SourceLocation Loc, DeclarationName Entity);
    781   QualType BuildReferenceType(QualType T, bool LValueRef,
    782                               SourceLocation Loc, DeclarationName Entity);
    783   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
    784                           Expr *ArraySize, unsigned Quals,
    785                           SourceRange Brackets, DeclarationName Entity);
    786   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
    787                               SourceLocation AttrLoc);
    788   QualType BuildFunctionType(QualType T,
    789                              QualType *ParamTypes, unsigned NumParamTypes,
    790                              bool Variadic, unsigned Quals,
    791                              RefQualifierKind RefQualifier,
    792                              SourceLocation Loc, DeclarationName Entity,
    793                              FunctionType::ExtInfo Info);
    794   QualType BuildMemberPointerType(QualType T, QualType Class,
    795                                   SourceLocation Loc,
    796                                   DeclarationName Entity);
    797   QualType BuildBlockPointerType(QualType T,
    798                                  SourceLocation Loc, DeclarationName Entity);
    799   QualType BuildParenType(QualType T);
    800   QualType BuildAtomicType(QualType T, SourceLocation Loc);
    801 
    802   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
    803   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
    804   TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
    805                                                TypeSourceInfo *ReturnTypeInfo);
    806   /// \brief Package the given type and TSI into a ParsedType.
    807   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
    808   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
    809   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
    810   static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
    811   bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range);
    812   bool CheckDistantExceptionSpec(QualType T);
    813   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
    814   bool CheckEquivalentExceptionSpec(
    815       const FunctionProtoType *Old, SourceLocation OldLoc,
    816       const FunctionProtoType *New, SourceLocation NewLoc);
    817   bool CheckEquivalentExceptionSpec(
    818       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
    819       const FunctionProtoType *Old, SourceLocation OldLoc,
    820       const FunctionProtoType *New, SourceLocation NewLoc,
    821       bool *MissingExceptionSpecification = 0,
    822       bool *MissingEmptyExceptionSpecification = 0,
    823       bool AllowNoexceptAllMatchWithNoSpec = false,
    824       bool IsOperatorNew = false);
    825   bool CheckExceptionSpecSubset(
    826       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
    827       const FunctionProtoType *Superset, SourceLocation SuperLoc,
    828       const FunctionProtoType *Subset, SourceLocation SubLoc);
    829   bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
    830       const FunctionProtoType *Target, SourceLocation TargetLoc,
    831       const FunctionProtoType *Source, SourceLocation SourceLoc);
    832 
    833   TypeResult ActOnTypeName(Scope *S, Declarator &D);
    834 
    835   /// \brief The parser has parsed the context-sensitive type 'instancetype'
    836   /// in an Objective-C message declaration. Return the appropriate type.
    837   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
    838 
    839   bool RequireCompleteType(SourceLocation Loc, QualType T,
    840                            const PartialDiagnostic &PD,
    841                            std::pair<SourceLocation, PartialDiagnostic> Note);
    842   bool RequireCompleteType(SourceLocation Loc, QualType T,
    843                            const PartialDiagnostic &PD);
    844   bool RequireCompleteType(SourceLocation Loc, QualType T,
    845                            unsigned DiagID);
    846   bool RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
    847                                std::pair<SourceLocation,
    848                                          PartialDiagnostic> Note);
    849 
    850   bool RequireLiteralType(SourceLocation Loc, QualType T,
    851                           const PartialDiagnostic &PD,
    852                           bool AllowIncompleteType = false);
    853 
    854   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
    855                              const CXXScopeSpec &SS, QualType T);
    856 
    857   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
    858   QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
    859   QualType BuildUnaryTransformType(QualType BaseType,
    860                                    UnaryTransformType::UTTKind UKind,
    861                                    SourceLocation Loc);
    862 
    863   //===--------------------------------------------------------------------===//
    864   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
    865   //
    866 
    867   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
    868 
    869   void DiagnoseUseOfUnimplementedSelectors();
    870 
    871   ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
    872                          Scope *S, CXXScopeSpec *SS = 0,
    873                          bool isClassName = false,
    874                          bool HasTrailingDot = false,
    875                          ParsedType ObjectType = ParsedType(),
    876                          bool WantNontrivialTypeSourceInfo = false,
    877                          IdentifierInfo **CorrectedII = 0);
    878   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
    879   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
    880   bool DiagnoseUnknownTypeName(const IdentifierInfo &II,
    881                                SourceLocation IILoc,
    882                                Scope *S,
    883                                CXXScopeSpec *SS,
    884                                ParsedType &SuggestedType);
    885 
    886   /// \brief Describes the result of the name lookup and resolution performed
    887   /// by \c ClassifyName().
    888   enum NameClassificationKind {
    889     NC_Unknown,
    890     NC_Error,
    891     NC_Keyword,
    892     NC_Type,
    893     NC_Expression,
    894     NC_NestedNameSpecifier,
    895     NC_TypeTemplate,
    896     NC_FunctionTemplate
    897   };
    898 
    899   class NameClassification {
    900     NameClassificationKind Kind;
    901     ExprResult Expr;
    902     TemplateName Template;
    903     ParsedType Type;
    904     const IdentifierInfo *Keyword;
    905 
    906     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
    907 
    908   public:
    909     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
    910 
    911     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
    912 
    913     NameClassification(const IdentifierInfo *Keyword)
    914       : Kind(NC_Keyword), Keyword(Keyword) { }
    915 
    916     static NameClassification Error() {
    917       return NameClassification(NC_Error);
    918     }
    919 
    920     static NameClassification Unknown() {
    921       return NameClassification(NC_Unknown);
    922     }
    923 
    924     static NameClassification NestedNameSpecifier() {
    925       return NameClassification(NC_NestedNameSpecifier);
    926     }
    927 
    928     static NameClassification TypeTemplate(TemplateName Name) {
    929       NameClassification Result(NC_TypeTemplate);
    930       Result.Template = Name;
    931       return Result;
    932     }
    933 
    934     static NameClassification FunctionTemplate(TemplateName Name) {
    935       NameClassification Result(NC_FunctionTemplate);
    936       Result.Template = Name;
    937       return Result;
    938     }
    939 
    940     NameClassificationKind getKind() const { return Kind; }
    941 
    942     ParsedType getType() const {
    943       assert(Kind == NC_Type);
    944       return Type;
    945     }
    946 
    947     ExprResult getExpression() const {
    948       assert(Kind == NC_Expression);
    949       return Expr;
    950     }
    951 
    952     TemplateName getTemplateName() const {
    953       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
    954       return Template;
    955     }
    956 
    957     TemplateNameKind getTemplateNameKind() const {
    958       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
    959       return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
    960     }
    961 };
    962 
    963   /// \brief Perform name lookup on the given name, classifying it based on
    964   /// the results of name lookup and the following token.
    965   ///
    966   /// This routine is used by the parser to resolve identifiers and help direct
    967   /// parsing. When the identifier cannot be found, this routine will attempt
    968   /// to correct the typo and classify based on the resulting name.
    969   ///
    970   /// \param S The scope in which we're performing name lookup.
    971   ///
    972   /// \param SS The nested-name-specifier that precedes the name.
    973   ///
    974   /// \param Name The identifier. If typo correction finds an alternative name,
    975   /// this pointer parameter will be updated accordingly.
    976   ///
    977   /// \param NameLoc The location of the identifier.
    978   ///
    979   /// \param NextToken The token following the identifier. Used to help
    980   /// disambiguate the name.
    981   NameClassification ClassifyName(Scope *S,
    982                                   CXXScopeSpec &SS,
    983                                   IdentifierInfo *&Name,
    984                                   SourceLocation NameLoc,
    985                                   const Token &NextToken);
    986 
    987   Decl *ActOnDeclarator(Scope *S, Declarator &D);
    988 
    989   Decl *HandleDeclarator(Scope *S, Declarator &D,
    990                          MultiTemplateParamsArg TemplateParameterLists);
    991   void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
    992                                         const LookupResult &Previous,
    993                                         Scope *S);
    994   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
    995   void DiagnoseFunctionSpecifiers(Declarator& D);
    996   void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
    997   void CheckShadow(Scope *S, VarDecl *D);
    998   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
    999   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
   1000   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
   1001                                     TypeSourceInfo *TInfo,
   1002                                     LookupResult &Previous);
   1003   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
   1004                                   LookupResult &Previous, bool &Redeclaration);
   1005   NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
   1006                                      TypeSourceInfo *TInfo,
   1007                                      LookupResult &Previous,
   1008                                      MultiTemplateParamsArg TemplateParamLists);
   1009   // Returns true if the variable declaration is a redeclaration
   1010   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
   1011   void CheckCompleteVariableDeclaration(VarDecl *var);
   1012   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
   1013                                      TypeSourceInfo *TInfo,
   1014                                      LookupResult &Previous,
   1015                                      MultiTemplateParamsArg TemplateParamLists,
   1016                                      bool &AddToScope);
   1017   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
   1018 
   1019   /// \brief The kind of constexpr declaration checking we are performing.
   1020   ///
   1021   /// The kind affects which diagnostics (if any) are emitted if the function
   1022   /// does not satisfy the requirements of a constexpr function declaration.
   1023   enum CheckConstexprKind {
   1024     /// \brief Check a constexpr function declaration, and produce errors if it
   1025     /// does not satisfy the requirements.
   1026     CCK_Declaration,
   1027     /// \brief Check a constexpr function template instantiation.
   1028     CCK_Instantiation,
   1029     /// \brief Produce notes explaining why an instantiation was not constexpr.
   1030     CCK_NoteNonConstexprInstantiation
   1031   };
   1032   bool CheckConstexprFunctionDecl(const FunctionDecl *FD, CheckConstexprKind CCK);
   1033   bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
   1034 
   1035   void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
   1036   // Returns true if the function declaration is a redeclaration
   1037   bool CheckFunctionDeclaration(Scope *S,
   1038                                 FunctionDecl *NewFD, LookupResult &Previous,
   1039                                 bool IsExplicitSpecialization);
   1040   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
   1041   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
   1042   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
   1043                                           SourceLocation Loc,
   1044                                           QualType T);
   1045   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
   1046                               SourceLocation NameLoc, IdentifierInfo *Name,
   1047                               QualType T, TypeSourceInfo *TSInfo,
   1048                               StorageClass SC, StorageClass SCAsWritten);
   1049   void ActOnParamDefaultArgument(Decl *param,
   1050                                  SourceLocation EqualLoc,
   1051                                  Expr *defarg);
   1052   void ActOnParamUnparsedDefaultArgument(Decl *param,
   1053                                          SourceLocation EqualLoc,
   1054                                          SourceLocation ArgLoc);
   1055   void ActOnParamDefaultArgumentError(Decl *param);
   1056   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
   1057                                SourceLocation EqualLoc);
   1058 
   1059   void CheckSelfReference(Decl *OrigDecl, Expr *E);
   1060   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
   1061                             bool TypeMayContainAuto);
   1062   void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
   1063   void ActOnInitializerError(Decl *Dcl);
   1064   void ActOnCXXForRangeDecl(Decl *D);
   1065   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
   1066   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
   1067   void FinalizeDeclaration(Decl *D);
   1068   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
   1069                                          Decl **Group,
   1070                                          unsigned NumDecls);
   1071   DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
   1072                                       bool TypeMayContainAuto = true);
   1073   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
   1074                                        SourceLocation LocAfterDecls);
   1075   void CheckForFunctionRedefinition(FunctionDecl *FD);
   1076   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
   1077   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
   1078   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
   1079 
   1080   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
   1081   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
   1082   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
   1083 
   1084   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
   1085   /// attribute for which parsing is delayed.
   1086   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
   1087 
   1088   /// \brief Diagnose any unused parameters in the given sequence of
   1089   /// ParmVarDecl pointers.
   1090   void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
   1091                                 ParmVarDecl * const *End);
   1092 
   1093   /// \brief Diagnose whether the size of parameters or return value of a
   1094   /// function or obj-c method definition is pass-by-value and larger than a
   1095   /// specified threshold.
   1096   void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
   1097                                               ParmVarDecl * const *End,
   1098                                               QualType ReturnTy,
   1099                                               NamedDecl *D);
   1100 
   1101   void DiagnoseInvalidJumps(Stmt *Body);
   1102   Decl *ActOnFileScopeAsmDecl(Expr *expr,
   1103                               SourceLocation AsmLoc,
   1104                               SourceLocation RParenLoc);
   1105 
   1106   /// \brief The parser has processed a module import declaration.
   1107   ///
   1108   /// \param ImportLoc The location of the '__import_module__' keyword.
   1109   ///
   1110   /// \param ModuleName The name of the module.
   1111   ///
   1112   /// \param ModuleNameLoc The location of the module name.
   1113   DeclResult ActOnModuleImport(SourceLocation ImportLoc,
   1114                                IdentifierInfo &ModuleName,
   1115                                SourceLocation ModuleNameLoc);
   1116 
   1117   /// \brief Diagnose that \p New is a module-private redeclaration of
   1118   /// \p Old.
   1119   void diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old,
   1120                                           SourceLocation ModulePrivateKeyword
   1121                                             = SourceLocation());
   1122 
   1123   /// \brief Retrieve a suitable printing policy.
   1124   PrintingPolicy getPrintingPolicy() const;
   1125 
   1126   /// Scope actions.
   1127   void ActOnPopScope(SourceLocation Loc, Scope *S);
   1128   void ActOnTranslationUnitScope(Scope *S);
   1129 
   1130   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
   1131                                    DeclSpec &DS);
   1132   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
   1133                                    DeclSpec &DS,
   1134                                    MultiTemplateParamsArg TemplateParams);
   1135 
   1136   StmtResult ActOnVlaStmt(const DeclSpec &DS);
   1137 
   1138   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
   1139                                     AccessSpecifier AS,
   1140                                     RecordDecl *Record);
   1141 
   1142   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
   1143                                        RecordDecl *Record);
   1144 
   1145   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
   1146                                     TagTypeKind NewTag, bool isDefinition,
   1147                                     SourceLocation NewTagLoc,
   1148                                     const IdentifierInfo &Name);
   1149 
   1150   enum TagUseKind {
   1151     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
   1152     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
   1153     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
   1154     TUK_Friend       // Friend declaration:  'friend struct foo;'
   1155   };
   1156 
   1157   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
   1158                  SourceLocation KWLoc, CXXScopeSpec &SS,
   1159                  IdentifierInfo *Name, SourceLocation NameLoc,
   1160                  AttributeList *Attr, AccessSpecifier AS,
   1161                  SourceLocation ModulePrivateLoc,
   1162                  MultiTemplateParamsArg TemplateParameterLists,
   1163                  bool &OwnedDecl, bool &IsDependent, bool ScopedEnum,
   1164                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
   1165 
   1166   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
   1167                                 unsigned TagSpec, SourceLocation TagLoc,
   1168                                 CXXScopeSpec &SS,
   1169                                 IdentifierInfo *Name, SourceLocation NameLoc,
   1170                                 AttributeList *Attr,
   1171                                 MultiTemplateParamsArg TempParamLists);
   1172 
   1173   TypeResult ActOnDependentTag(Scope *S,
   1174                                unsigned TagSpec,
   1175                                TagUseKind TUK,
   1176                                const CXXScopeSpec &SS,
   1177                                IdentifierInfo *Name,
   1178                                SourceLocation TagLoc,
   1179                                SourceLocation NameLoc);
   1180 
   1181   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
   1182                  IdentifierInfo *ClassName,
   1183                  SmallVectorImpl<Decl *> &Decls);
   1184   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
   1185                    Declarator &D, Expr *BitfieldWidth);
   1186 
   1187   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
   1188                          Declarator &D, Expr *BitfieldWidth, bool HasInit,
   1189                          AccessSpecifier AS);
   1190 
   1191   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
   1192                             TypeSourceInfo *TInfo,
   1193                             RecordDecl *Record, SourceLocation Loc,
   1194                             bool Mutable, Expr *BitfieldWidth, bool HasInit,
   1195                             SourceLocation TSSL,
   1196                             AccessSpecifier AS, NamedDecl *PrevDecl,
   1197                             Declarator *D = 0);
   1198 
   1199   enum CXXSpecialMember {
   1200     CXXDefaultConstructor,
   1201     CXXCopyConstructor,
   1202     CXXMoveConstructor,
   1203     CXXCopyAssignment,
   1204     CXXMoveAssignment,
   1205     CXXDestructor,
   1206     CXXInvalid
   1207   };
   1208   bool CheckNontrivialField(FieldDecl *FD);
   1209   void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem);
   1210   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
   1211   void ActOnLastBitfield(SourceLocation DeclStart,
   1212                          SmallVectorImpl<Decl *> &AllIvarDecls);
   1213   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
   1214                   Declarator &D, Expr *BitfieldWidth,
   1215                   tok::ObjCKeywordKind visibility);
   1216 
   1217   // This is used for both record definitions and ObjC interface declarations.
   1218   void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
   1219                    llvm::ArrayRef<Decl *> Fields,
   1220                    SourceLocation LBrac, SourceLocation RBrac,
   1221                    AttributeList *AttrList);
   1222 
   1223   /// ActOnTagStartDefinition - Invoked when we have entered the
   1224   /// scope of a tag's definition (e.g., for an enumeration, class,
   1225   /// struct, or union).
   1226   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
   1227 
   1228   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
   1229 
   1230   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
   1231   /// C++ record definition's base-specifiers clause and are starting its
   1232   /// member declarations.
   1233   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
   1234                                        SourceLocation FinalLoc,
   1235                                        SourceLocation LBraceLoc);
   1236 
   1237   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
   1238   /// the definition of a tag (enumeration, class, struct, or union).
   1239   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
   1240                                 SourceLocation RBraceLoc);
   1241 
   1242   void ActOnObjCContainerFinishDefinition();
   1243 
   1244   /// \brief Invoked when we must temporarily exit the objective-c container
   1245   /// scope for parsing/looking-up C constructs.
   1246   ///
   1247   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
   1248   void ActOnObjCTemporaryExitContainerContext();
   1249   void ActOnObjCReenterContainerContext();
   1250 
   1251   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
   1252   /// error parsing the definition of a tag.
   1253   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
   1254 
   1255   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
   1256                                       EnumConstantDecl *LastEnumConst,
   1257                                       SourceLocation IdLoc,
   1258                                       IdentifierInfo *Id,
   1259                                       Expr *val);
   1260 
   1261   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
   1262                           SourceLocation IdLoc, IdentifierInfo *Id,
   1263                           AttributeList *Attrs,
   1264                           SourceLocation EqualLoc, Expr *Val);
   1265   void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
   1266                      SourceLocation RBraceLoc, Decl *EnumDecl,
   1267                      Decl **Elements, unsigned NumElements,
   1268                      Scope *S, AttributeList *Attr);
   1269 
   1270   DeclContext *getContainingDC(DeclContext *DC);
   1271 
   1272   /// Set the current declaration context until it gets popped.
   1273   void PushDeclContext(Scope *S, DeclContext *DC);
   1274   void PopDeclContext();
   1275 
   1276   /// EnterDeclaratorContext - Used when we must lookup names in the context
   1277   /// of a declarator's nested name specifier.
   1278   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
   1279   void ExitDeclaratorContext(Scope *S);
   1280 
   1281   /// Push the parameters of D, which must be a function, into scope.
   1282   void ActOnReenterFunctionContext(Scope* S, Decl* D);
   1283   void ActOnExitFunctionContext() { PopDeclContext(); }
   1284 
   1285   DeclContext *getFunctionLevelDeclContext();
   1286 
   1287   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
   1288   /// to the function decl for the function being parsed.  If we're currently
   1289   /// in a 'block', this returns the containing context.
   1290   FunctionDecl *getCurFunctionDecl();
   1291 
   1292   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
   1293   /// the method decl for the method being parsed.  If we're currently
   1294   /// in a 'block', this returns the containing context.
   1295   ObjCMethodDecl *getCurMethodDecl();
   1296 
   1297   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
   1298   /// or C function we're in, otherwise return null.  If we're currently
   1299   /// in a 'block', this returns the containing context.
   1300   NamedDecl *getCurFunctionOrMethodDecl();
   1301 
   1302   /// Add this decl to the scope shadowed decl chains.
   1303   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
   1304 
   1305   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
   1306   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
   1307   /// true if 'D' belongs to the given declaration context.
   1308   ///
   1309   /// \param ExplicitInstantiationOrSpecialization When true, we are checking
   1310   /// whether the declaration is in scope for the purposes of explicit template
   1311   /// instantiation or specialization. The default is false.
   1312   bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0,
   1313                      bool ExplicitInstantiationOrSpecialization = false);
   1314 
   1315   /// Finds the scope corresponding to the given decl context, if it
   1316   /// happens to be an enclosing scope.  Otherwise return NULL.
   1317   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
   1318 
   1319   /// Subroutines of ActOnDeclarator().
   1320   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
   1321                                 TypeSourceInfo *TInfo);
   1322   void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
   1323   bool MergeFunctionDecl(FunctionDecl *New, Decl *Old);
   1324   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old);
   1325   void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old);
   1326   void MergeVarDecl(VarDecl *New, LookupResult &OldDecls);
   1327   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old);
   1328   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
   1329   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old);
   1330 
   1331   // AssignmentAction - This is used by all the assignment diagnostic functions
   1332   // to represent what is actually causing the operation
   1333   enum AssignmentAction {
   1334     AA_Assigning,
   1335     AA_Passing,
   1336     AA_Returning,
   1337     AA_Converting,
   1338     AA_Initializing,
   1339     AA_Sending,
   1340     AA_Casting
   1341   };
   1342 
   1343   /// C++ Overloading.
   1344   enum OverloadKind {
   1345     /// This is a legitimate overload: the existing declarations are
   1346     /// functions or function templates with different signatures.
   1347     Ovl_Overload,
   1348 
   1349     /// This is not an overload because the signature exactly matches
   1350     /// an existing declaration.
   1351     Ovl_Match,
   1352 
   1353     /// This is not an overload because the lookup results contain a
   1354     /// non-function.
   1355     Ovl_NonFunction
   1356   };
   1357   OverloadKind CheckOverload(Scope *S,
   1358                              FunctionDecl *New,
   1359                              const LookupResult &OldDecls,
   1360                              NamedDecl *&OldDecl,
   1361                              bool IsForUsingDecl);
   1362   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
   1363 
   1364   /// \brief Checks availability of the function depending on the current
   1365   /// function context.Inside an unavailable function,unavailability is ignored.
   1366   ///
   1367   /// \returns true if \arg FD is unavailable and current context is inside
   1368   /// an available function, false otherwise.
   1369   bool isFunctionConsideredUnavailable(FunctionDecl *FD);
   1370 
   1371   ImplicitConversionSequence
   1372   TryImplicitConversion(Expr *From, QualType ToType,
   1373                         bool SuppressUserConversions,
   1374                         bool AllowExplicit,
   1375                         bool InOverloadResolution,
   1376                         bool CStyle,
   1377                         bool AllowObjCWritebackConversion);
   1378 
   1379   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
   1380   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
   1381   bool IsComplexPromotion(QualType FromType, QualType ToType);
   1382   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
   1383                            bool InOverloadResolution,
   1384                            QualType& ConvertedType, bool &IncompatibleObjC);
   1385   bool isObjCPointerConversion(QualType FromType, QualType ToType,
   1386                                QualType& ConvertedType, bool &IncompatibleObjC);
   1387   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
   1388                                  QualType &ConvertedType);
   1389   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
   1390                                 QualType& ConvertedType);
   1391   bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
   1392                                 const FunctionProtoType *NewType);
   1393 
   1394   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
   1395   bool CheckPointerConversion(Expr *From, QualType ToType,
   1396                               CastKind &Kind,
   1397                               CXXCastPath& BasePath,
   1398                               bool IgnoreBaseAccess);
   1399   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
   1400                                  bool InOverloadResolution,
   1401                                  QualType &ConvertedType);
   1402   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
   1403                                     CastKind &Kind,
   1404                                     CXXCastPath &BasePath,
   1405                                     bool IgnoreBaseAccess);
   1406   bool IsQualificationConversion(QualType FromType, QualType ToType,
   1407                                  bool CStyle, bool &ObjCLifetimeConversion);
   1408   bool IsNoReturnConversion(QualType FromType, QualType ToType,
   1409                             QualType &ResultTy);
   1410   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
   1411 
   1412 
   1413   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
   1414                                              const VarDecl *NRVOCandidate,
   1415                                              QualType ResultType,
   1416                                              Expr *Value,
   1417                                              bool AllowNRVO = true);
   1418 
   1419   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
   1420                                     ExprResult Init);
   1421   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
   1422                                        SourceLocation EqualLoc,
   1423                                        ExprResult Init,
   1424                                        bool TopLevelOfInitList = false);
   1425   ExprResult PerformObjectArgumentInitialization(Expr *From,
   1426                                                  NestedNameSpecifier *Qualifier,
   1427                                                  NamedDecl *FoundDecl,
   1428                                                  CXXMethodDecl *Method);
   1429 
   1430   ExprResult PerformContextuallyConvertToBool(Expr *From);
   1431   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
   1432 
   1433   ExprResult
   1434   ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
   1435                                      const PartialDiagnostic &NotIntDiag,
   1436                                      const PartialDiagnostic &IncompleteDiag,
   1437                                      const PartialDiagnostic &ExplicitConvDiag,
   1438                                      const PartialDiagnostic &ExplicitConvNote,
   1439                                      const PartialDiagnostic &AmbigDiag,
   1440                                      const PartialDiagnostic &AmbigNote,
   1441                                      const PartialDiagnostic &ConvDiag);
   1442 
   1443   ExprResult PerformObjectMemberConversion(Expr *From,
   1444                                            NestedNameSpecifier *Qualifier,
   1445                                            NamedDecl *FoundDecl,
   1446                                            NamedDecl *Member);
   1447 
   1448   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
   1449   // TODO: make this is a typesafe union.
   1450   typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
   1451   typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
   1452 
   1453   void AddOverloadCandidate(NamedDecl *Function,
   1454                             DeclAccessPair FoundDecl,
   1455                             Expr **Args, unsigned NumArgs,
   1456                             OverloadCandidateSet &CandidateSet);
   1457 
   1458   void AddOverloadCandidate(FunctionDecl *Function,
   1459                             DeclAccessPair FoundDecl,
   1460                             Expr **Args, unsigned NumArgs,
   1461                             OverloadCandidateSet& CandidateSet,
   1462                             bool SuppressUserConversions = false,
   1463                             bool PartialOverloading = false);
   1464   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
   1465                              Expr **Args, unsigned NumArgs,
   1466                              OverloadCandidateSet& CandidateSet,
   1467                              bool SuppressUserConversions = false);
   1468   void AddMethodCandidate(DeclAccessPair FoundDecl,
   1469                           QualType ObjectType,
   1470                           Expr::Classification ObjectClassification,
   1471                           Expr **Args, unsigned NumArgs,
   1472                           OverloadCandidateSet& CandidateSet,
   1473                           bool SuppressUserConversion = false);
   1474   void AddMethodCandidate(CXXMethodDecl *Method,
   1475                           DeclAccessPair FoundDecl,
   1476                           CXXRecordDecl *ActingContext, QualType ObjectType,
   1477                           Expr::Classification ObjectClassification,
   1478                           Expr **Args, unsigned NumArgs,
   1479                           OverloadCandidateSet& CandidateSet,
   1480                           bool SuppressUserConversions = false);
   1481   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
   1482                                   DeclAccessPair FoundDecl,
   1483                                   CXXRecordDecl *ActingContext,
   1484                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
   1485                                   QualType ObjectType,
   1486                                   Expr::Classification ObjectClassification,
   1487                                   Expr **Args, unsigned NumArgs,
   1488                                   OverloadCandidateSet& CandidateSet,
   1489                                   bool SuppressUserConversions = false);
   1490   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
   1491                                     DeclAccessPair FoundDecl,
   1492                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
   1493                                     Expr **Args, unsigned NumArgs,
   1494                                     OverloadCandidateSet& CandidateSet,
   1495                                     bool SuppressUserConversions = false);
   1496   void AddConversionCandidate(CXXConversionDecl *Conversion,
   1497                               DeclAccessPair FoundDecl,
   1498                               CXXRecordDecl *ActingContext,
   1499                               Expr *From, QualType ToType,
   1500                               OverloadCandidateSet& CandidateSet);
   1501   void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
   1502                                       DeclAccessPair FoundDecl,
   1503                                       CXXRecordDecl *ActingContext,
   1504                                       Expr *From, QualType ToType,
   1505                                       OverloadCandidateSet &CandidateSet);
   1506   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
   1507                              DeclAccessPair FoundDecl,
   1508                              CXXRecordDecl *ActingContext,
   1509                              const FunctionProtoType *Proto,
   1510                              Expr *Object, Expr **Args, unsigned NumArgs,
   1511                              OverloadCandidateSet& CandidateSet);
   1512   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
   1513                                    SourceLocation OpLoc,
   1514                                    Expr **Args, unsigned NumArgs,
   1515                                    OverloadCandidateSet& CandidateSet,
   1516                                    SourceRange OpRange = SourceRange());
   1517   void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
   1518                            Expr **Args, unsigned NumArgs,
   1519                            OverloadCandidateSet& CandidateSet,
   1520                            bool IsAssignmentOperator = false,
   1521                            unsigned NumContextualBoolArguments = 0);
   1522   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
   1523                                     SourceLocation OpLoc,
   1524                                     Expr **Args, unsigned NumArgs,
   1525                                     OverloadCandidateSet& CandidateSet);
   1526   void AddArgumentDependentLookupCandidates(DeclarationName Name,
   1527                                             bool Operator,
   1528                                             Expr **Args, unsigned NumArgs,
   1529                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
   1530                                             OverloadCandidateSet& CandidateSet,
   1531                                             bool PartialOverloading = false,
   1532                                         bool StdNamespaceIsAssociated = false);
   1533 
   1534   // Emit as a 'note' the specific overload candidate
   1535   void NoteOverloadCandidate(FunctionDecl *Fn);
   1536 
   1537   // Emit as a series of 'note's all template and non-templates
   1538   // identified by the expression Expr
   1539   void NoteAllOverloadCandidates(Expr* E);
   1540 
   1541   // [PossiblyAFunctionType]  -->   [Return]
   1542   // NonFunctionType --> NonFunctionType
   1543   // R (A) --> R(A)
   1544   // R (*)(A) --> R (A)
   1545   // R (&)(A) --> R (A)
   1546   // R (S::*)(A) --> R (A)
   1547   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
   1548 
   1549   FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
   1550                                                    bool Complain,
   1551                                                    DeclAccessPair &Found);
   1552 
   1553   FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
   1554                                                    bool Complain = false,
   1555                                                    DeclAccessPair* Found = 0);
   1556 
   1557   bool ResolveAndFixSingleFunctionTemplateSpecialization(
   1558                       ExprResult &SrcExpr,
   1559                       bool DoFunctionPointerConverion = false,
   1560                       bool Complain = false,
   1561                       const SourceRange& OpRangeForComplaining = SourceRange(),
   1562                       QualType DestTypeForComplaining = QualType(),
   1563                       unsigned DiagIDForComplaining = 0);
   1564 
   1565 
   1566   Expr *FixOverloadedFunctionReference(Expr *E,
   1567                                        DeclAccessPair FoundDecl,
   1568                                        FunctionDecl *Fn);
   1569   ExprResult FixOverloadedFunctionReference(ExprResult,
   1570                                             DeclAccessPair FoundDecl,
   1571                                             FunctionDecl *Fn);
   1572 
   1573   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
   1574                                    Expr **Args, unsigned NumArgs,
   1575                                    OverloadCandidateSet &CandidateSet,
   1576                                    bool PartialOverloading = false);
   1577 
   1578   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
   1579                                      UnresolvedLookupExpr *ULE,
   1580                                      SourceLocation LParenLoc,
   1581                                      Expr **Args, unsigned NumArgs,
   1582                                      SourceLocation RParenLoc,
   1583                                      Expr *ExecConfig);
   1584 
   1585   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
   1586                                      unsigned Opc,
   1587                                      const UnresolvedSetImpl &Fns,
   1588                                      Expr *input);
   1589 
   1590   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
   1591                                    unsigned Opc,
   1592                                    const UnresolvedSetImpl &Fns,
   1593                                    Expr *LHS, Expr *RHS);
   1594 
   1595   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
   1596                                                 SourceLocation RLoc,
   1597                                                 Expr *Base,Expr *Idx);
   1598 
   1599   ExprResult
   1600   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
   1601                             SourceLocation LParenLoc, Expr **Args,
   1602                             unsigned NumArgs, SourceLocation RParenLoc);
   1603   ExprResult
   1604   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
   1605                                Expr **Args, unsigned NumArgs,
   1606                                SourceLocation RParenLoc);
   1607 
   1608   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
   1609                                       SourceLocation OpLoc);
   1610 
   1611   /// CheckCallReturnType - Checks that a call expression's return type is
   1612   /// complete. Returns true on failure. The location passed in is the location
   1613   /// that best represents the call.
   1614   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
   1615                            CallExpr *CE, FunctionDecl *FD);
   1616 
   1617   /// Helpers for dealing with blocks and functions.
   1618   bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
   1619                                 bool CheckParameterNames);
   1620   void CheckCXXDefaultArguments(FunctionDecl *FD);
   1621   void CheckExtraCXXDefaultArguments(Declarator &D);
   1622   Scope *getNonFieldDeclScope(Scope *S);
   1623 
   1624   /// \name Name lookup
   1625   ///
   1626   /// These routines provide name lookup that is used during semantic
   1627   /// analysis to resolve the various kinds of names (identifiers,
   1628   /// overloaded operator names, constructor names, etc.) into zero or
   1629   /// more declarations within a particular scope. The major entry
   1630   /// points are LookupName, which performs unqualified name lookup,
   1631   /// and LookupQualifiedName, which performs qualified name lookup.
   1632   ///
   1633   /// All name lookup is performed based on some specific criteria,
   1634   /// which specify what names will be visible to name lookup and how
   1635   /// far name lookup should work. These criteria are important both
   1636   /// for capturing language semantics (certain lookups will ignore
   1637   /// certain names, for example) and for performance, since name
   1638   /// lookup is often a bottleneck in the compilation of C++. Name
   1639   /// lookup criteria is specified via the LookupCriteria enumeration.
   1640   ///
   1641   /// The results of name lookup can vary based on the kind of name
   1642   /// lookup performed, the current language, and the translation
   1643   /// unit. In C, for example, name lookup will either return nothing
   1644   /// (no entity found) or a single declaration. In C++, name lookup
   1645   /// can additionally refer to a set of overloaded functions or
   1646   /// result in an ambiguity. All of the possible results of name
   1647   /// lookup are captured by the LookupResult class, which provides
   1648   /// the ability to distinguish among them.
   1649   //@{
   1650 
   1651   /// @brief Describes the kind of name lookup to perform.
   1652   enum LookupNameKind {
   1653     /// Ordinary name lookup, which finds ordinary names (functions,
   1654     /// variables, typedefs, etc.) in C and most kinds of names
   1655     /// (functions, variables, members, types, etc.) in C++.
   1656     LookupOrdinaryName = 0,
   1657     /// Tag name lookup, which finds the names of enums, classes,
   1658     /// structs, and unions.
   1659     LookupTagName,
   1660     /// Label name lookup.
   1661     LookupLabel,
   1662     /// Member name lookup, which finds the names of
   1663     /// class/struct/union members.
   1664     LookupMemberName,
   1665     /// Look up of an operator name (e.g., operator+) for use with
   1666     /// operator overloading. This lookup is similar to ordinary name
   1667     /// lookup, but will ignore any declarations that are class members.
   1668     LookupOperatorName,
   1669     /// Look up of a name that precedes the '::' scope resolution
   1670     /// operator in C++. This lookup completely ignores operator, object,
   1671     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
   1672     LookupNestedNameSpecifierName,
   1673     /// Look up a namespace name within a C++ using directive or
   1674     /// namespace alias definition, ignoring non-namespace names (C++
   1675     /// [basic.lookup.udir]p1).
   1676     LookupNamespaceName,
   1677     /// Look up all declarations in a scope with the given name,
   1678     /// including resolved using declarations.  This is appropriate
   1679     /// for checking redeclarations for a using declaration.
   1680     LookupUsingDeclName,
   1681     /// Look up an ordinary name that is going to be redeclared as a
   1682     /// name with linkage. This lookup ignores any declarations that
   1683     /// are outside of the current scope unless they have linkage. See
   1684     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
   1685     LookupRedeclarationWithLinkage,
   1686     /// Look up the name of an Objective-C protocol.
   1687     LookupObjCProtocolName,
   1688     /// Look up implicit 'self' parameter of an objective-c method.
   1689     LookupObjCImplicitSelfParam,
   1690     /// \brief Look up any declaration with any name.
   1691     LookupAnyName
   1692   };
   1693 
   1694   /// \brief Specifies whether (or how) name lookup is being performed for a
   1695   /// redeclaration (vs. a reference).
   1696   enum RedeclarationKind {
   1697     /// \brief The lookup is a reference to this name that is not for the
   1698     /// purpose of redeclaring the name.
   1699     NotForRedeclaration = 0,
   1700     /// \brief The lookup results will be used for redeclaration of a name,
   1701     /// if an entity by that name already exists.
   1702     ForRedeclaration
   1703   };
   1704 
   1705 private:
   1706   bool CppLookupName(LookupResult &R, Scope *S);
   1707 
   1708   SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
   1709                                                    CXXSpecialMember SM,
   1710                                                    bool ConstArg,
   1711                                                    bool VolatileArg,
   1712                                                    bool RValueThis,
   1713                                                    bool ConstThis,
   1714                                                    bool VolatileThis);
   1715 
   1716   // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
   1717   //
   1718   // The boolean value will be true to indicate that the namespace was loaded
   1719   // from an AST/PCH file, or false otherwise.
   1720   llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces;
   1721 
   1722   /// \brief Whether we have already loaded known namespaces from an extenal
   1723   /// source.
   1724   bool LoadedExternalKnownNamespaces;
   1725 
   1726 public:
   1727   /// \brief Look up a name, looking for a single declaration.  Return
   1728   /// null if the results were absent, ambiguous, or overloaded.
   1729   ///
   1730   /// It is preferable to use the elaborated form and explicitly handle
   1731   /// ambiguity and overloaded.
   1732   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
   1733                               SourceLocation Loc,
   1734                               LookupNameKind NameKind,
   1735                               RedeclarationKind Redecl
   1736                                 = NotForRedeclaration);
   1737   bool LookupName(LookupResult &R, Scope *S,
   1738                   bool AllowBuiltinCreation = false);
   1739   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
   1740                            bool InUnqualifiedLookup = false);
   1741   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
   1742                         bool AllowBuiltinCreation = false,
   1743                         bool EnteringContext = false);
   1744   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc);
   1745 
   1746   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
   1747                                     QualType T1, QualType T2,
   1748                                     UnresolvedSetImpl &Functions);
   1749 
   1750   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
   1751                                  SourceLocation GnuLabelLoc = SourceLocation());
   1752 
   1753   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
   1754   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
   1755   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
   1756                                                unsigned Quals,
   1757                                                bool *ConstParam = 0);
   1758   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
   1759                                          bool RValueThis, unsigned ThisQuals,
   1760                                          bool *ConstParam = 0);
   1761   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class);
   1762   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, bool RValueThis,
   1763                                         unsigned ThisQuals);
   1764   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
   1765 
   1766   void ArgumentDependentLookup(DeclarationName Name, bool Operator,
   1767                                Expr **Args, unsigned NumArgs,
   1768                                ADLResult &Functions,
   1769                                bool StdNamespaceIsAssociated = false);
   1770 
   1771   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
   1772                           VisibleDeclConsumer &Consumer,
   1773                           bool IncludeGlobalScope = true);
   1774   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
   1775                           VisibleDeclConsumer &Consumer,
   1776                           bool IncludeGlobalScope = true);
   1777 
   1778   /// \brief The context in which typo-correction occurs.
   1779   ///
   1780   /// The typo-correction context affects which keywords (if any) are
   1781   /// considered when trying to correct for typos.
   1782   enum CorrectTypoContext {
   1783     /// \brief An unknown context, where any keyword might be valid.
   1784     CTC_Unknown,
   1785     /// \brief A context where no keywords are used (e.g. we expect an actual
   1786     /// name).
   1787     CTC_NoKeywords,
   1788     /// \brief A context where we're correcting a type name.
   1789     CTC_Type,
   1790     /// \brief An expression context.
   1791     CTC_Expression,
   1792     /// \brief A type cast, or anything else that can be followed by a '<'.
   1793     CTC_CXXCasts,
   1794     /// \brief A member lookup context.
   1795     CTC_MemberLookup,
   1796     /// \brief An Objective-C ivar lookup context (e.g., self->ivar).
   1797     CTC_ObjCIvarLookup,
   1798     /// \brief An Objective-C property lookup context (e.g., self.prop).
   1799     CTC_ObjCPropertyLookup,
   1800     /// \brief The receiver of an Objective-C message send within an
   1801     /// Objective-C method where 'super' is a valid keyword.
   1802     CTC_ObjCMessageReceiver
   1803   };
   1804 
   1805   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
   1806                              Sema::LookupNameKind LookupKind,
   1807                              Scope *S, CXXScopeSpec *SS,
   1808                              DeclContext *MemberContext = NULL,
   1809                              bool EnteringContext = false,
   1810                              CorrectTypoContext CTC = CTC_Unknown,
   1811                              const ObjCObjectPointerType *OPT = NULL);
   1812 
   1813   void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
   1814                                    AssociatedNamespaceSet &AssociatedNamespaces,
   1815                                    AssociatedClassSet &AssociatedClasses);
   1816 
   1817   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
   1818                             bool ConsiderLinkage,
   1819                             bool ExplicitInstantiationOrSpecialization);
   1820 
   1821   bool DiagnoseAmbiguousLookup(LookupResult &Result);
   1822   //@}
   1823 
   1824   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
   1825                                           SourceLocation IdLoc,
   1826                                           bool TypoCorrection = false);
   1827   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
   1828                                  Scope *S, bool ForRedeclaration,
   1829                                  SourceLocation Loc);
   1830   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
   1831                                       Scope *S);
   1832   void AddKnownFunctionAttributes(FunctionDecl *FD);
   1833 
   1834   // More parsing and symbol table subroutines.
   1835 
   1836   // Decl attributes - this routine is the top level dispatcher.
   1837   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
   1838                            bool NonInheritable = true, bool Inheritable = true);
   1839   void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
   1840                            bool NonInheritable = true, bool Inheritable = true);
   1841   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
   1842                                       const AttributeList *AttrList);
   1843 
   1844   void checkUnusedDeclAttributes(Declarator &D);
   1845 
   1846   bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
   1847   bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC);
   1848   bool CheckNoReturnAttr(const AttributeList &attr);
   1849 
   1850   void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
   1851                            bool &IncompleteImpl, unsigned DiagID);
   1852   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
   1853                                    ObjCMethodDecl *MethodDecl,
   1854                                    bool IsProtocolMethodDecl);
   1855 
   1856   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
   1857                                    ObjCMethodDecl *Overridden,
   1858                                    bool IsProtocolMethodDecl);
   1859 
   1860   /// WarnExactTypedMethods - This routine issues a warning if method
   1861   /// implementation declaration matches exactly that of its declaration.
   1862   void WarnExactTypedMethods(ObjCMethodDecl *Method,
   1863                              ObjCMethodDecl *MethodDecl,
   1864                              bool IsProtocolMethodDecl);
   1865 
   1866   bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
   1867                           ObjCInterfaceDecl *IDecl);
   1868 
   1869   typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet;
   1870   typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
   1871 
   1872   /// CheckProtocolMethodDefs - This routine checks unimplemented
   1873   /// methods declared in protocol, and those referenced by it.
   1874   /// \param IDecl - Used for checking for methods which may have been
   1875   /// inherited.
   1876   void CheckProtocolMethodDefs(SourceLocation ImpLoc,
   1877                                ObjCProtocolDecl *PDecl,
   1878                                bool& IncompleteImpl,
   1879                                const SelectorSet &InsMap,
   1880                                const SelectorSet &ClsMap,
   1881                                ObjCContainerDecl *CDecl);
   1882 
   1883   /// CheckImplementationIvars - This routine checks if the instance variables
   1884   /// listed in the implelementation match those listed in the interface.
   1885   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
   1886                                 ObjCIvarDecl **Fields, unsigned nIvars,
   1887                                 SourceLocation Loc);
   1888 
   1889   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
   1890   /// remains unimplemented in the class or category @implementation.
   1891   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
   1892                                  ObjCContainerDecl* IDecl,
   1893                                  bool IncompleteImpl = false);
   1894 
   1895   /// DiagnoseUnimplementedProperties - This routine warns on those properties
   1896   /// which must be implemented by this implementation.
   1897   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
   1898                                        ObjCContainerDecl *CDecl,
   1899                                        const SelectorSet &InsMap);
   1900 
   1901   /// DefaultSynthesizeProperties - This routine default synthesizes all
   1902   /// properties which must be synthesized in class's @implementation.
   1903   void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
   1904                                     ObjCInterfaceDecl *IDecl);
   1905   void DefaultSynthesizeProperties(Scope *S, Decl *D);
   1906 
   1907   /// CollectImmediateProperties - This routine collects all properties in
   1908   /// the class and its conforming protocols; but not those it its super class.
   1909   void CollectImmediateProperties(ObjCContainerDecl *CDecl,
   1910             llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
   1911             llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
   1912 
   1913 
   1914   /// LookupPropertyDecl - Looks up a property in the current class and all
   1915   /// its protocols.
   1916   ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl,
   1917                                        IdentifierInfo *II);
   1918 
   1919   /// Called by ActOnProperty to handle @property declarations in
   1920   ////  class extensions.
   1921   Decl *HandlePropertyInClassExtension(Scope *S,
   1922                                        SourceLocation AtLoc,
   1923                                        FieldDeclarator &FD,
   1924                                        Selector GetterSel,
   1925                                        Selector SetterSel,
   1926                                        const bool isAssign,
   1927                                        const bool isReadWrite,
   1928                                        const unsigned Attributes,
   1929                                        bool *isOverridingProperty,
   1930                                        TypeSourceInfo *T,
   1931                                        tok::ObjCKeywordKind MethodImplKind);
   1932 
   1933   /// Called by ActOnProperty and HandlePropertyInClassExtension to
   1934   ///  handle creating the ObjcPropertyDecl for a category or @interface.
   1935   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
   1936                                        ObjCContainerDecl *CDecl,
   1937                                        SourceLocation AtLoc,
   1938                                        FieldDeclarator &FD,
   1939                                        Selector GetterSel,
   1940                                        Selector SetterSel,
   1941                                        const bool isAssign,
   1942                                        const bool isReadWrite,
   1943                                        const unsigned Attributes,
   1944                                        TypeSourceInfo *T,
   1945                                        tok::ObjCKeywordKind MethodImplKind,
   1946                                        DeclContext *lexicalDC = 0);
   1947 
   1948   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
   1949   /// warning) when atomic property has one but not the other user-declared
   1950   /// setter or getter.
   1951   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
   1952                                        ObjCContainerDecl* IDecl);
   1953 
   1954   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
   1955 
   1956   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
   1957 
   1958   enum MethodMatchStrategy {
   1959     MMS_loose,
   1960     MMS_strict
   1961   };
   1962 
   1963   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
   1964   /// true, or false, accordingly.
   1965   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
   1966                                   const ObjCMethodDecl *PrevMethod,
   1967                                   MethodMatchStrategy strategy = MMS_strict);
   1968 
   1969   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
   1970   /// or protocol against those declared in their implementations.
   1971   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
   1972                                   const SelectorSet &ClsMap,
   1973                                   SelectorSet &InsMapSeen,
   1974                                   SelectorSet &ClsMapSeen,
   1975                                   ObjCImplDecl* IMPDecl,
   1976                                   ObjCContainerDecl* IDecl,
   1977                                   bool &IncompleteImpl,
   1978                                   bool ImmediateClass,
   1979                                   bool WarnExactMatch=false);
   1980 
   1981   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
   1982   /// category matches with those implemented in its primary class and
   1983   /// warns each time an exact match is found.
   1984   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
   1985 
   1986 private:
   1987   /// AddMethodToGlobalPool - Add an instance or factory method to the global
   1988   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
   1989   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
   1990 
   1991   /// LookupMethodInGlobalPool - Returns the instance or factory method and
   1992   /// optionally warns if there are multiple signatures.
   1993   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
   1994                                            bool receiverIdOrClass,
   1995                                            bool warn, bool instance);
   1996 
   1997 public:
   1998   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
   1999   /// unit are added to a global pool. This allows us to efficiently associate
   2000   /// a selector with a method declaraation for purposes of typechecking
   2001   /// messages sent to "id" (where the class of the object is unknown).
   2002   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
   2003     AddMethodToGlobalPool(Method, impl, /*instance*/true);
   2004   }
   2005 
   2006   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
   2007   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
   2008     AddMethodToGlobalPool(Method, impl, /*instance*/false);
   2009   }
   2010 
   2011   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
   2012   /// pool.
   2013   void AddAnyMethodToGlobalPool(Decl *D);
   2014 
   2015   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
   2016   /// there are multiple signatures.
   2017   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
   2018                                                    bool receiverIdOrClass=false,
   2019                                                    bool warn=true) {
   2020     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
   2021                                     warn, /*instance*/true);
   2022   }
   2023 
   2024   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
   2025   /// there are multiple signatures.
   2026   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
   2027                                                   bool receiverIdOrClass=false,
   2028                                                   bool warn=true) {
   2029     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
   2030                                     warn, /*instance*/false);
   2031   }
   2032 
   2033   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
   2034   /// implementation.
   2035   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
   2036 
   2037   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
   2038   /// initialization.
   2039   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
   2040                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
   2041 
   2042   //===--------------------------------------------------------------------===//
   2043   // Statement Parsing Callbacks: SemaStmt.cpp.
   2044 public:
   2045   class FullExprArg {
   2046   public:
   2047     FullExprArg(Sema &actions) : E(0) { }
   2048 
   2049     // FIXME: The const_cast here is ugly. RValue references would make this
   2050     // much nicer (or we could duplicate a bunch of the move semantics
   2051     // emulation code from Ownership.h).
   2052     FullExprArg(const FullExprArg& Other) : E(Other.E) {}
   2053 
   2054     ExprResult release() {
   2055       return move(E);
   2056     }
   2057 
   2058     Expr *get() const { return E; }
   2059 
   2060     Expr *operator->() {
   2061       return E;
   2062     }
   2063 
   2064   private:
   2065     // FIXME: No need to make the entire Sema class a friend when it's just
   2066     // Sema::MakeFullExpr that needs access to the constructor below.
   2067     friend class Sema;
   2068 
   2069     explicit FullExprArg(Expr *expr) : E(expr) {}
   2070 
   2071     Expr *E;
   2072   };
   2073 
   2074   FullExprArg MakeFullExpr(Expr *Arg) {
   2075     return FullExprArg(ActOnFinishFullExpr(Arg).release());
   2076   }
   2077 
   2078   StmtResult ActOnExprStmt(FullExprArg Expr);
   2079 
   2080   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
   2081                            bool HasLeadingEmptyMacro = false);
   2082   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
   2083                                        MultiStmtArg Elts,
   2084                                        bool isStmtExpr);
   2085   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
   2086                                    SourceLocation StartLoc,
   2087                                    SourceLocation EndLoc);
   2088   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
   2089   StmtResult ActOnForEachLValueExpr(Expr *E);
   2090   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
   2091                                    SourceLocation DotDotDotLoc, Expr *RHSVal,
   2092                                    SourceLocation ColonLoc);
   2093   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
   2094 
   2095   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
   2096                                       SourceLocation ColonLoc,
   2097                                       Stmt *SubStmt, Scope *CurScope);
   2098   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
   2099                             SourceLocation ColonLoc, Stmt *SubStmt);
   2100 
   2101   StmtResult ActOnIfStmt(SourceLocation IfLoc,
   2102                          FullExprArg CondVal, Decl *CondVar,
   2103                          Stmt *ThenVal,
   2104                          SourceLocation ElseLoc, Stmt *ElseVal);
   2105   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
   2106                                             Expr *Cond,
   2107                                             Decl *CondVar);
   2108   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
   2109                                            Stmt *Switch, Stmt *Body);
   2110   StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
   2111                             FullExprArg Cond,
   2112                             Decl *CondVar, Stmt *Body);
   2113   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
   2114                                  SourceLocation WhileLoc,
   2115                                  SourceLocation CondLParen, Expr *Cond,
   2116                                  SourceLocation CondRParen);
   2117 
   2118   StmtResult ActOnForStmt(SourceLocation ForLoc,
   2119                           SourceLocation LParenLoc,
   2120                           Stmt *First, FullExprArg Second,
   2121                           Decl *SecondVar,
   2122                           FullExprArg Third,
   2123                           SourceLocation RParenLoc,
   2124                           Stmt *Body);
   2125   ExprResult ActOnObjCForCollectionOperand(SourceLocation forLoc,
   2126                                            Expr *collection);
   2127   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
   2128                                         SourceLocation LParenLoc,
   2129                                         Stmt *First, Expr *Second,
   2130                                         SourceLocation RParenLoc, Stmt *Body);
   2131   StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc,
   2132                                   SourceLocation LParenLoc, Stmt *LoopVar,
   2133                                   SourceLocation ColonLoc, Expr *Collection,
   2134                                   SourceLocation RParenLoc);
   2135   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
   2136                                   SourceLocation ColonLoc,
   2137                                   Stmt *RangeDecl, Stmt *BeginEndDecl,
   2138                                   Expr *Cond, Expr *Inc,
   2139                                   Stmt *LoopVarDecl,
   2140                                   SourceLocation RParenLoc);
   2141   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
   2142 
   2143   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
   2144                            SourceLocation LabelLoc,
   2145                            LabelDecl *TheDecl);
   2146   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
   2147                                    SourceLocation StarLoc,
   2148                                    Expr *DestExp);
   2149   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
   2150   StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
   2151 
   2152   const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
   2153                                          bool AllowFunctionParameters);
   2154 
   2155   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
   2156   StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
   2157 
   2158   StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
   2159                           bool IsSimple, bool IsVolatile,
   2160                           unsigned NumOutputs, unsigned NumInputs,
   2161                           IdentifierInfo **Names,
   2162                           MultiExprArg Constraints,
   2163                           MultiExprArg Exprs,
   2164                           Expr *AsmString,
   2165                           MultiExprArg Clobbers,
   2166                           SourceLocation RParenLoc,
   2167                           bool MSAsm = false);
   2168 
   2169 
   2170   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
   2171                                   SourceLocation StartLoc,
   2172                                   SourceLocation IdLoc, IdentifierInfo *Id,
   2173                                   bool Invalid = false);
   2174 
   2175   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
   2176 
   2177   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
   2178                                   Decl *Parm, Stmt *Body);
   2179 
   2180   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
   2181 
   2182   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
   2183                                 MultiStmtArg Catch, Stmt *Finally);
   2184 
   2185   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
   2186   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
   2187                                   Scope *CurScope);
   2188   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
   2189                                             Expr *operand);
   2190   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
   2191                                          Expr *SynchExpr,
   2192                                          Stmt *SynchBody);
   2193 
   2194   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
   2195 
   2196   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
   2197                                      SourceLocation StartLoc,
   2198                                      SourceLocation IdLoc,
   2199                                      IdentifierInfo *Id);
   2200 
   2201   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
   2202 
   2203   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
   2204                                 Decl *ExDecl, Stmt *HandlerBlock);
   2205   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
   2206                               MultiStmtArg Handlers);
   2207 
   2208   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
   2209                               SourceLocation TryLoc,
   2210                               Stmt *TryBlock,
   2211                               Stmt *Handler);
   2212 
   2213   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
   2214                                  Expr *FilterExpr,
   2215                                  Stmt *Block);
   2216 
   2217   StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
   2218                                   Stmt *Block);
   2219 
   2220   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
   2221 
   2222   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
   2223 
   2224   /// \brief If it's a file scoped decl that must warn if not used, keep track
   2225   /// of it.
   2226   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
   2227 
   2228   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
   2229   /// whose result is unused, warn.
   2230   void DiagnoseUnusedExprResult(const Stmt *S);
   2231   void DiagnoseUnusedDecl(const NamedDecl *ND);
   2232 
   2233   ParsingDeclState PushParsingDeclaration() {
   2234     return DelayedDiagnostics.pushParsingDecl();
   2235   }
   2236   void PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
   2237     DelayedDiagnostics::popParsingDecl(*this, state, decl);
   2238   }
   2239 
   2240   typedef ProcessingContextState ParsingClassState;
   2241   ParsingClassState PushParsingClass() {
   2242     return DelayedDiagnostics.pushContext();
   2243   }
   2244   void PopParsingClass(ParsingClassState state) {
   2245     DelayedDiagnostics.popContext(state);
   2246   }
   2247 
   2248   void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
   2249                               SourceLocation Loc,
   2250                               const ObjCInterfaceDecl *UnknownObjCClass=0);
   2251 
   2252   void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
   2253 
   2254   bool makeUnavailableInSystemHeader(SourceLocation loc,
   2255                                      StringRef message);
   2256 
   2257   //===--------------------------------------------------------------------===//
   2258   // Expression Parsing Callbacks: SemaExpr.cpp.
   2259 
   2260   bool CanUseDecl(NamedDecl *D);
   2261   bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
   2262                          const ObjCInterfaceDecl *UnknownObjCClass=0);
   2263   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
   2264   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
   2265                                         ObjCMethodDecl *Getter,
   2266                                         SourceLocation Loc);
   2267   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
   2268                              Expr **Args, unsigned NumArgs);
   2269 
   2270   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext);
   2271 
   2272   void PopExpressionEvaluationContext();
   2273 
   2274   void DiscardCleanupsInEvaluationContext();
   2275 
   2276   void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
   2277   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
   2278   void MarkDeclarationsReferencedInExpr(Expr *E);
   2279 
   2280   /// \brief Try to recover by turning the given expression into a
   2281   /// call.  Returns true if recovery was attempted or an error was
   2282   /// emitted; this may also leave the ExprResult invalid.
   2283   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
   2284                             bool ForceComplain = false,
   2285                             bool (*IsPlausibleResult)(QualType) = 0);
   2286 
   2287   /// \brief Figure out if an expression could be turned into a call.
   2288   bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
   2289                       UnresolvedSetImpl &NonTemplateOverloads);
   2290 
   2291   /// \brief Conditionally issue a diagnostic based on the current
   2292   /// evaluation context.
   2293   ///
   2294   /// \param stmt - If stmt is non-null, delay reporting the diagnostic until
   2295   ///  the function body is parsed, and then do a basic reachability analysis to
   2296   ///  determine if the statement is reachable.  If it is unreachable, the
   2297   ///  diagnostic will not be emitted.
   2298   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
   2299                            const PartialDiagnostic &PD);
   2300 
   2301   // Primary Expressions.
   2302   SourceRange getExprRange(Expr *E) const;
   2303 
   2304   ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Id,
   2305                                bool HasTrailingLParen, bool IsAddressOfOperand);
   2306 
   2307   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
   2308                               TemplateArgumentListInfo &Buffer,
   2309                               DeclarationNameInfo &NameInfo,
   2310                               const TemplateArgumentListInfo *&TemplateArgs);
   2311 
   2312   bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
   2313                            CorrectTypoContext CTC = CTC_Unknown,
   2314                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
   2315                            Expr **Args = 0, unsigned NumArgs = 0);
   2316 
   2317   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
   2318                                 IdentifierInfo *II,
   2319                                 bool AllowBuiltinCreation=false);
   2320 
   2321   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
   2322                                         const DeclarationNameInfo &NameInfo,
   2323                                         bool isAddressOfOperand,
   2324                                 const TemplateArgumentListInfo *TemplateArgs);
   2325 
   2326   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
   2327                               ExprValueKind VK,
   2328                               SourceLocation Loc,
   2329                               const CXXScopeSpec *SS = 0);
   2330   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
   2331                               ExprValueKind VK,
   2332                               const DeclarationNameInfo &NameInfo,
   2333                               const CXXScopeSpec *SS = 0);
   2334   ExprResult
   2335   BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
   2336                                            SourceLocation nameLoc,
   2337                                            IndirectFieldDecl *indirectField,
   2338                                            Expr *baseObjectExpr = 0,
   2339                                       SourceLocation opLoc = SourceLocation());
   2340   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
   2341                                              LookupResult &R,
   2342                                 const TemplateArgumentListInfo *TemplateArgs);
   2343   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
   2344                                      LookupResult &R,
   2345                                 const TemplateArgumentListInfo *TemplateArgs,
   2346                                      bool IsDefiniteInstance);
   2347   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
   2348                                   const LookupResult &R,
   2349                                   bool HasTrailingLParen);
   2350 
   2351   ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
   2352                                          const DeclarationNameInfo &NameInfo);
   2353   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
   2354                                 const DeclarationNameInfo &NameInfo,
   2355                                 const TemplateArgumentListInfo *TemplateArgs);
   2356 
   2357   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2358                                       LookupResult &R,
   2359                                       bool NeedsADL);
   2360   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2361                                       const DeclarationNameInfo &NameInfo,
   2362                                       NamedDecl *D);
   2363 
   2364   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
   2365   ExprResult ActOnNumericConstant(const Token &Tok);
   2366   ExprResult ActOnCharacterConstant(const Token &Tok);
   2367   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
   2368   ExprResult ActOnParenOrParenListExpr(SourceLocation L,
   2369                                        SourceLocation R,
   2370                                        MultiExprArg Val);
   2371 
   2372   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
   2373   /// fragments (e.g. "foo" "bar" L"baz").
   2374   ExprResult ActOnStringLiteral(const Token *StringToks,
   2375                                 unsigned NumStringToks);
   2376 
   2377   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
   2378                                        SourceLocation DefaultLoc,
   2379                                        SourceLocation RParenLoc,
   2380                                        Expr *ControllingExpr,
   2381                                        MultiTypeArg ArgTypes,
   2382                                        MultiExprArg ArgExprs);
   2383   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
   2384                                         SourceLocation DefaultLoc,
   2385                                         SourceLocation RParenLoc,
   2386                                         Expr *ControllingExpr,
   2387                                         TypeSourceInfo **Types,
   2388                                         Expr **Exprs,
   2389                                         unsigned NumAssocs);
   2390 
   2391   // Binary/Unary Operators.  'Tok' is the token for the operator.
   2392   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
   2393                                   Expr *InputExpr);
   2394   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
   2395                           UnaryOperatorKind Opc, Expr *Input);
   2396   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
   2397                           tok::TokenKind Op, Expr *Input);
   2398 
   2399   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
   2400                                             SourceLocation OpLoc,
   2401                                             UnaryExprOrTypeTrait ExprKind,
   2402                                             SourceRange R);
   2403   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
   2404                                             UnaryExprOrTypeTrait ExprKind);
   2405   ExprResult
   2406     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
   2407                                   UnaryExprOrTypeTrait ExprKind,
   2408                                   bool IsType, void *TyOrEx,
   2409                                   const SourceRange &ArgRange);
   2410 
   2411   ExprResult CheckPlaceholderExpr(Expr *E);
   2412   bool CheckVecStepExpr(Expr *E);
   2413 
   2414   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
   2415   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
   2416                                         SourceRange ExprRange,
   2417                                         UnaryExprOrTypeTrait ExprKind);
   2418   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
   2419                                           SourceLocation OpLoc,
   2420                                           IdentifierInfo &Name,
   2421                                           SourceLocation NameLoc,
   2422                                           SourceLocation RParenLoc);
   2423   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
   2424                                  tok::TokenKind Kind, Expr *Input);
   2425 
   2426   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
   2427                                      Expr *Idx, SourceLocation RLoc);
   2428   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
   2429                                              Expr *Idx, SourceLocation RLoc);
   2430 
   2431   ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
   2432                                       SourceLocation OpLoc, bool IsArrow,
   2433                                       CXXScopeSpec &SS,
   2434                                       NamedDecl *FirstQualifierInScope,
   2435                                 const DeclarationNameInfo &NameInfo,
   2436                                 const TemplateArgumentListInfo *TemplateArgs);
   2437 
   2438   ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
   2439                                       SourceLocation OpLoc, bool IsArrow,
   2440                                       const CXXScopeSpec &SS,
   2441                                       NamedDecl *FirstQualifierInScope,
   2442                                       LookupResult &R,
   2443                                  const TemplateArgumentListInfo *TemplateArgs,
   2444                                       bool SuppressQualifierCheck = false);
   2445 
   2446   ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
   2447                               bool &IsArrow, SourceLocation OpLoc,
   2448                               CXXScopeSpec &SS,
   2449                               Decl *ObjCImpDecl,
   2450                               bool HasTemplateArgs);
   2451 
   2452   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
   2453                                      const CXXScopeSpec &SS,
   2454                                      const LookupResult &R);
   2455 
   2456   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
   2457                                       bool IsArrow, SourceLocation OpLoc,
   2458                                       const CXXScopeSpec &SS,
   2459                                       NamedDecl *FirstQualifierInScope,
   2460                                const DeclarationNameInfo &NameInfo,
   2461                                const TemplateArgumentListInfo *TemplateArgs);
   2462 
   2463   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
   2464                                    SourceLocation OpLoc,
   2465                                    tok::TokenKind OpKind,
   2466                                    CXXScopeSpec &SS,
   2467                                    UnqualifiedId &Member,
   2468                                    Decl *ObjCImpDecl,
   2469                                    bool HasTrailingLParen);
   2470 
   2471   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
   2472   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
   2473                                FunctionDecl *FDecl,
   2474                                const FunctionProtoType *Proto,
   2475                                Expr **Args, unsigned NumArgs,
   2476                                SourceLocation RParenLoc,
   2477                                bool ExecConfig = false);
   2478   void CheckStaticArrayArgument(SourceLocation CallLoc,
   2479                                 ParmVarDecl *Param,
   2480                                 const Expr *ArgExpr);
   2481 
   2482   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
   2483   /// This provides the location of the left/right parens and a list of comma
   2484   /// locations.
   2485   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
   2486                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
   2487                            Expr *ExecConfig = 0, bool IsExecConfig = false);
   2488   ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
   2489                                    SourceLocation LParenLoc,
   2490                                    Expr **Args, unsigned NumArgs,
   2491                                    SourceLocation RParenLoc,
   2492                                    Expr *Config = 0,
   2493                                    bool IsExecConfig = false);
   2494 
   2495   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
   2496                                      MultiExprArg ExecConfig,
   2497                                      SourceLocation GGGLoc);
   2498 
   2499   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
   2500                            Declarator &D, ParsedType &Ty,
   2501                            SourceLocation RParenLoc, Expr *CastExpr);
   2502   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
   2503                                  TypeSourceInfo *Ty,
   2504                                  SourceLocation RParenLoc,
   2505                                  Expr *Op);
   2506   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
   2507 
   2508   /// \brief Build an altivec or OpenCL literal.
   2509   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
   2510                                 SourceLocation RParenLoc, Expr *E,
   2511                                 TypeSourceInfo *TInfo);
   2512 
   2513   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
   2514 
   2515   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
   2516                                   ParsedType Ty,
   2517                                   SourceLocation RParenLoc,
   2518                                   Expr *InitExpr);
   2519 
   2520   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
   2521                                       TypeSourceInfo *TInfo,
   2522                                       SourceLocation RParenLoc,
   2523                                       Expr *LiteralExpr);
   2524 
   2525   ExprResult ActOnInitList(SourceLocation LBraceLoc,
   2526                            MultiExprArg InitArgList,
   2527                            SourceLocation RBraceLoc);
   2528 
   2529   ExprResult ActOnDesignatedInitializer(Designation &Desig,
   2530                                         SourceLocation Loc,
   2531                                         bool GNUSyntax,
   2532                                         ExprResult Init);
   2533 
   2534   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
   2535                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
   2536   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
   2537                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
   2538   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
   2539                                 Expr *LHSExpr, Expr *RHSExpr);
   2540 
   2541   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
   2542   /// in the case of a the GNU conditional expr extension.
   2543   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
   2544                                 SourceLocation ColonLoc,
   2545                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
   2546 
   2547   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
   2548   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
   2549                             LabelDecl *TheDecl);
   2550 
   2551   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
   2552                            SourceLocation RPLoc); // "({..})"
   2553 
   2554   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
   2555   struct OffsetOfComponent {
   2556     SourceLocation LocStart, LocEnd;
   2557     bool isBrackets;  // true if [expr], false if .ident
   2558     union {
   2559       IdentifierInfo *IdentInfo;
   2560       Expr *E;
   2561     } U;
   2562   };
   2563 
   2564   /// __builtin_offsetof(type, a.b[123][456].c)
   2565   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
   2566                                   TypeSourceInfo *TInfo,
   2567                                   OffsetOfComponent *CompPtr,
   2568                                   unsigned NumComponents,
   2569                                   SourceLocation RParenLoc);
   2570   ExprResult ActOnBuiltinOffsetOf(Scope *S,
   2571                                   SourceLocation BuiltinLoc,
   2572                                   SourceLocation TypeLoc,
   2573                                   ParsedType ParsedArgTy,
   2574                                   OffsetOfComponent *CompPtr,
   2575                                   unsigned NumComponents,
   2576                                   SourceLocation RParenLoc);
   2577 
   2578   // __builtin_choose_expr(constExpr, expr1, expr2)
   2579   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
   2580                              Expr *CondExpr, Expr *LHSExpr,
   2581                              Expr *RHSExpr, SourceLocation RPLoc);
   2582 
   2583   // __builtin_va_arg(expr, type)
   2584   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
   2585                         SourceLocation RPLoc);
   2586   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
   2587                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
   2588 
   2589   // __null
   2590   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
   2591 
   2592   bool CheckCaseExpression(Expr *E);
   2593 
   2594   bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name);
   2595 
   2596   //===------------------------- "Block" Extension ------------------------===//
   2597 
   2598   /// ActOnBlockStart - This callback is invoked when a block literal is
   2599   /// started.
   2600   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
   2601 
   2602   /// ActOnBlockArguments - This callback allows processing of block arguments.
   2603   /// If there are no arguments, this is still invoked.
   2604   void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
   2605 
   2606   /// ActOnBlockError - If there is an error parsing a block, this callback
   2607   /// is invoked to pop the information about the block from the action impl.
   2608   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
   2609 
   2610   /// ActOnBlockStmtExpr - This is called when the body of a block statement
   2611   /// literal was successfully completed.  ^(int x){...}
   2612   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
   2613                                 Scope *CurScope);
   2614 
   2615   //===---------------------------- OpenCL Features -----------------------===//
   2616 
   2617   /// __builtin_astype(...)
   2618   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
   2619                              SourceLocation BuiltinLoc,
   2620                              SourceLocation RParenLoc);
   2621 
   2622   //===---------------------------- C++ Features --------------------------===//
   2623 
   2624   // Act on C++ namespaces
   2625   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
   2626                                SourceLocation NamespaceLoc,
   2627                                SourceLocation IdentLoc,
   2628                                IdentifierInfo *Ident,
   2629                                SourceLocation LBrace,
   2630                                AttributeList *AttrList);
   2631   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
   2632 
   2633   NamespaceDecl *getStdNamespace() const;
   2634   NamespaceDecl *getOrCreateStdNamespace();
   2635 
   2636   CXXRecordDecl *getStdBadAlloc() const;
   2637 
   2638   Decl *ActOnUsingDirective(Scope *CurScope,
   2639                             SourceLocation UsingLoc,
   2640                             SourceLocation NamespcLoc,
   2641                             CXXScopeSpec &SS,
   2642                             SourceLocation IdentLoc,
   2643                             IdentifierInfo *NamespcName,
   2644                             AttributeList *AttrList);
   2645 
   2646   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
   2647 
   2648   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
   2649                                SourceLocation NamespaceLoc,
   2650                                SourceLocation AliasLoc,
   2651                                IdentifierInfo *Alias,
   2652                                CXXScopeSpec &SS,
   2653                                SourceLocation IdentLoc,
   2654                                IdentifierInfo *Ident);
   2655 
   2656   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
   2657   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
   2658                             const LookupResult &PreviousDecls);
   2659   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
   2660                                         NamedDecl *Target);
   2661 
   2662   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
   2663                                    bool isTypeName,
   2664                                    const CXXScopeSpec &SS,
   2665                                    SourceLocation NameLoc,
   2666                                    const LookupResult &Previous);
   2667   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
   2668                                const CXXScopeSpec &SS,
   2669                                SourceLocation NameLoc);
   2670 
   2671   NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
   2672                                    SourceLocation UsingLoc,
   2673                                    CXXScopeSpec &SS,
   2674                                    const DeclarationNameInfo &NameInfo,
   2675                                    AttributeList *AttrList,
   2676                                    bool IsInstantiation,
   2677                                    bool IsTypeName,
   2678                                    SourceLocation TypenameLoc);
   2679 
   2680   bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
   2681 
   2682   Decl *ActOnUsingDeclaration(Scope *CurScope,
   2683                               AccessSpecifier AS,
   2684                               bool HasUsingKeyword,
   2685                               SourceLocation UsingLoc,
   2686                               CXXScopeSpec &SS,
   2687                               UnqualifiedId &Name,
   2688                               AttributeList *AttrList,
   2689                               bool IsTypeName,
   2690                               SourceLocation TypenameLoc);
   2691   Decl *ActOnAliasDeclaration(Scope *CurScope,
   2692                               AccessSpecifier AS,
   2693                               MultiTemplateParamsArg TemplateParams,
   2694                               SourceLocation UsingLoc,
   2695                               UnqualifiedId &Name,
   2696                               TypeResult Type);
   2697 
   2698   /// AddCXXDirectInitializerToDecl - This action is called immediately after
   2699   /// ActOnDeclarator, when a C++ direct initializer is present.
   2700   /// e.g: "int x(1);"
   2701   void AddCXXDirectInitializerToDecl(Decl *Dcl,
   2702                                      SourceLocation LParenLoc,
   2703                                      MultiExprArg Exprs,
   2704                                      SourceLocation RParenLoc,
   2705                                      bool TypeMayContainAuto);
   2706 
   2707   /// InitializeVarWithConstructor - Creates an CXXConstructExpr
   2708   /// and sets it as the initializer for the the passed in VarDecl.
   2709   bool InitializeVarWithConstructor(VarDecl *VD,
   2710                                     CXXConstructorDecl *Constructor,
   2711                                     MultiExprArg Exprs,
   2712                                     bool HadMultipleCandidates);
   2713 
   2714   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
   2715   /// including handling of its default argument expressions.
   2716   ///
   2717   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
   2718   ExprResult
   2719   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   2720                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
   2721                         bool HadMultipleCandidates, bool RequiresZeroInit,
   2722                         unsigned ConstructKind, SourceRange ParenRange);
   2723 
   2724   // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
   2725   // the constructor can be elidable?
   2726   ExprResult
   2727   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   2728                         CXXConstructorDecl *Constructor, bool Elidable,
   2729                         MultiExprArg Exprs, bool HadMultipleCandidates,
   2730                         bool RequiresZeroInit, unsigned ConstructKind,
   2731                         SourceRange ParenRange);
   2732 
   2733   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
   2734   /// the default expr if needed.
   2735   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
   2736                                     FunctionDecl *FD,
   2737                                     ParmVarDecl *Param);
   2738 
   2739   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
   2740   /// constructed variable.
   2741   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
   2742 
   2743   /// \brief Helper class that collects exception specifications for
   2744   /// implicitly-declared special member functions.
   2745   class ImplicitExceptionSpecification {
   2746     // Pointer to allow copying
   2747     ASTContext *Context;
   2748     // We order exception specifications thus:
   2749     // noexcept is the most restrictive, but is only used in C++0x.
   2750     // throw() comes next.
   2751     // Then a throw(collected exceptions)
   2752     // Finally no specification.
   2753     // throw(...) is used instead if any called function uses it.
   2754     //
   2755     // If this exception specification cannot be known yet (for instance,
   2756     // because this is the exception specification for a defaulted default
   2757     // constructor and we haven't finished parsing the deferred parts of the
   2758     // class yet), the C++0x standard does not specify how to behave. We
   2759     // record this as an 'unknown' exception specification, which overrules
   2760     // any other specification (even 'none', to keep this rule simple).
   2761     ExceptionSpecificationType ComputedEST;
   2762     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
   2763     SmallVector<QualType, 4> Exceptions;
   2764 
   2765     void ClearExceptions() {
   2766       ExceptionsSeen.clear();
   2767       Exceptions.clear();
   2768     }
   2769 
   2770   public:
   2771     explicit ImplicitExceptionSpecification(ASTContext &Context)
   2772       : Context(&Context), ComputedEST(EST_BasicNoexcept) {
   2773       if (!Context.getLangOptions().CPlusPlus0x)
   2774         ComputedEST = EST_DynamicNone;
   2775     }
   2776 
   2777     /// \brief Get the computed exception specification type.
   2778     ExceptionSpecificationType getExceptionSpecType() const {
   2779       assert(ComputedEST != EST_ComputedNoexcept &&
   2780              "noexcept(expr) should not be a possible result");
   2781       return ComputedEST;
   2782     }
   2783 
   2784     /// \brief The number of exceptions in the exception specification.
   2785     unsigned size() const { return Exceptions.size(); }
   2786 
   2787     /// \brief The set of exceptions in the exception specification.
   2788     const QualType *data() const { return Exceptions.data(); }
   2789 
   2790     /// \brief Integrate another called method into the collected data.
   2791     void CalledDecl(CXXMethodDecl *Method);
   2792 
   2793     /// \brief Integrate an invoked expression into the collected data.
   2794     void CalledExpr(Expr *E);
   2795 
   2796     /// \brief Specify that the exception specification can't be detemined yet.
   2797     void SetDelayed() {
   2798       ClearExceptions();
   2799       ComputedEST = EST_Delayed;
   2800     }
   2801 
   2802     FunctionProtoType::ExtProtoInfo getEPI() const {
   2803       FunctionProtoType::ExtProtoInfo EPI;
   2804       EPI.ExceptionSpecType = getExceptionSpecType();
   2805       EPI.NumExceptions = size();
   2806       EPI.Exceptions = data();
   2807       return EPI;
   2808     }
   2809   };
   2810 
   2811   /// \brief Determine what sort of exception specification a defaulted
   2812   /// copy constructor of a class will have.
   2813   ImplicitExceptionSpecification
   2814   ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl);
   2815 
   2816   /// \brief Determine what sort of exception specification a defaulted
   2817   /// default constructor of a class will have, and whether the parameter
   2818   /// will be const.
   2819   std::pair<ImplicitExceptionSpecification, bool>
   2820   ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
   2821 
   2822   /// \brief Determine what sort of exception specification a defautled
   2823   /// copy assignment operator of a class will have, and whether the
   2824   /// parameter will be const.
   2825   std::pair<ImplicitExceptionSpecification, bool>
   2826   ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
   2827 
   2828   /// \brief Determine what sort of exception specification a defaulted move
   2829   /// constructor of a class will have.
   2830   ImplicitExceptionSpecification
   2831   ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl);
   2832 
   2833   /// \brief Determine what sort of exception specification a defaulted move
   2834   /// assignment operator of a class will have.
   2835   ImplicitExceptionSpecification
   2836   ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl);
   2837 
   2838   /// \brief Determine what sort of exception specification a defaulted
   2839   /// destructor of a class will have.
   2840   ImplicitExceptionSpecification
   2841   ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl);
   2842 
   2843   /// \brief Determine if a special member function should have a deleted
   2844   /// definition when it is defaulted.
   2845   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM);
   2846 
   2847   /// \brief Determine if a defaulted copy assignment operator ought to be
   2848   /// deleted.
   2849   bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD);
   2850 
   2851   /// \brief Determine if a defaulted move assignment operator ought to be
   2852   /// deleted.
   2853   bool ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD);
   2854 
   2855   /// \brief Determine if a defaulted destructor ought to be deleted.
   2856   bool ShouldDeleteDestructor(CXXDestructorDecl *DD);
   2857 
   2858   /// \brief Declare the implicit default constructor for the given class.
   2859   ///
   2860   /// \param ClassDecl The class declaration into which the implicit
   2861   /// default constructor will be added.
   2862   ///
   2863   /// \returns The implicitly-declared default constructor.
   2864   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
   2865                                                      CXXRecordDecl *ClassDecl);
   2866 
   2867   /// DefineImplicitDefaultConstructor - Checks for feasibility of
   2868   /// defining this constructor as the default constructor.
   2869   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
   2870                                         CXXConstructorDecl *Constructor);
   2871 
   2872   /// \brief Declare the implicit destructor for the given class.
   2873   ///
   2874   /// \param ClassDecl The class declaration into which the implicit
   2875   /// destructor will be added.
   2876   ///
   2877   /// \returns The implicitly-declared destructor.
   2878   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
   2879 
   2880   /// DefineImplicitDestructor - Checks for feasibility of
   2881   /// defining this destructor as the default destructor.
   2882   void DefineImplicitDestructor(SourceLocation CurrentLocation,
   2883                                 CXXDestructorDecl *Destructor);
   2884 
   2885   /// \brief Build an exception spec for destructors that don't have one.
   2886   ///
   2887   /// C++11 says that user-defined destructors with no exception spec get one
   2888   /// that looks as if the destructor was implicitly declared.
   2889   void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
   2890                                      CXXDestructorDecl *Destructor);
   2891 
   2892   /// \brief Declare all inherited constructors for the given class.
   2893   ///
   2894   /// \param ClassDecl The class declaration into which the inherited
   2895   /// constructors will be added.
   2896   void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
   2897 
   2898   /// \brief Declare the implicit copy constructor for the given class.
   2899   ///
   2900   /// \param ClassDecl The class declaration into which the implicit
   2901   /// copy constructor will be added.
   2902   ///
   2903   /// \returns The implicitly-declared copy constructor.
   2904   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
   2905 
   2906   /// DefineImplicitCopyConstructor - Checks for feasibility of
   2907   /// defining this constructor as the copy constructor.
   2908   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
   2909                                      CXXConstructorDecl *Constructor);
   2910 
   2911   /// \brief Declare the implicit move constructor for the given class.
   2912   ///
   2913   /// \param ClassDecl The Class declaration into which the implicit
   2914   /// move constructor will be added.
   2915   ///
   2916   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
   2917   /// declared.
   2918   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
   2919 
   2920   /// DefineImplicitMoveConstructor - Checks for feasibility of
   2921   /// defining this constructor as the move constructor.
   2922   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
   2923                                      CXXConstructorDecl *Constructor);
   2924 
   2925   /// \brief Declare the implicit copy assignment operator for the given class.
   2926   ///
   2927   /// \param ClassDecl The class declaration into which the implicit
   2928   /// copy assignment operator will be added.
   2929   ///
   2930   /// \returns The implicitly-declared copy assignment operator.
   2931   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
   2932 
   2933   /// \brief Defines an implicitly-declared copy assignment operator.
   2934   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
   2935                                     CXXMethodDecl *MethodDecl);
   2936 
   2937   /// \brief Declare the implicit move assignment operator for the given class.
   2938   ///
   2939   /// \param ClassDecl The Class declaration into which the implicit
   2940   /// move assignment operator will be added.
   2941   ///
   2942   /// \returns The implicitly-declared move assignment operator, or NULL if it
   2943   /// wasn't declared.
   2944   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
   2945 
   2946   /// \brief Defines an implicitly-declared move assignment operator.
   2947   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
   2948                                     CXXMethodDecl *MethodDecl);
   2949 
   2950   /// \brief Force the declaration of any implicitly-declared members of this
   2951   /// class.
   2952   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
   2953 
   2954   /// MaybeBindToTemporary - If the passed in expression has a record type with
   2955   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
   2956   /// it simply returns the passed in expression.
   2957   ExprResult MaybeBindToTemporary(Expr *E);
   2958 
   2959   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
   2960                                MultiExprArg ArgsPtr,
   2961                                SourceLocation Loc,
   2962                                ASTOwningVector<Expr*> &ConvertedArgs);
   2963 
   2964   ParsedType getDestructorName(SourceLocation TildeLoc,
   2965                                IdentifierInfo &II, SourceLocation NameLoc,
   2966                                Scope *S, CXXScopeSpec &SS,
   2967                                ParsedType ObjectType,
   2968                                bool EnteringContext);
   2969 
   2970   // Checks that reinterpret casts don't have undefined behavior.
   2971   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
   2972                                       bool IsDereference, SourceRange Range);
   2973 
   2974   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
   2975   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
   2976                                tok::TokenKind Kind,
   2977                                SourceLocation LAngleBracketLoc,
   2978                                Declarator &D,
   2979                                SourceLocation RAngleBracketLoc,
   2980                                SourceLocation LParenLoc,
   2981                                Expr *E,
   2982                                SourceLocation RParenLoc);
   2983 
   2984   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
   2985                                tok::TokenKind Kind,
   2986                                TypeSourceInfo *Ty,
   2987                                Expr *E,
   2988                                SourceRange AngleBrackets,
   2989                                SourceRange Parens);
   2990 
   2991   ExprResult BuildCXXTypeId(QualType TypeInfoType,
   2992                             SourceLocation TypeidLoc,
   2993                             TypeSourceInfo *Operand,
   2994                             SourceLocation RParenLoc);
   2995   ExprResult BuildCXXTypeId(QualType TypeInfoType,
   2996                             SourceLocation TypeidLoc,
   2997                             Expr *Operand,
   2998                             SourceLocation RParenLoc);
   2999 
   3000   /// ActOnCXXTypeid - Parse typeid( something ).
   3001   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
   3002                             SourceLocation LParenLoc, bool isType,
   3003                             void *TyOrExpr,
   3004                             SourceLocation RParenLoc);
   3005 
   3006   ExprResult BuildCXXUuidof(QualType TypeInfoType,
   3007                             SourceLocation TypeidLoc,
   3008                             TypeSourceInfo *Operand,
   3009                             SourceLocation RParenLoc);
   3010   ExprResult BuildCXXUuidof(QualType TypeInfoType,
   3011                             SourceLocation TypeidLoc,
   3012                             Expr *Operand,
   3013                             SourceLocation RParenLoc);
   3014 
   3015   /// ActOnCXXUuidof - Parse __uuidof( something ).
   3016   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
   3017                             SourceLocation LParenLoc, bool isType,
   3018                             void *TyOrExpr,
   3019                             SourceLocation RParenLoc);
   3020 
   3021 
   3022   //// ActOnCXXThis -  Parse 'this' pointer.
   3023   ExprResult ActOnCXXThis(SourceLocation loc);
   3024 
   3025   /// \brief Try to retrieve the type of the 'this' pointer.
   3026   ///
   3027   /// \param Capture If true, capture 'this' in this context.
   3028   ///
   3029   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
   3030   QualType getCurrentThisType(bool Capture = true);
   3031 
   3032   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
   3033   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
   3034 
   3035   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
   3036   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
   3037 
   3038   //// ActOnCXXThrow -  Parse throw expressions.
   3039   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
   3040   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
   3041                            bool IsThrownVarInScope);
   3042   ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
   3043                                   bool IsThrownVarInScope);
   3044 
   3045   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
   3046   /// Can be interpreted either as function-style casting ("int(x)")
   3047   /// or class type construction ("ClassType(x,y,z)")
   3048   /// or creation of a value-initialized type ("int()").
   3049   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
   3050                                        SourceLocation LParenLoc,
   3051                                        MultiExprArg Exprs,
   3052                                        SourceLocation RParenLoc);
   3053 
   3054   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
   3055                                        SourceLocation LParenLoc,
   3056                                        MultiExprArg Exprs,
   3057                                        SourceLocation RParenLoc);
   3058 
   3059   /// ActOnCXXNew - Parsed a C++ 'new' expression.
   3060   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
   3061                          SourceLocation PlacementLParen,
   3062                          MultiExprArg PlacementArgs,
   3063                          SourceLocation PlacementRParen,
   3064                          SourceRange TypeIdParens, Declarator &D,
   3065                          SourceLocation ConstructorLParen,
   3066                          MultiExprArg ConstructorArgs,
   3067                          SourceLocation ConstructorRParen);
   3068   ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
   3069                          SourceLocation PlacementLParen,
   3070                          MultiExprArg PlacementArgs,
   3071                          SourceLocation PlacementRParen,
   3072                          SourceRange TypeIdParens,
   3073                          QualType AllocType,
   3074                          TypeSourceInfo *AllocTypeInfo,
   3075                          Expr *ArraySize,
   3076                          SourceLocation ConstructorLParen,
   3077                          MultiExprArg ConstructorArgs,
   3078                          SourceLocation ConstructorRParen,
   3079                          bool TypeMayContainAuto = true);
   3080 
   3081   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
   3082                           SourceRange R);
   3083   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
   3084                                bool UseGlobal, QualType AllocType, bool IsArray,
   3085                                Expr **PlaceArgs, unsigned NumPlaceArgs,
   3086                                FunctionDecl *&OperatorNew,
   3087                                FunctionDecl *&OperatorDelete);
   3088   bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
   3089                               DeclarationName Name, Expr** Args,
   3090                               unsigned NumArgs, DeclContext *Ctx,
   3091                               bool AllowMissing, FunctionDecl *&Operator,
   3092                               bool Diagnose = true);
   3093   void DeclareGlobalNewDelete();
   3094   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
   3095                                        QualType Argument,
   3096                                        bool addMallocAttr = false);
   3097 
   3098   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
   3099                                 DeclarationName Name, FunctionDecl* &Operator,
   3100                                 bool Diagnose = true);
   3101 
   3102   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
   3103   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
   3104                             bool UseGlobal, bool ArrayForm,
   3105                             Expr *Operand);
   3106 
   3107   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
   3108   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
   3109                                     SourceLocation StmtLoc,
   3110                                     bool ConvertToBoolean);
   3111 
   3112   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
   3113                                Expr *Operand, SourceLocation RParen);
   3114   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
   3115                                   SourceLocation RParen);
   3116 
   3117   /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
   3118   /// pseudo-functions.
   3119   ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
   3120                                  SourceLocation KWLoc,
   3121                                  ParsedType Ty,
   3122                                  SourceLocation RParen);
   3123 
   3124   ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
   3125                                  SourceLocation KWLoc,
   3126                                  TypeSourceInfo *T,
   3127                                  SourceLocation RParen);
   3128 
   3129   /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
   3130   /// pseudo-functions.
   3131   ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
   3132                                   SourceLocation KWLoc,
   3133                                   ParsedType LhsTy,
   3134                                   ParsedType RhsTy,
   3135                                   SourceLocation RParen);
   3136 
   3137   ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
   3138                                   SourceLocation KWLoc,
   3139                                   TypeSourceInfo *LhsT,
   3140                                   TypeSourceInfo *RhsT,
   3141                                   SourceLocation RParen);
   3142 
   3143   /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
   3144   /// pseudo-functions.
   3145   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
   3146                                  SourceLocation KWLoc,
   3147                                  ParsedType LhsTy,
   3148                                  Expr *DimExpr,
   3149                                  SourceLocation RParen);
   3150 
   3151   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
   3152                                  SourceLocation KWLoc,
   3153                                  TypeSourceInfo *TSInfo,
   3154                                  Expr *DimExpr,
   3155                                  SourceLocation RParen);
   3156 
   3157   /// ActOnExpressionTrait - Parsed one of the unary type trait support
   3158   /// pseudo-functions.
   3159   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
   3160                                   SourceLocation KWLoc,
   3161                                   Expr *Queried,
   3162                                   SourceLocation RParen);
   3163 
   3164   ExprResult BuildExpressionTrait(ExpressionTrait OET,
   3165                                   SourceLocation KWLoc,
   3166                                   Expr *Queried,
   3167                                   SourceLocation RParen);
   3168 
   3169   ExprResult ActOnStartCXXMemberReference(Scope *S,
   3170                                           Expr *Base,
   3171                                           SourceLocation OpLoc,
   3172                                           tok::TokenKind OpKind,
   3173                                           ParsedType &ObjectType,
   3174                                           bool &MayBePseudoDestructor);
   3175 
   3176   ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
   3177 
   3178   ExprResult BuildPseudoDestructorExpr(Expr *Base,
   3179                                        SourceLocation OpLoc,
   3180                                        tok::TokenKind OpKind,
   3181                                        const CXXScopeSpec &SS,
   3182                                        TypeSourceInfo *ScopeType,
   3183                                        SourceLocation CCLoc,
   3184                                        SourceLocation TildeLoc,
   3185                                      PseudoDestructorTypeStorage DestroyedType,
   3186                                        bool HasTrailingLParen);
   3187 
   3188   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
   3189                                        SourceLocation OpLoc,
   3190                                        tok::TokenKind OpKind,
   3191                                        CXXScopeSpec &SS,
   3192                                        UnqualifiedId &FirstTypeName,
   3193                                        SourceLocation CCLoc,
   3194                                        SourceLocation TildeLoc,
   3195                                        UnqualifiedId &SecondTypeName,
   3196                                        bool HasTrailingLParen);
   3197 
   3198   /// MaybeCreateExprWithCleanups - If the current full-expression
   3199   /// requires any cleanups, surround it with a ExprWithCleanups node.
   3200   /// Otherwise, just returns the passed-in expression.
   3201   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
   3202   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
   3203   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
   3204 
   3205   ExprResult ActOnFinishFullExpr(Expr *Expr);
   3206   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
   3207 
   3208   // Marks SS invalid if it represents an incomplete type.
   3209   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
   3210 
   3211   DeclContext *computeDeclContext(QualType T);
   3212   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
   3213                                   bool EnteringContext = false);
   3214   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
   3215   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
   3216   bool isUnknownSpecialization(const CXXScopeSpec &SS);
   3217 
   3218   /// \brief The parser has parsed a global nested-name-specifier '::'.
   3219   ///
   3220   /// \param S The scope in which this nested-name-specifier occurs.
   3221   ///
   3222   /// \param CCLoc The location of the '::'.
   3223   ///
   3224   /// \param SS The nested-name-specifier, which will be updated in-place
   3225   /// to reflect the parsed nested-name-specifier.
   3226   ///
   3227   /// \returns true if an error occurred, false otherwise.
   3228   bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
   3229                                     CXXScopeSpec &SS);
   3230 
   3231   bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
   3232   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
   3233 
   3234   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
   3235                                     SourceLocation IdLoc,
   3236                                     IdentifierInfo &II,
   3237                                     ParsedType ObjectType);
   3238 
   3239   bool BuildCXXNestedNameSpecifier(Scope *S,
   3240                                    IdentifierInfo &Identifier,
   3241                                    SourceLocation IdentifierLoc,
   3242                                    SourceLocation CCLoc,
   3243                                    QualType ObjectType,
   3244                                    bool EnteringContext,
   3245                                    CXXScopeSpec &SS,
   3246                                    NamedDecl *ScopeLookupResult,
   3247                                    bool ErrorRecoveryLookup);
   3248 
   3249   /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
   3250   ///
   3251   /// \param S The scope in which this nested-name-specifier occurs.
   3252   ///
   3253   /// \param Identifier The identifier preceding the '::'.
   3254   ///
   3255   /// \param IdentifierLoc The location of the identifier.
   3256   ///
   3257   /// \param CCLoc The location of the '::'.
   3258   ///
   3259   /// \param ObjectType The type of the object, if we're parsing
   3260   /// nested-name-specifier in a member access expression.
   3261   ///
   3262   /// \param EnteringContext Whether we're entering the context nominated by
   3263   /// this nested-name-specifier.
   3264   ///
   3265   /// \param SS The nested-name-specifier, which is both an input
   3266   /// parameter (the nested-name-specifier before this type) and an
   3267   /// output parameter (containing the full nested-name-specifier,
   3268   /// including this new type).
   3269   ///
   3270   /// \returns true if an error occurred, false otherwise.
   3271   bool ActOnCXXNestedNameSpecifier(Scope *S,
   3272                                    IdentifierInfo &Identifier,
   3273                                    SourceLocation IdentifierLoc,
   3274                                    SourceLocation CCLoc,
   3275                                    ParsedType ObjectType,
   3276                                    bool EnteringContext,
   3277                                    CXXScopeSpec &SS);
   3278 
   3279   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
   3280                                  IdentifierInfo &Identifier,
   3281                                  SourceLocation IdentifierLoc,
   3282                                  SourceLocation ColonLoc,
   3283                                  ParsedType ObjectType,
   3284                                  bool EnteringContext);
   3285 
   3286   /// \brief The parser has parsed a nested-name-specifier
   3287   /// 'template[opt] template-name < template-args >::'.
   3288   ///
   3289   /// \param S The scope in which this nested-name-specifier occurs.
   3290   ///
   3291   /// \param TemplateLoc The location of the 'template' keyword, if any.
   3292   ///
   3293   /// \param SS The nested-name-specifier, which is both an input
   3294   /// parameter (the nested-name-specifier before this type) and an
   3295   /// output parameter (containing the full nested-name-specifier,
   3296   /// including this new type).
   3297   ///
   3298   /// \param TemplateLoc the location of the 'template' keyword, if any.
   3299   /// \param TemplateName The template name.
   3300   /// \param TemplateNameLoc The location of the template name.
   3301   /// \param LAngleLoc The location of the opening angle bracket  ('<').
   3302   /// \param TemplateArgs The template arguments.
   3303   /// \param RAngleLoc The location of the closing angle bracket  ('>').
   3304   /// \param CCLoc The location of the '::'.
   3305 
   3306   /// \param EnteringContext Whether we're entering the context of the
   3307   /// nested-name-specifier.
   3308   ///
   3309   ///
   3310   /// \returns true if an error occurred, false otherwise.
   3311   bool ActOnCXXNestedNameSpecifier(Scope *S,
   3312                                    SourceLocation TemplateLoc,
   3313                                    CXXScopeSpec &SS,
   3314                                    TemplateTy Template,
   3315                                    SourceLocation TemplateNameLoc,
   3316                                    SourceLocation LAngleLoc,
   3317                                    ASTTemplateArgsPtr TemplateArgs,
   3318                                    SourceLocation RAngleLoc,
   3319                                    SourceLocation CCLoc,
   3320                                    bool EnteringContext);
   3321 
   3322   /// \brief Given a C++ nested-name-specifier, produce an annotation value
   3323   /// that the parser can use later to reconstruct the given
   3324   /// nested-name-specifier.
   3325   ///
   3326   /// \param SS A nested-name-specifier.
   3327   ///
   3328   /// \returns A pointer containing all of the information in the
   3329   /// nested-name-specifier \p SS.
   3330   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
   3331 
   3332   /// \brief Given an annotation pointer for a nested-name-specifier, restore
   3333   /// the nested-name-specifier structure.
   3334   ///
   3335   /// \param Annotation The annotation pointer, produced by
   3336   /// \c SaveNestedNameSpecifierAnnotation().
   3337   ///
   3338   /// \param AnnotationRange The source range corresponding to the annotation.
   3339   ///
   3340   /// \param SS The nested-name-specifier that will be updated with the contents
   3341   /// of the annotation pointer.
   3342   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
   3343                                             SourceRange AnnotationRange,
   3344                                             CXXScopeSpec &SS);
   3345 
   3346   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
   3347 
   3348   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
   3349   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
   3350   /// After this method is called, according to [C++ 3.4.3p3], names should be
   3351   /// looked up in the declarator-id's scope, until the declarator is parsed and
   3352   /// ActOnCXXExitDeclaratorScope is called.
   3353   /// The 'SS' should be a non-empty valid CXXScopeSpec.
   3354   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
   3355 
   3356   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
   3357   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
   3358   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
   3359   /// Used to indicate that names should revert to being looked up in the
   3360   /// defining scope.
   3361   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
   3362 
   3363   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
   3364   /// initializer for the declaration 'Dcl'.
   3365   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
   3366   /// static data member of class X, names should be looked up in the scope of
   3367   /// class X.
   3368   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
   3369 
   3370   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
   3371   /// initializer for the declaration 'Dcl'.
   3372   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
   3373 
   3374   // ParseObjCStringLiteral - Parse Objective-C string literals.
   3375   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
   3376                                     Expr **Strings,
   3377                                     unsigned NumStrings);
   3378 
   3379   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
   3380                                   TypeSourceInfo *EncodedTypeInfo,
   3381                                   SourceLocation RParenLoc);
   3382   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
   3383                                     CXXMethodDecl *Method,
   3384                                     bool HadMultipleCandidates);
   3385 
   3386   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
   3387                                        SourceLocation EncodeLoc,
   3388                                        SourceLocation LParenLoc,
   3389                                        ParsedType Ty,
   3390                                        SourceLocation RParenLoc);
   3391 
   3392   // ParseObjCSelectorExpression - Build selector expression for @selector
   3393   ExprResult ParseObjCSelectorExpression(Selector Sel,
   3394                                          SourceLocation AtLoc,
   3395                                          SourceLocation SelLoc,
   3396                                          SourceLocation LParenLoc,
   3397                                          SourceLocation RParenLoc);
   3398 
   3399   // ParseObjCProtocolExpression - Build protocol expression for @protocol
   3400   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
   3401                                          SourceLocation AtLoc,
   3402                                          SourceLocation ProtoLoc,
   3403                                          SourceLocation LParenLoc,
   3404                                          SourceLocation RParenLoc);
   3405 
   3406   //===--------------------------------------------------------------------===//
   3407   // C++ Declarations
   3408   //
   3409   Decl *ActOnStartLinkageSpecification(Scope *S,
   3410                                        SourceLocation ExternLoc,
   3411                                        SourceLocation LangLoc,
   3412                                        StringRef Lang,
   3413                                        SourceLocation LBraceLoc);
   3414   Decl *ActOnFinishLinkageSpecification(Scope *S,
   3415                                         Decl *LinkageSpec,
   3416                                         SourceLocation RBraceLoc);
   3417 
   3418 
   3419   //===--------------------------------------------------------------------===//
   3420   // C++ Classes
   3421   //
   3422   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
   3423                           const CXXScopeSpec *SS = 0);
   3424 
   3425   bool ActOnAccessSpecifier(AccessSpecifier Access,
   3426                             SourceLocation ASLoc,
   3427                             SourceLocation ColonLoc,
   3428                             AttributeList *Attrs = 0);
   3429 
   3430   Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
   3431                                  Declarator &D,
   3432                                  MultiTemplateParamsArg TemplateParameterLists,
   3433                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
   3434                                  bool HasDeferredInit);
   3435   void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
   3436                                         Expr *Init);
   3437 
   3438   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
   3439                                     Scope *S,
   3440                                     CXXScopeSpec &SS,
   3441                                     IdentifierInfo *MemberOrBase,
   3442                                     ParsedType TemplateTypeTy,
   3443                                     SourceLocation IdLoc,
   3444                                     SourceLocation LParenLoc,
   3445                                     Expr **Args, unsigned NumArgs,
   3446                                     SourceLocation RParenLoc,
   3447                                     SourceLocation EllipsisLoc);
   3448 
   3449   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
   3450                                     Scope *S,
   3451                                     CXXScopeSpec &SS,
   3452                                     IdentifierInfo *MemberOrBase,
   3453                                     ParsedType TemplateTypeTy,
   3454                                     SourceLocation IdLoc,
   3455                                     Expr *InitList,
   3456                                     SourceLocation EllipsisLoc);
   3457 
   3458   MemInitResult BuildMemInitializer(Decl *ConstructorD,
   3459                                     Scope *S,
   3460                                     CXXScopeSpec &SS,
   3461                                     IdentifierInfo *MemberOrBase,
   3462                                     ParsedType TemplateTypeTy,
   3463                                     SourceLocation IdLoc,
   3464                                     const MultiInitializer &Init,
   3465                                     SourceLocation EllipsisLoc);
   3466 
   3467   MemInitResult BuildMemberInitializer(ValueDecl *Member,
   3468                                        const MultiInitializer &Args,
   3469                                        SourceLocation IdLoc);
   3470 
   3471   MemInitResult BuildBaseInitializer(QualType BaseType,
   3472                                      TypeSourceInfo *BaseTInfo,
   3473                                      const MultiInitializer &Args,
   3474                                      CXXRecordDecl *ClassDecl,
   3475                                      SourceLocation EllipsisLoc);
   3476 
   3477   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
   3478                                            const MultiInitializer &Args,
   3479                                            SourceLocation BaseLoc,
   3480                                            CXXRecordDecl *ClassDecl);
   3481 
   3482   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
   3483                                 CXXCtorInitializer *Initializer);
   3484 
   3485   bool SetCtorInitializers(CXXConstructorDecl *Constructor,
   3486                            CXXCtorInitializer **Initializers,
   3487                            unsigned NumInitializers, bool AnyErrors);
   3488 
   3489   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
   3490 
   3491 
   3492   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
   3493   /// mark all the non-trivial destructors of its members and bases as
   3494   /// referenced.
   3495   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
   3496                                               CXXRecordDecl *Record);
   3497 
   3498   /// \brief The list of classes whose vtables have been used within
   3499   /// this translation unit, and the source locations at which the
   3500   /// first use occurred.
   3501   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
   3502 
   3503   /// \brief The list of vtables that are required but have not yet been
   3504   /// materialized.
   3505   SmallVector<VTableUse, 16> VTableUses;
   3506 
   3507   /// \brief The set of classes whose vtables have been used within
   3508   /// this translation unit, and a bit that will be true if the vtable is
   3509   /// required to be emitted (otherwise, it should be emitted only if needed
   3510   /// by code generation).
   3511   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
   3512 
   3513   /// \brief Load any externally-stored vtable uses.
   3514   void LoadExternalVTableUses();
   3515 
   3516   typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
   3517                      &ExternalSemaSource::ReadDynamicClasses, 2, 2>
   3518     DynamicClassesType;
   3519 
   3520   /// \brief A list of all of the dynamic classes in this translation
   3521   /// unit.
   3522   DynamicClassesType DynamicClasses;
   3523 
   3524   /// \brief Note that the vtable for the given class was used at the
   3525   /// given location.
   3526   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
   3527                       bool DefinitionRequired = false);
   3528 
   3529   /// MarkVirtualMembersReferenced - Will mark all members of the given
   3530   /// CXXRecordDecl referenced.
   3531   void MarkVirtualMembersReferenced(SourceLocation Loc,
   3532                                     const CXXRecordDecl *RD);
   3533 
   3534   /// \brief Define all of the vtables that have been used in this
   3535   /// translation unit and reference any virtual members used by those
   3536   /// vtables.
   3537   ///
   3538   /// \returns true if any work was done, false otherwise.
   3539   bool DefineUsedVTables();
   3540 
   3541   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
   3542 
   3543   void ActOnMemInitializers(Decl *ConstructorDecl,
   3544                             SourceLocation ColonLoc,
   3545                             CXXCtorInitializer **MemInits,
   3546                             unsigned NumMemInits,
   3547                             bool AnyErrors);
   3548 
   3549   void CheckCompletedCXXClass(CXXRecordDecl *Record);
   3550   void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
   3551                                          Decl *TagDecl,
   3552                                          SourceLocation LBrac,
   3553                                          SourceLocation RBrac,
   3554                                          AttributeList *AttrList);
   3555 
   3556   void ActOnReenterTemplateScope(Scope *S, Decl *Template);
   3557   void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
   3558   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
   3559   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
   3560   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
   3561   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
   3562   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
   3563   void ActOnFinishDelayedMemberInitializers(Decl *Record);
   3564   void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
   3565   bool IsInsideALocalClassWithinATemplateFunction();
   3566 
   3567   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   3568                                      Expr *AssertExpr,
   3569                                      Expr *AssertMessageExpr,
   3570                                      SourceLocation RParenLoc);
   3571 
   3572   FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
   3573                                   TypeSourceInfo *TSInfo);
   3574   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
   3575                             MultiTemplateParamsArg TemplateParams);
   3576   Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
   3577                                 MultiTemplateParamsArg TemplateParams);
   3578 
   3579   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
   3580                                       StorageClass& SC);
   3581   void CheckConstructor(CXXConstructorDecl *Constructor);
   3582   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
   3583                                      StorageClass& SC);
   3584   bool CheckDestructor(CXXDestructorDecl *Destructor);
   3585   void CheckConversionDeclarator(Declarator &D, QualType &R,
   3586                                  StorageClass& SC);
   3587   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
   3588 
   3589   void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
   3590   void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor);
   3591   void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor);
   3592   void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method);
   3593   void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor);
   3594   void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method);
   3595   void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor);
   3596 
   3597   //===--------------------------------------------------------------------===//
   3598   // C++ Derived Classes
   3599   //
   3600 
   3601   /// ActOnBaseSpecifier - Parsed a base specifier
   3602   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
   3603                                        SourceRange SpecifierRange,
   3604                                        bool Virtual, AccessSpecifier Access,
   3605                                        TypeSourceInfo *TInfo,
   3606                                        SourceLocation EllipsisLoc);
   3607 
   3608   BaseResult ActOnBaseSpecifier(Decl *classdecl,
   3609                                 SourceRange SpecifierRange,
   3610                                 bool Virtual, AccessSpecifier Access,
   3611                                 ParsedType basetype,
   3612                                 SourceLocation BaseLoc,
   3613                                 SourceLocation EllipsisLoc);
   3614 
   3615   bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
   3616                             unsigned NumBases);
   3617   void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
   3618                            unsigned NumBases);
   3619 
   3620   bool IsDerivedFrom(QualType Derived, QualType Base);
   3621   bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
   3622 
   3623   // FIXME: I don't like this name.
   3624   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
   3625 
   3626   bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
   3627 
   3628   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   3629                                     SourceLocation Loc, SourceRange Range,
   3630                                     CXXCastPath *BasePath = 0,
   3631                                     bool IgnoreAccess = false);
   3632   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   3633                                     unsigned InaccessibleBaseID,
   3634                                     unsigned AmbigiousBaseConvID,
   3635                                     SourceLocation Loc, SourceRange Range,
   3636                                     DeclarationName Name,
   3637                                     CXXCastPath *BasePath);
   3638 
   3639   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
   3640 
   3641   /// CheckOverridingFunctionReturnType - Checks whether the return types are
   3642   /// covariant, according to C++ [class.virtual]p5.
   3643   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
   3644                                          const CXXMethodDecl *Old);
   3645 
   3646   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
   3647   /// spec is a subset of base spec.
   3648   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
   3649                                             const CXXMethodDecl *Old);
   3650 
   3651   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
   3652 
   3653   /// CheckOverrideControl - Check C++0x override control semantics.
   3654   void CheckOverrideControl(const Decl *D);
   3655 
   3656   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
   3657   /// overrides a virtual member function marked 'final', according to
   3658   /// C++0x [class.virtual]p3.
   3659   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
   3660                                               const CXXMethodDecl *Old);
   3661 
   3662 
   3663   //===--------------------------------------------------------------------===//
   3664   // C++ Access Control
   3665   //
   3666 
   3667   enum AccessResult {
   3668     AR_accessible,
   3669     AR_inaccessible,
   3670     AR_dependent,
   3671     AR_delayed
   3672   };
   3673 
   3674   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
   3675                                 NamedDecl *PrevMemberDecl,
   3676                                 AccessSpecifier LexicalAS);
   3677 
   3678   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
   3679                                            DeclAccessPair FoundDecl);
   3680   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
   3681                                            DeclAccessPair FoundDecl);
   3682   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
   3683                                      SourceRange PlacementRange,
   3684                                      CXXRecordDecl *NamingClass,
   3685                                      DeclAccessPair FoundDecl,
   3686                                      bool Diagnose = true);
   3687   AccessResult CheckConstructorAccess(SourceLocation Loc,
   3688                                       CXXConstructorDecl *D,
   3689                                       const InitializedEntity &Entity,
   3690                                       AccessSpecifier Access,
   3691                                       bool IsCopyBindingRefToTemp = false);
   3692   AccessResult CheckConstructorAccess(SourceLocation Loc,
   3693                                       CXXConstructorDecl *D,
   3694                                       AccessSpecifier Access,
   3695                                       PartialDiagnostic PD);
   3696   AccessResult CheckDestructorAccess(SourceLocation Loc,
   3697                                      CXXDestructorDecl *Dtor,
   3698                                      const PartialDiagnostic &PDiag);
   3699   AccessResult CheckDirectMemberAccess(SourceLocation Loc,
   3700                                        NamedDecl *D,
   3701                                        const PartialDiagnostic &PDiag);
   3702   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
   3703                                          Expr *ObjectExpr,
   3704                                          Expr *ArgExpr,
   3705                                          DeclAccessPair FoundDecl);
   3706   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
   3707                                           DeclAccessPair FoundDecl);
   3708   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
   3709                                     QualType Base, QualType Derived,
   3710                                     const CXXBasePath &Path,
   3711                                     unsigned DiagID,
   3712                                     bool ForceCheck = false,
   3713                                     bool ForceUnprivileged = false);
   3714   void CheckLookupAccess(const LookupResult &R);
   3715   bool IsSimplyAccessible(NamedDecl *decl, CXXRecordDecl *Class);
   3716 
   3717   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
   3718                          const MultiLevelTemplateArgumentList &TemplateArgs);
   3719   void PerformDependentDiagnostics(const DeclContext *Pattern,
   3720                         const MultiLevelTemplateArgumentList &TemplateArgs);
   3721 
   3722   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
   3723 
   3724   /// A flag to suppress access checking.
   3725   bool SuppressAccessChecking;
   3726 
   3727   /// \brief When true, access checking violations are treated as SFINAE
   3728   /// failures rather than hard errors.
   3729   bool AccessCheckingSFINAE;
   3730 
   3731   void ActOnStartSuppressingAccessChecks();
   3732   void ActOnStopSuppressingAccessChecks();
   3733 
   3734   enum AbstractDiagSelID {
   3735     AbstractNone = -1,
   3736     AbstractReturnType,
   3737     AbstractParamType,
   3738     AbstractVariableType,
   3739     AbstractFieldType,
   3740     AbstractArrayType
   3741   };
   3742 
   3743   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
   3744                               const PartialDiagnostic &PD);
   3745   void DiagnoseAbstractType(const CXXRecordDecl *RD);
   3746 
   3747   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
   3748                               AbstractDiagSelID SelID = AbstractNone);
   3749 
   3750   //===--------------------------------------------------------------------===//
   3751   // C++ Overloaded Operators [C++ 13.5]
   3752   //
   3753 
   3754   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
   3755 
   3756   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
   3757 
   3758   //===--------------------------------------------------------------------===//
   3759   // C++ Templates [C++ 14]
   3760   //
   3761   void FilterAcceptableTemplateNames(LookupResult &R);
   3762   bool hasAnyAcceptableTemplateNames(LookupResult &R);
   3763 
   3764   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
   3765                           QualType ObjectType, bool EnteringContext,
   3766                           bool &MemberOfUnknownSpecialization);
   3767 
   3768   TemplateNameKind isTemplateName(Scope *S,
   3769                                   CXXScopeSpec &SS,
   3770                                   bool hasTemplateKeyword,
   3771                                   UnqualifiedId &Name,
   3772                                   ParsedType ObjectType,
   3773                                   bool EnteringContext,
   3774                                   TemplateTy &Template,
   3775                                   bool &MemberOfUnknownSpecialization);
   3776 
   3777   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
   3778                                    SourceLocation IILoc,
   3779                                    Scope *S,
   3780                                    const CXXScopeSpec *SS,
   3781                                    TemplateTy &SuggestedTemplate,
   3782                                    TemplateNameKind &SuggestedKind);
   3783 
   3784   bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
   3785   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
   3786 
   3787   Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
   3788                            SourceLocation EllipsisLoc,
   3789                            SourceLocation KeyLoc,
   3790                            IdentifierInfo *ParamName,
   3791                            SourceLocation ParamNameLoc,
   3792                            unsigned Depth, unsigned Position,
   3793                            SourceLocation EqualLoc,
   3794                            ParsedType DefaultArg);
   3795 
   3796   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
   3797   Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
   3798                                       unsigned Depth,
   3799                                       unsigned Position,
   3800                                       SourceLocation EqualLoc,
   3801                                       Expr *DefaultArg);
   3802   Decl *ActOnTemplateTemplateParameter(Scope *S,
   3803                                        SourceLocation TmpLoc,
   3804                                        TemplateParameterList *Params,
   3805                                        SourceLocation EllipsisLoc,
   3806                                        IdentifierInfo *ParamName,
   3807                                        SourceLocation ParamNameLoc,
   3808                                        unsigned Depth,
   3809                                        unsigned Position,
   3810                                        SourceLocation EqualLoc,
   3811                                        ParsedTemplateArgument DefaultArg);
   3812 
   3813   TemplateParameterList *
   3814   ActOnTemplateParameterList(unsigned Depth,
   3815                              SourceLocation ExportLoc,
   3816                              SourceLocation TemplateLoc,
   3817                              SourceLocation LAngleLoc,
   3818                              Decl **Params, unsigned NumParams,
   3819                              SourceLocation RAngleLoc);
   3820 
   3821   /// \brief The context in which we are checking a template parameter
   3822   /// list.
   3823   enum TemplateParamListContext {
   3824     TPC_ClassTemplate,
   3825     TPC_FunctionTemplate,
   3826     TPC_ClassTemplateMember,
   3827     TPC_FriendFunctionTemplate,
   3828     TPC_FriendFunctionTemplateDefinition,
   3829     TPC_TypeAliasTemplate
   3830   };
   3831 
   3832   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
   3833                                   TemplateParameterList *OldParams,
   3834                                   TemplateParamListContext TPC);
   3835   TemplateParameterList *
   3836   MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
   3837                                           SourceLocation DeclLoc,
   3838                                           const CXXScopeSpec &SS,
   3839                                           TemplateParameterList **ParamLists,
   3840                                           unsigned NumParamLists,
   3841                                           bool IsFriend,
   3842                                           bool &IsExplicitSpecialization,
   3843                                           bool &Invalid);
   3844 
   3845   DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
   3846                                 SourceLocation KWLoc, CXXScopeSpec &SS,
   3847                                 IdentifierInfo *Name, SourceLocation NameLoc,
   3848                                 AttributeList *Attr,
   3849                                 TemplateParameterList *TemplateParams,
   3850                                 AccessSpecifier AS,
   3851                                 SourceLocation ModulePrivateLoc,
   3852                                 unsigned NumOuterTemplateParamLists,
   3853                             TemplateParameterList **OuterTemplateParamLists);
   3854 
   3855   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
   3856                                   TemplateArgumentListInfo &Out);
   3857 
   3858   void NoteAllFoundTemplates(TemplateName Name);
   3859 
   3860   QualType CheckTemplateIdType(TemplateName Template,
   3861                                SourceLocation TemplateLoc,
   3862                               TemplateArgumentListInfo &TemplateArgs);
   3863 
   3864   TypeResult
   3865   ActOnTemplateIdType(CXXScopeSpec &SS,
   3866                       TemplateTy Template, SourceLocation TemplateLoc,
   3867                       SourceLocation LAngleLoc,
   3868                       ASTTemplateArgsPtr TemplateArgs,
   3869                       SourceLocation RAngleLoc);
   3870 
   3871   /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
   3872   /// such as \c class T::template apply<U>.
   3873   ///
   3874   /// \param TUK
   3875   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
   3876                                     TypeSpecifierType TagSpec,
   3877                                     SourceLocation TagLoc,
   3878                                     CXXScopeSpec &SS,
   3879                                     TemplateTy TemplateD,
   3880                                     SourceLocation TemplateLoc,
   3881                                     SourceLocation LAngleLoc,
   3882                                     ASTTemplateArgsPtr TemplateArgsIn,
   3883                                     SourceLocation RAngleLoc);
   3884 
   3885 
   3886   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
   3887                                  LookupResult &R,
   3888                                  bool RequiresADL,
   3889                                const TemplateArgumentListInfo &TemplateArgs);
   3890   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
   3891                                const DeclarationNameInfo &NameInfo,
   3892                                const TemplateArgumentListInfo &TemplateArgs);
   3893 
   3894   TemplateNameKind ActOnDependentTemplateName(Scope *S,
   3895                                               SourceLocation TemplateKWLoc,
   3896                                               CXXScopeSpec &SS,
   3897                                               UnqualifiedId &Name,
   3898                                               ParsedType ObjectType,
   3899                                               bool EnteringContext,
   3900                                               TemplateTy &Template);
   3901 
   3902   DeclResult
   3903   ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
   3904                                    SourceLocation KWLoc,
   3905                                    SourceLocation ModulePrivateLoc,
   3906                                    CXXScopeSpec &SS,
   3907                                    TemplateTy Template,
   3908                                    SourceLocation TemplateNameLoc,
   3909                                    SourceLocation LAngleLoc,
   3910                                    ASTTemplateArgsPtr TemplateArgs,
   3911                                    SourceLocation RAngleLoc,
   3912                                    AttributeList *Attr,
   3913                                  MultiTemplateParamsArg TemplateParameterLists);
   3914 
   3915   Decl *ActOnTemplateDeclarator(Scope *S,
   3916                                 MultiTemplateParamsArg TemplateParameterLists,
   3917                                 Declarator &D);
   3918 
   3919   Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
   3920                                   MultiTemplateParamsArg TemplateParameterLists,
   3921                                         Declarator &D);
   3922 
   3923   bool
   3924   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
   3925                                          TemplateSpecializationKind NewTSK,
   3926                                          NamedDecl *PrevDecl,
   3927                                          TemplateSpecializationKind PrevTSK,
   3928                                          SourceLocation PrevPtOfInstantiation,
   3929                                          bool &SuppressNew);
   3930 
   3931   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
   3932                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
   3933                                                     LookupResult &Previous);
   3934 
   3935   bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
   3936                          TemplateArgumentListInfo *ExplicitTemplateArgs,
   3937                                            LookupResult &Previous);
   3938   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
   3939 
   3940   DeclResult
   3941   ActOnExplicitInstantiation(Scope *S,
   3942                              SourceLocation ExternLoc,
   3943                              SourceLocation TemplateLoc,
   3944                              unsigned TagSpec,
   3945                              SourceLocation KWLoc,
   3946                              const CXXScopeSpec &SS,
   3947                              TemplateTy Template,
   3948                              SourceLocation TemplateNameLoc,
   3949                              SourceLocation LAngleLoc,
   3950                              ASTTemplateArgsPtr TemplateArgs,
   3951                              SourceLocation RAngleLoc,
   3952                              AttributeList *Attr);
   3953 
   3954   DeclResult
   3955   ActOnExplicitInstantiation(Scope *S,
   3956                              SourceLocation ExternLoc,
   3957                              SourceLocation TemplateLoc,
   3958                              unsigned TagSpec,
   3959                              SourceLocation KWLoc,
   3960                              CXXScopeSpec &SS,
   3961                              IdentifierInfo *Name,
   3962                              SourceLocation NameLoc,
   3963                              AttributeList *Attr);
   3964 
   3965   DeclResult ActOnExplicitInstantiation(Scope *S,
   3966                                         SourceLocation ExternLoc,
   3967                                         SourceLocation TemplateLoc,
   3968                                         Declarator &D);
   3969 
   3970   TemplateArgumentLoc
   3971   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
   3972                                           SourceLocation TemplateLoc,
   3973                                           SourceLocation RAngleLoc,
   3974                                           Decl *Param,
   3975                           SmallVectorImpl<TemplateArgument> &Converted);
   3976 
   3977   /// \brief Specifies the context in which a particular template
   3978   /// argument is being checked.
   3979   enum CheckTemplateArgumentKind {
   3980     /// \brief The template argument was specified in the code or was
   3981     /// instantiated with some deduced template arguments.
   3982     CTAK_Specified,
   3983 
   3984     /// \brief The template argument was deduced via template argument
   3985     /// deduction.
   3986     CTAK_Deduced,
   3987 
   3988     /// \brief The template argument was deduced from an array bound
   3989     /// via template argument deduction.
   3990     CTAK_DeducedFromArrayBound
   3991   };
   3992 
   3993   bool CheckTemplateArgument(NamedDecl *Param,
   3994                              const TemplateArgumentLoc &Arg,
   3995                              NamedDecl *Template,
   3996                              SourceLocation TemplateLoc,
   3997                              SourceLocation RAngleLoc,
   3998                              unsigned ArgumentPackIndex,
   3999                            SmallVectorImpl<TemplateArgument> &Converted,
   4000                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
   4001 
   4002   /// \brief Check that the given template arguments can be be provided to
   4003   /// the given template, converting the arguments along the way.
   4004   ///
   4005   /// \param Template The template to which the template arguments are being
   4006   /// provided.
   4007   ///
   4008   /// \param TemplateLoc The location of the template name in the source.
   4009   ///
   4010   /// \param TemplateArgs The list of template arguments. If the template is
   4011   /// a template template parameter, this function may extend the set of
   4012   /// template arguments to also include substituted, defaulted template
   4013   /// arguments.
   4014   ///
   4015   /// \param PartialTemplateArgs True if the list of template arguments is
   4016   /// intentionally partial, e.g., because we're checking just the initial
   4017   /// set of template arguments.
   4018   ///
   4019   /// \param Converted Will receive the converted, canonicalized template
   4020   /// arguments.
   4021   ///
   4022   /// \returns True if an error occurred, false otherwise.
   4023   bool CheckTemplateArgumentList(TemplateDecl *Template,
   4024                                  SourceLocation TemplateLoc,
   4025                                  TemplateArgumentListInfo &TemplateArgs,
   4026                                  bool PartialTemplateArgs,
   4027                            SmallVectorImpl<TemplateArgument> &Converted);
   4028 
   4029   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
   4030                                  const TemplateArgumentLoc &Arg,
   4031                            SmallVectorImpl<TemplateArgument> &Converted);
   4032 
   4033   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
   4034                              TypeSourceInfo *Arg);
   4035   bool CheckTemplateArgumentPointerToMember(Expr *Arg,
   4036                                             TemplateArgument &Converted);
   4037   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
   4038                                    QualType InstantiatedParamType, Expr *Arg,
   4039                                    TemplateArgument &Converted,
   4040                                    CheckTemplateArgumentKind CTAK = CTAK_Specified);
   4041   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
   4042                              const TemplateArgumentLoc &Arg);
   4043 
   4044   ExprResult
   4045   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
   4046                                           QualType ParamType,
   4047                                           SourceLocation Loc);
   4048   ExprResult
   4049   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
   4050                                               SourceLocation Loc);
   4051 
   4052   /// \brief Enumeration describing how template parameter lists are compared
   4053   /// for equality.
   4054   enum TemplateParameterListEqualKind {
   4055     /// \brief We are matching the template parameter lists of two templates
   4056     /// that might be redeclarations.
   4057     ///
   4058     /// \code
   4059     /// template<typename T> struct X;
   4060     /// template<typename T> struct X;
   4061     /// \endcode
   4062     TPL_TemplateMatch,
   4063 
   4064     /// \brief We are matching the template parameter lists of two template
   4065     /// template parameters as part of matching the template parameter lists
   4066     /// of two templates that might be redeclarations.
   4067     ///
   4068     /// \code
   4069     /// template<template<int I> class TT> struct X;
   4070     /// template<template<int Value> class Other> struct X;
   4071     /// \endcode
   4072     TPL_TemplateTemplateParmMatch,
   4073 
   4074     /// \brief We are matching the template parameter lists of a template
   4075     /// template argument against the template parameter lists of a template
   4076     /// template parameter.
   4077     ///
   4078     /// \code
   4079     /// template<template<int Value> class Metafun> struct X;
   4080     /// template<int Value> struct integer_c;
   4081     /// X<integer_c> xic;
   4082     /// \endcode
   4083     TPL_TemplateTemplateArgumentMatch
   4084   };
   4085 
   4086   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
   4087                                       TemplateParameterList *Old,
   4088                                       bool Complain,
   4089                                       TemplateParameterListEqualKind Kind,
   4090                                       SourceLocation TemplateArgLoc
   4091                                         = SourceLocation());
   4092 
   4093   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
   4094 
   4095   /// \brief Called when the parser has parsed a C++ typename
   4096   /// specifier, e.g., "typename T::type".
   4097   ///
   4098   /// \param S The scope in which this typename type occurs.
   4099   /// \param TypenameLoc the location of the 'typename' keyword
   4100   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
   4101   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
   4102   /// \param IdLoc the location of the identifier.
   4103   TypeResult
   4104   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
   4105                     const CXXScopeSpec &SS, const IdentifierInfo &II,
   4106                     SourceLocation IdLoc);
   4107 
   4108   /// \brief Called when the parser has parsed a C++ typename
   4109   /// specifier that ends in a template-id, e.g.,
   4110   /// "typename MetaFun::template apply<T1, T2>".
   4111   ///
   4112   /// \param S The scope in which this typename type occurs.
   4113   /// \param TypenameLoc the location of the 'typename' keyword
   4114   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
   4115   /// \param TemplateLoc the location of the 'template' keyword, if any.
   4116   /// \param TemplateName The template name.
   4117   /// \param TemplateNameLoc The location of the template name.
   4118   /// \param LAngleLoc The location of the opening angle bracket  ('<').
   4119   /// \param TemplateArgs The template arguments.
   4120   /// \param RAngleLoc The location of the closing angle bracket  ('>').
   4121   TypeResult
   4122   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
   4123                     const CXXScopeSpec &SS,
   4124                     SourceLocation TemplateLoc,
   4125                     TemplateTy Template,
   4126                     SourceLocation TemplateNameLoc,
   4127                     SourceLocation LAngleLoc,
   4128                     ASTTemplateArgsPtr TemplateArgs,
   4129                     SourceLocation RAngleLoc);
   4130 
   4131   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
   4132                              SourceLocation KeywordLoc,
   4133                              NestedNameSpecifierLoc QualifierLoc,
   4134                              const IdentifierInfo &II,
   4135                              SourceLocation IILoc);
   4136 
   4137   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
   4138                                                     SourceLocation Loc,
   4139                                                     DeclarationName Name);
   4140   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
   4141 
   4142   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
   4143   bool RebuildTemplateParamsInCurrentInstantiation(
   4144                                                 TemplateParameterList *Params);
   4145 
   4146   std::string
   4147   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
   4148                                   const TemplateArgumentList &Args);
   4149 
   4150   std::string
   4151   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
   4152                                   const TemplateArgument *Args,
   4153                                   unsigned NumArgs);
   4154 
   4155   //===--------------------------------------------------------------------===//
   4156   // C++ Variadic Templates (C++0x [temp.variadic])
   4157   //===--------------------------------------------------------------------===//
   4158 
   4159   /// \brief The context in which an unexpanded parameter pack is
   4160   /// being diagnosed.
   4161   ///
   4162   /// Note that the values of this enumeration line up with the first
   4163   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
   4164   enum UnexpandedParameterPackContext {
   4165     /// \brief An arbitrary expression.
   4166     UPPC_Expression = 0,
   4167 
   4168     /// \brief The base type of a class type.
   4169     UPPC_BaseType,
   4170 
   4171     /// \brief The type of an arbitrary declaration.
   4172     UPPC_DeclarationType,
   4173 
   4174     /// \brief The type of a data member.
   4175     UPPC_DataMemberType,
   4176 
   4177     /// \brief The size of a bit-field.
   4178     UPPC_BitFieldWidth,
   4179 
   4180     /// \brief The expression in a static assertion.
   4181     UPPC_StaticAssertExpression,
   4182 
   4183     /// \brief The fixed underlying type of an enumeration.
   4184     UPPC_FixedUnderlyingType,
   4185 
   4186     /// \brief The enumerator value.
   4187     UPPC_EnumeratorValue,
   4188 
   4189     /// \brief A using declaration.
   4190     UPPC_UsingDeclaration,
   4191 
   4192     /// \brief A friend declaration.
   4193     UPPC_FriendDeclaration,
   4194 
   4195     /// \brief A declaration qualifier.
   4196     UPPC_DeclarationQualifier,
   4197 
   4198     /// \brief An initializer.
   4199     UPPC_Initializer,
   4200 
   4201     /// \brief A default argument.
   4202     UPPC_DefaultArgument,
   4203 
   4204     /// \brief The type of a non-type template parameter.
   4205     UPPC_NonTypeTemplateParameterType,
   4206 
   4207     /// \brief The type of an exception.
   4208     UPPC_ExceptionType,
   4209 
   4210     /// \brief Partial specialization.
   4211     UPPC_PartialSpecialization
   4212   };
   4213 
   4214   /// \brief If the given type contains an unexpanded parameter pack,
   4215   /// diagnose the error.
   4216   ///
   4217   /// \param Loc The source location where a diagnostc should be emitted.
   4218   ///
   4219   /// \param T The type that is being checked for unexpanded parameter
   4220   /// packs.
   4221   ///
   4222   /// \returns true if an error occurred, false otherwise.
   4223   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
   4224                                        UnexpandedParameterPackContext UPPC);
   4225 
   4226   /// \brief If the given expression contains an unexpanded parameter
   4227   /// pack, diagnose the error.
   4228   ///
   4229   /// \param E The expression that is being checked for unexpanded
   4230   /// parameter packs.
   4231   ///
   4232   /// \returns true if an error occurred, false otherwise.
   4233   bool DiagnoseUnexpandedParameterPack(Expr *E,
   4234                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
   4235 
   4236   /// \brief If the given nested-name-specifier contains an unexpanded
   4237   /// parameter pack, diagnose the error.
   4238   ///
   4239   /// \param SS The nested-name-specifier that is being checked for
   4240   /// unexpanded parameter packs.
   4241   ///
   4242   /// \returns true if an error occurred, false otherwise.
   4243   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
   4244                                        UnexpandedParameterPackContext UPPC);
   4245 
   4246   /// \brief If the given name contains an unexpanded parameter pack,
   4247   /// diagnose the error.
   4248   ///
   4249   /// \param NameInfo The name (with source location information) that
   4250   /// is being checked for unexpanded parameter packs.
   4251   ///
   4252   /// \returns true if an error occurred, false otherwise.
   4253   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
   4254                                        UnexpandedParameterPackContext UPPC);
   4255 
   4256   /// \brief If the given template name contains an unexpanded parameter pack,
   4257   /// diagnose the error.
   4258   ///
   4259   /// \param Loc The location of the template name.
   4260   ///
   4261   /// \param Template The template name that is being checked for unexpanded
   4262   /// parameter packs.
   4263   ///
   4264   /// \returns true if an error occurred, false otherwise.
   4265   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
   4266                                        TemplateName Template,
   4267                                        UnexpandedParameterPackContext UPPC);
   4268 
   4269   /// \brief If the given template argument contains an unexpanded parameter
   4270   /// pack, diagnose the error.
   4271   ///
   4272   /// \param Arg The template argument that is being checked for unexpanded
   4273   /// parameter packs.
   4274   ///
   4275   /// \returns true if an error occurred, false otherwise.
   4276   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
   4277                                        UnexpandedParameterPackContext UPPC);
   4278 
   4279   /// \brief Collect the set of unexpanded parameter packs within the given
   4280   /// template argument.
   4281   ///
   4282   /// \param Arg The template argument that will be traversed to find
   4283   /// unexpanded parameter packs.
   4284   void collectUnexpandedParameterPacks(TemplateArgument Arg,
   4285                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
   4286 
   4287   /// \brief Collect the set of unexpanded parameter packs within the given
   4288   /// template argument.
   4289   ///
   4290   /// \param Arg The template argument that will be traversed to find
   4291   /// unexpanded parameter packs.
   4292   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
   4293                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
   4294 
   4295   /// \brief Collect the set of unexpanded parameter packs within the given
   4296   /// type.
   4297   ///
   4298   /// \param T The type that will be traversed to find
   4299   /// unexpanded parameter packs.
   4300   void collectUnexpandedParameterPacks(QualType T,
   4301                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
   4302 
   4303   /// \brief Collect the set of unexpanded parameter packs within the given
   4304   /// type.
   4305   ///
   4306   /// \param TL The type that will be traversed to find
   4307   /// unexpanded parameter packs.
   4308   void collectUnexpandedParameterPacks(TypeLoc TL,
   4309                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
   4310 
   4311   /// \brief Invoked when parsing a template argument followed by an
   4312   /// ellipsis, which creates a pack expansion.
   4313   ///
   4314   /// \param Arg The template argument preceding the ellipsis, which
   4315   /// may already be invalid.
   4316   ///
   4317   /// \param EllipsisLoc The location of the ellipsis.
   4318   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
   4319                                             SourceLocation EllipsisLoc);
   4320 
   4321   /// \brief Invoked when parsing a type followed by an ellipsis, which
   4322   /// creates a pack expansion.
   4323   ///
   4324   /// \param Type The type preceding the ellipsis, which will become
   4325   /// the pattern of the pack expansion.
   4326   ///
   4327   /// \param EllipsisLoc The location of the ellipsis.
   4328   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
   4329 
   4330   /// \brief Construct a pack expansion type from the pattern of the pack
   4331   /// expansion.
   4332   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
   4333                                      SourceLocation EllipsisLoc,
   4334                                      llvm::Optional<unsigned> NumExpansions);
   4335 
   4336   /// \brief Construct a pack expansion type from the pattern of the pack
   4337   /// expansion.
   4338   QualType CheckPackExpansion(QualType Pattern,
   4339                               SourceRange PatternRange,
   4340                               SourceLocation EllipsisLoc,
   4341                               llvm::Optional<unsigned> NumExpansions);
   4342 
   4343   /// \brief Invoked when parsing an expression followed by an ellipsis, which
   4344   /// creates a pack expansion.
   4345   ///
   4346   /// \param Pattern The expression preceding the ellipsis, which will become
   4347   /// the pattern of the pack expansion.
   4348   ///
   4349   /// \param EllipsisLoc The location of the ellipsis.
   4350   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
   4351 
   4352   /// \brief Invoked when parsing an expression followed by an ellipsis, which
   4353   /// creates a pack expansion.
   4354   ///
   4355   /// \param Pattern The expression preceding the ellipsis, which will become
   4356   /// the pattern of the pack expansion.
   4357   ///
   4358   /// \param EllipsisLoc The location of the ellipsis.
   4359   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
   4360                                 llvm::Optional<unsigned> NumExpansions);
   4361 
   4362   /// \brief Determine whether we could expand a pack expansion with the
   4363   /// given set of parameter packs into separate arguments by repeatedly
   4364   /// transforming the pattern.
   4365   ///
   4366   /// \param EllipsisLoc The location of the ellipsis that identifies the
   4367   /// pack expansion.
   4368   ///
   4369   /// \param PatternRange The source range that covers the entire pattern of
   4370   /// the pack expansion.
   4371   ///
   4372   /// \param Unexpanded The set of unexpanded parameter packs within the
   4373   /// pattern.
   4374   ///
   4375   /// \param NumUnexpanded The number of unexpanded parameter packs in
   4376   /// \p Unexpanded.
   4377   ///
   4378   /// \param ShouldExpand Will be set to \c true if the transformer should
   4379   /// expand the corresponding pack expansions into separate arguments. When
   4380   /// set, \c NumExpansions must also be set.
   4381   ///
   4382   /// \param RetainExpansion Whether the caller should add an unexpanded
   4383   /// pack expansion after all of the expanded arguments. This is used
   4384   /// when extending explicitly-specified template argument packs per
   4385   /// C++0x [temp.arg.explicit]p9.
   4386   ///
   4387   /// \param NumExpansions The number of separate arguments that will be in
   4388   /// the expanded form of the corresponding pack expansion. This is both an
   4389   /// input and an output parameter, which can be set by the caller if the
   4390   /// number of expansions is known a priori (e.g., due to a prior substitution)
   4391   /// and will be set by the callee when the number of expansions is known.
   4392   /// The callee must set this value when \c ShouldExpand is \c true; it may
   4393   /// set this value in other cases.
   4394   ///
   4395   /// \returns true if an error occurred (e.g., because the parameter packs
   4396   /// are to be instantiated with arguments of different lengths), false
   4397   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
   4398   /// must be set.
   4399   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
   4400                                        SourceRange PatternRange,
   4401                              llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
   4402                              const MultiLevelTemplateArgumentList &TemplateArgs,
   4403                                        bool &ShouldExpand,
   4404                                        bool &RetainExpansion,
   4405                                        llvm::Optional<unsigned> &NumExpansions);
   4406 
   4407   /// \brief Determine the number of arguments in the given pack expansion
   4408   /// type.
   4409   ///
   4410   /// This routine already assumes that the pack expansion type can be
   4411   /// expanded and that the number of arguments in the expansion is
   4412   /// consistent across all of the unexpanded parameter packs in its pattern.
   4413   unsigned getNumArgumentsInExpansion(QualType T,
   4414                             const MultiLevelTemplateArgumentList &TemplateArgs);
   4415 
   4416   /// \brief Determine whether the given declarator contains any unexpanded
   4417   /// parameter packs.
   4418   ///
   4419   /// This routine is used by the parser to disambiguate function declarators
   4420   /// with an ellipsis prior to the ')', e.g.,
   4421   ///
   4422   /// \code
   4423   ///   void f(T...);
   4424   /// \endcode
   4425   ///
   4426   /// To determine whether we have an (unnamed) function parameter pack or
   4427   /// a variadic function.
   4428   ///
   4429   /// \returns true if the declarator contains any unexpanded parameter packs,
   4430   /// false otherwise.
   4431   bool containsUnexpandedParameterPacks(Declarator &D);
   4432 
   4433   //===--------------------------------------------------------------------===//
   4434   // C++ Template Argument Deduction (C++ [temp.deduct])
   4435   //===--------------------------------------------------------------------===//
   4436 
   4437   /// \brief Describes the result of template argument deduction.
   4438   ///
   4439   /// The TemplateDeductionResult enumeration describes the result of
   4440   /// template argument deduction, as returned from
   4441   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
   4442   /// structure provides additional information about the results of
   4443   /// template argument deduction, e.g., the deduced template argument
   4444   /// list (if successful) or the specific template parameters or
   4445   /// deduced arguments that were involved in the failure.
   4446   enum TemplateDeductionResult {
   4447     /// \brief Template argument deduction was successful.
   4448     TDK_Success = 0,
   4449     /// \brief Template argument deduction exceeded the maximum template
   4450     /// instantiation depth (which has already been diagnosed).
   4451     TDK_InstantiationDepth,
   4452     /// \brief Template argument deduction did not deduce a value
   4453     /// for every template parameter.
   4454     TDK_Incomplete,
   4455     /// \brief Template argument deduction produced inconsistent
   4456     /// deduced values for the given template parameter.
   4457     TDK_Inconsistent,
   4458     /// \brief Template argument deduction failed due to inconsistent
   4459     /// cv-qualifiers on a template parameter type that would
   4460     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
   4461     /// but were given a non-const "X".
   4462     TDK_Underqualified,
   4463     /// \brief Substitution of the deduced template argument values
   4464     /// resulted in an error.
   4465     TDK_SubstitutionFailure,
   4466     /// \brief Substitution of the deduced template argument values
   4467     /// into a non-deduced context produced a type or value that
   4468     /// produces a type that does not match the original template
   4469     /// arguments provided.
   4470     TDK_NonDeducedMismatch,
   4471     /// \brief When performing template argument deduction for a function
   4472     /// template, there were too many call arguments.
   4473     TDK_TooManyArguments,
   4474     /// \brief When performing template argument deduction for a function
   4475     /// template, there were too few call arguments.
   4476     TDK_TooFewArguments,
   4477     /// \brief The explicitly-specified template arguments were not valid
   4478     /// template arguments for the given template.
   4479     TDK_InvalidExplicitArguments,
   4480     /// \brief The arguments included an overloaded function name that could
   4481     /// not be resolved to a suitable function.
   4482     TDK_FailedOverloadResolution
   4483   };
   4484 
   4485   TemplateDeductionResult
   4486   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
   4487                           const TemplateArgumentList &TemplateArgs,
   4488                           sema::TemplateDeductionInfo &Info);
   4489 
   4490   TemplateDeductionResult
   4491   SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
   4492                               TemplateArgumentListInfo &ExplicitTemplateArgs,
   4493                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
   4494                                  SmallVectorImpl<QualType> &ParamTypes,
   4495                                       QualType *FunctionType,
   4496                                       sema::TemplateDeductionInfo &Info);
   4497 
   4498   /// brief A function argument from which we performed template argument
   4499   // deduction for a call.
   4500   struct OriginalCallArg {
   4501     OriginalCallArg(QualType OriginalParamType,
   4502                     unsigned ArgIdx,
   4503                     QualType OriginalArgType)
   4504       : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
   4505         OriginalArgType(OriginalArgType) { }
   4506 
   4507     QualType OriginalParamType;
   4508     unsigned ArgIdx;
   4509     QualType OriginalArgType;
   4510   };
   4511 
   4512   TemplateDeductionResult
   4513   FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
   4514                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
   4515                                   unsigned NumExplicitlySpecified,
   4516                                   FunctionDecl *&Specialization,
   4517                                   sema::TemplateDeductionInfo &Info,
   4518            SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
   4519 
   4520   TemplateDeductionResult
   4521   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
   4522                           TemplateArgumentListInfo *ExplicitTemplateArgs,
   4523                           Expr **Args, unsigned NumArgs,
   4524                           FunctionDecl *&Specialization,
   4525                           sema::TemplateDeductionInfo &Info);
   4526 
   4527   TemplateDeductionResult
   4528   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
   4529                           TemplateArgumentListInfo *ExplicitTemplateArgs,
   4530                           QualType ArgFunctionType,
   4531                           FunctionDecl *&Specialization,
   4532                           sema::TemplateDeductionInfo &Info);
   4533 
   4534   TemplateDeductionResult
   4535   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
   4536                           QualType ToType,
   4537                           CXXConversionDecl *&Specialization,
   4538                           sema::TemplateDeductionInfo &Info);
   4539 
   4540   TemplateDeductionResult
   4541   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
   4542                           TemplateArgumentListInfo *ExplicitTemplateArgs,
   4543                           FunctionDecl *&Specialization,
   4544                           sema::TemplateDeductionInfo &Info);
   4545 
   4546   bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer,
   4547                       TypeSourceInfo *&Result);
   4548 
   4549   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
   4550                                                    FunctionTemplateDecl *FT2,
   4551                                                    SourceLocation Loc,
   4552                                            TemplatePartialOrderingContext TPOC,
   4553                                                    unsigned NumCallArguments);
   4554   UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
   4555                                            UnresolvedSetIterator SEnd,
   4556                                            TemplatePartialOrderingContext TPOC,
   4557                                            unsigned NumCallArguments,
   4558                                            SourceLocation Loc,
   4559                                            const PartialDiagnostic &NoneDiag,
   4560                                            const PartialDiagnostic &AmbigDiag,
   4561                                         const PartialDiagnostic &CandidateDiag,
   4562                                         bool Complain = true);
   4563 
   4564   ClassTemplatePartialSpecializationDecl *
   4565   getMoreSpecializedPartialSpecialization(
   4566                                   ClassTemplatePartialSpecializationDecl *PS1,
   4567                                   ClassTemplatePartialSpecializationDecl *PS2,
   4568                                   SourceLocation Loc);
   4569 
   4570   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
   4571                                   bool OnlyDeduced,
   4572                                   unsigned Depth,
   4573                                   SmallVectorImpl<bool> &Used);
   4574   void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
   4575                                      SmallVectorImpl<bool> &Deduced);
   4576 
   4577   //===--------------------------------------------------------------------===//
   4578   // C++ Template Instantiation
   4579   //
   4580 
   4581   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
   4582                                      const TemplateArgumentList *Innermost = 0,
   4583                                                 bool RelativeToPrimary = false,
   4584                                                const FunctionDecl *Pattern = 0);
   4585 
   4586   /// \brief A template instantiation that is currently in progress.
   4587   struct ActiveTemplateInstantiation {
   4588     /// \brief The kind of template instantiation we are performing
   4589     enum InstantiationKind {
   4590       /// We are instantiating a template declaration. The entity is
   4591       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
   4592       TemplateInstantiation,
   4593 
   4594       /// We are instantiating a default argument for a template
   4595       /// parameter. The Entity is the template, and
   4596       /// TemplateArgs/NumTemplateArguments provides the template
   4597       /// arguments as specified.
   4598       /// FIXME: Use a TemplateArgumentList
   4599       DefaultTemplateArgumentInstantiation,
   4600 
   4601       /// We are instantiating a default argument for a function.
   4602       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
   4603       /// provides the template arguments as specified.
   4604       DefaultFunctionArgumentInstantiation,
   4605 
   4606       /// We are substituting explicit template arguments provided for
   4607       /// a function template. The entity is a FunctionTemplateDecl.
   4608       ExplicitTemplateArgumentSubstitution,
   4609 
   4610       /// We are substituting template argument determined as part of
   4611       /// template argument deduction for either a class template
   4612       /// partial specialization or a function template. The
   4613       /// Entity is either a ClassTemplatePartialSpecializationDecl or
   4614       /// a FunctionTemplateDecl.
   4615       DeducedTemplateArgumentSubstitution,
   4616 
   4617       /// We are substituting prior template arguments into a new
   4618       /// template parameter. The template parameter itself is either a
   4619       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
   4620       PriorTemplateArgumentSubstitution,
   4621 
   4622       /// We are checking the validity of a default template argument that
   4623       /// has been used when naming a template-id.
   4624       DefaultTemplateArgumentChecking
   4625     } Kind;
   4626 
   4627     /// \brief The point of instantiation within the source code.
   4628     SourceLocation PointOfInstantiation;
   4629 
   4630     /// \brief The template (or partial specialization) in which we are
   4631     /// performing the instantiation, for substitutions of prior template
   4632     /// arguments.
   4633     NamedDecl *Template;
   4634 
   4635     /// \brief The entity that is being instantiated.
   4636     uintptr_t Entity;
   4637 
   4638     /// \brief The list of template arguments we are substituting, if they
   4639     /// are not part of the entity.
   4640     const TemplateArgument *TemplateArgs;
   4641 
   4642     /// \brief The number of template arguments in TemplateArgs.
   4643     unsigned NumTemplateArgs;
   4644 
   4645     /// \brief The template deduction info object associated with the
   4646     /// substitution or checking of explicit or deduced template arguments.
   4647     sema::TemplateDeductionInfo *DeductionInfo;
   4648 
   4649     /// \brief The source range that covers the construct that cause
   4650     /// the instantiation, e.g., the template-id that causes a class
   4651     /// template instantiation.
   4652     SourceRange InstantiationRange;
   4653 
   4654     ActiveTemplateInstantiation()
   4655       : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
   4656         NumTemplateArgs(0), DeductionInfo(0) {}
   4657 
   4658     /// \brief Determines whether this template is an actual instantiation
   4659     /// that should be counted toward the maximum instantiation depth.
   4660     bool isInstantiationRecord() const;
   4661 
   4662     friend bool operator==(const ActiveTemplateInstantiation &X,
   4663                            const ActiveTemplateInstantiation &Y) {
   4664       if (X.Kind != Y.Kind)
   4665         return false;
   4666 
   4667       if (X.Entity != Y.Entity)
   4668         return false;
   4669 
   4670       switch (X.Kind) {
   4671       case TemplateInstantiation:
   4672         return true;
   4673 
   4674       case PriorTemplateArgumentSubstitution:
   4675       case DefaultTemplateArgumentChecking:
   4676         if (X.Template != Y.Template)
   4677           return false;
   4678 
   4679         // Fall through
   4680 
   4681       case DefaultTemplateArgumentInstantiation:
   4682       case ExplicitTemplateArgumentSubstitution:
   4683       case DeducedTemplateArgumentSubstitution:
   4684       case DefaultFunctionArgumentInstantiation:
   4685         return X.TemplateArgs == Y.TemplateArgs;
   4686 
   4687       }
   4688 
   4689       return true;
   4690     }
   4691 
   4692     friend bool operator!=(const ActiveTemplateInstantiation &X,
   4693                            const ActiveTemplateInstantiation &Y) {
   4694       return !(X == Y);
   4695     }
   4696   };
   4697 
   4698   /// \brief List of active template instantiations.
   4699   ///
   4700   /// This vector is treated as a stack. As one template instantiation
   4701   /// requires another template instantiation, additional
   4702   /// instantiations are pushed onto the stack up to a
   4703   /// user-configurable limit LangOptions::InstantiationDepth.
   4704   SmallVector<ActiveTemplateInstantiation, 16>
   4705     ActiveTemplateInstantiations;
   4706 
   4707   /// \brief Whether we are in a SFINAE context that is not associated with
   4708   /// template instantiation.
   4709   ///
   4710   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
   4711   /// of a template instantiation or template argument deduction.
   4712   bool InNonInstantiationSFINAEContext;
   4713 
   4714   /// \brief The number of ActiveTemplateInstantiation entries in
   4715   /// \c ActiveTemplateInstantiations that are not actual instantiations and,
   4716   /// therefore, should not be counted as part of the instantiation depth.
   4717   unsigned NonInstantiationEntries;
   4718 
   4719   /// \brief The last template from which a template instantiation
   4720   /// error or warning was produced.
   4721   ///
   4722   /// This value is used to suppress printing of redundant template
   4723   /// instantiation backtraces when there are multiple errors in the
   4724   /// same instantiation. FIXME: Does this belong in Sema? It's tough
   4725   /// to implement it anywhere else.
   4726   ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
   4727 
   4728   /// \brief The current index into pack expansion arguments that will be
   4729   /// used for substitution of parameter packs.
   4730   ///
   4731   /// The pack expansion index will be -1 to indicate that parameter packs
   4732   /// should be instantiated as themselves. Otherwise, the index specifies
   4733   /// which argument within the parameter pack will be used for substitution.
   4734   int ArgumentPackSubstitutionIndex;
   4735 
   4736   /// \brief RAII object used to change the argument pack substitution index
   4737   /// within a \c Sema object.
   4738   ///
   4739   /// See \c ArgumentPackSubstitutionIndex for more information.
   4740   class ArgumentPackSubstitutionIndexRAII {
   4741     Sema &Self;
   4742     int OldSubstitutionIndex;
   4743 
   4744   public:
   4745     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
   4746       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
   4747       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
   4748     }
   4749 
   4750     ~ArgumentPackSubstitutionIndexRAII() {
   4751       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
   4752     }
   4753   };
   4754 
   4755   friend class ArgumentPackSubstitutionRAII;
   4756 
   4757   /// \brief The stack of calls expression undergoing template instantiation.
   4758   ///
   4759   /// The top of this stack is used by a fixit instantiating unresolved
   4760   /// function calls to fix the AST to match the textual change it prints.
   4761   SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
   4762 
   4763   /// \brief For each declaration that involved template argument deduction, the
   4764   /// set of diagnostics that were suppressed during that template argument
   4765   /// deduction.
   4766   ///
   4767   /// FIXME: Serialize this structure to the AST file.
   4768   llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
   4769     SuppressedDiagnostics;
   4770 
   4771   /// \brief A stack object to be created when performing template
   4772   /// instantiation.
   4773   ///
   4774   /// Construction of an object of type \c InstantiatingTemplate
   4775   /// pushes the current instantiation onto the stack of active
   4776   /// instantiations. If the size of this stack exceeds the maximum
   4777   /// number of recursive template instantiations, construction
   4778   /// produces an error and evaluates true.
   4779   ///
   4780   /// Destruction of this object will pop the named instantiation off
   4781   /// the stack.
   4782   struct InstantiatingTemplate {
   4783     /// \brief Note that we are instantiating a class template,
   4784     /// function template, or a member thereof.
   4785     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4786                           Decl *Entity,
   4787                           SourceRange InstantiationRange = SourceRange());
   4788 
   4789     /// \brief Note that we are instantiating a default argument in a
   4790     /// template-id.
   4791     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4792                           TemplateDecl *Template,
   4793                           const TemplateArgument *TemplateArgs,
   4794                           unsigned NumTemplateArgs,
   4795                           SourceRange InstantiationRange = SourceRange());
   4796 
   4797     /// \brief Note that we are instantiating a default argument in a
   4798     /// template-id.
   4799     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4800                           FunctionTemplateDecl *FunctionTemplate,
   4801                           const TemplateArgument *TemplateArgs,
   4802                           unsigned NumTemplateArgs,
   4803                           ActiveTemplateInstantiation::InstantiationKind Kind,
   4804                           sema::TemplateDeductionInfo &DeductionInfo,
   4805                           SourceRange InstantiationRange = SourceRange());
   4806 
   4807     /// \brief Note that we are instantiating as part of template
   4808     /// argument deduction for a class template partial
   4809     /// specialization.
   4810     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4811                           ClassTemplatePartialSpecializationDecl *PartialSpec,
   4812                           const TemplateArgument *TemplateArgs,
   4813                           unsigned NumTemplateArgs,
   4814                           sema::TemplateDeductionInfo &DeductionInfo,
   4815                           SourceRange InstantiationRange = SourceRange());
   4816 
   4817     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4818                           ParmVarDecl *Param,
   4819                           const TemplateArgument *TemplateArgs,
   4820                           unsigned NumTemplateArgs,
   4821                           SourceRange InstantiationRange = SourceRange());
   4822 
   4823     /// \brief Note that we are substituting prior template arguments into a
   4824     /// non-type or template template parameter.
   4825     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4826                           NamedDecl *Template,
   4827                           NonTypeTemplateParmDecl *Param,
   4828                           const TemplateArgument *TemplateArgs,
   4829                           unsigned NumTemplateArgs,
   4830                           SourceRange InstantiationRange);
   4831 
   4832     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4833                           NamedDecl *Template,
   4834                           TemplateTemplateParmDecl *Param,
   4835                           const TemplateArgument *TemplateArgs,
   4836                           unsigned NumTemplateArgs,
   4837                           SourceRange InstantiationRange);
   4838 
   4839     /// \brief Note that we are checking the default template argument
   4840     /// against the template parameter for a given template-id.
   4841     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
   4842                           TemplateDecl *Template,
   4843                           NamedDecl *Param,
   4844                           const TemplateArgument *TemplateArgs,
   4845                           unsigned NumTemplateArgs,
   4846                           SourceRange InstantiationRange);
   4847 
   4848 
   4849     /// \brief Note that we have finished instantiating this template.
   4850     void Clear();
   4851 
   4852     ~InstantiatingTemplate() { Clear(); }
   4853 
   4854     /// \brief Determines whether we have exceeded the maximum
   4855     /// recursive template instantiations.
   4856     operator bool() const { return Invalid; }
   4857 
   4858   private:
   4859     Sema &SemaRef;
   4860     bool Invalid;
   4861     bool SavedInNonInstantiationSFINAEContext;
   4862     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
   4863                                  SourceRange InstantiationRange);
   4864 
   4865     InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
   4866 
   4867     InstantiatingTemplate&
   4868     operator=(const InstantiatingTemplate&); // not implemented
   4869   };
   4870 
   4871   void PrintInstantiationStack();
   4872 
   4873   /// \brief Determines whether we are currently in a context where
   4874   /// template argument substitution failures are not considered
   4875   /// errors.
   4876   ///
   4877   /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
   4878   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
   4879   /// template-deduction context object, which can be used to capture
   4880   /// diagnostics that will be suppressed.
   4881   llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
   4882 
   4883   /// \brief RAII class used to determine whether SFINAE has
   4884   /// trapped any errors that occur during template argument
   4885   /// deduction.`
   4886   class SFINAETrap {
   4887     Sema &SemaRef;
   4888     unsigned PrevSFINAEErrors;
   4889     bool PrevInNonInstantiationSFINAEContext;
   4890     bool PrevAccessCheckingSFINAE;
   4891 
   4892   public:
   4893     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
   4894       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
   4895         PrevInNonInstantiationSFINAEContext(
   4896                                       SemaRef.InNonInstantiationSFINAEContext),
   4897         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
   4898     {
   4899       if (!SemaRef.isSFINAEContext())
   4900         SemaRef.InNonInstantiationSFINAEContext = true;
   4901       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
   4902     }
   4903 
   4904     ~SFINAETrap() {
   4905       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
   4906       SemaRef.InNonInstantiationSFINAEContext
   4907         = PrevInNonInstantiationSFINAEContext;
   4908       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
   4909     }
   4910 
   4911     /// \brief Determine whether any SFINAE errors have been trapped.
   4912     bool hasErrorOccurred() const {
   4913       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
   4914     }
   4915   };
   4916 
   4917   /// \brief The current instantiation scope used to store local
   4918   /// variables.
   4919   LocalInstantiationScope *CurrentInstantiationScope;
   4920 
   4921   /// \brief The number of typos corrected by CorrectTypo.
   4922   unsigned TyposCorrected;
   4923 
   4924   typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
   4925     UnqualifiedTyposCorrectedMap;
   4926 
   4927   /// \brief A cache containing the results of typo correction for unqualified
   4928   /// name lookup.
   4929   ///
   4930   /// The string is the string that we corrected to (which may be empty, if
   4931   /// there was no correction), while the boolean will be true when the
   4932   /// string represents a keyword.
   4933   UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
   4934 
   4935   /// \brief Worker object for performing CFG-based warnings.
   4936   sema::AnalysisBasedWarnings AnalysisWarnings;
   4937 
   4938   /// \brief An entity for which implicit template instantiation is required.
   4939   ///
   4940   /// The source location associated with the declaration is the first place in
   4941   /// the source code where the declaration was "used". It is not necessarily
   4942   /// the point of instantiation (which will be either before or after the
   4943   /// namespace-scope declaration that triggered this implicit instantiation),
   4944   /// However, it is the location that diagnostics should generally refer to,
   4945   /// because users will need to know what code triggered the instantiation.
   4946   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
   4947 
   4948   /// \brief The queue of implicit template instantiations that are required
   4949   /// but have not yet been performed.
   4950   std::deque<PendingImplicitInstantiation> PendingInstantiations;
   4951 
   4952   /// \brief The queue of implicit template instantiations that are required
   4953   /// and must be performed within the current local scope.
   4954   ///
   4955   /// This queue is only used for member functions of local classes in
   4956   /// templates, which must be instantiated in the same scope as their
   4957   /// enclosing function, so that they can reference function-local
   4958   /// types, static variables, enumerators, etc.
   4959   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
   4960 
   4961   void PerformPendingInstantiations(bool LocalOnly = false);
   4962 
   4963   TypeSourceInfo *SubstType(TypeSourceInfo *T,
   4964                             const MultiLevelTemplateArgumentList &TemplateArgs,
   4965                             SourceLocation Loc, DeclarationName Entity);
   4966 
   4967   QualType SubstType(QualType T,
   4968                      const MultiLevelTemplateArgumentList &TemplateArgs,
   4969                      SourceLocation Loc, DeclarationName Entity);
   4970 
   4971   TypeSourceInfo *SubstType(TypeLoc TL,
   4972                             const MultiLevelTemplateArgumentList &TemplateArgs,
   4973                             SourceLocation Loc, DeclarationName Entity);
   4974 
   4975   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
   4976                             const MultiLevelTemplateArgumentList &TemplateArgs,
   4977                                         SourceLocation Loc,
   4978                                         DeclarationName Entity);
   4979   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
   4980                             const MultiLevelTemplateArgumentList &TemplateArgs,
   4981                                 int indexAdjustment,
   4982                                 llvm::Optional<unsigned> NumExpansions);
   4983   bool SubstParmTypes(SourceLocation Loc,
   4984                       ParmVarDecl **Params, unsigned NumParams,
   4985                       const MultiLevelTemplateArgumentList &TemplateArgs,
   4986                       SmallVectorImpl<QualType> &ParamTypes,
   4987                       SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
   4988   ExprResult SubstExpr(Expr *E,
   4989                        const MultiLevelTemplateArgumentList &TemplateArgs);
   4990 
   4991   /// \brief Substitute the given template arguments into a list of
   4992   /// expressions, expanding pack expansions if required.
   4993   ///
   4994   /// \param Exprs The list of expressions to substitute into.
   4995   ///
   4996   /// \param NumExprs The number of expressions in \p Exprs.
   4997   ///
   4998   /// \param IsCall Whether this is some form of call, in which case
   4999   /// default arguments will be dropped.
   5000   ///
   5001   /// \param TemplateArgs The set of template arguments to substitute.
   5002   ///
   5003   /// \param Outputs Will receive all of the substituted arguments.
   5004   ///
   5005   /// \returns true if an error occurred, false otherwise.
   5006   bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
   5007                   const MultiLevelTemplateArgumentList &TemplateArgs,
   5008                   SmallVectorImpl<Expr *> &Outputs);
   5009 
   5010   StmtResult SubstStmt(Stmt *S,
   5011                        const MultiLevelTemplateArgumentList &TemplateArgs);
   5012 
   5013   Decl *SubstDecl(Decl *D, DeclContext *Owner,
   5014                   const MultiLevelTemplateArgumentList &TemplateArgs);
   5015 
   5016   bool
   5017   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
   5018                       CXXRecordDecl *Pattern,
   5019                       const MultiLevelTemplateArgumentList &TemplateArgs);
   5020 
   5021   bool
   5022   InstantiateClass(SourceLocation PointOfInstantiation,
   5023                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
   5024                    const MultiLevelTemplateArgumentList &TemplateArgs,
   5025                    TemplateSpecializationKind TSK,
   5026                    bool Complain = true);
   5027 
   5028   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
   5029                         const Decl *Pattern, Decl *Inst);
   5030 
   5031   bool
   5032   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
   5033                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
   5034                            TemplateSpecializationKind TSK,
   5035                            bool Complain = true);
   5036 
   5037   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
   5038                                CXXRecordDecl *Instantiation,
   5039                             const MultiLevelTemplateArgumentList &TemplateArgs,
   5040                                TemplateSpecializationKind TSK);
   5041 
   5042   void InstantiateClassTemplateSpecializationMembers(
   5043                                           SourceLocation PointOfInstantiation,
   5044                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
   5045                                                 TemplateSpecializationKind TSK);
   5046 
   5047   NestedNameSpecifierLoc
   5048   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
   5049                            const MultiLevelTemplateArgumentList &TemplateArgs);
   5050 
   5051   DeclarationNameInfo
   5052   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
   5053                            const MultiLevelTemplateArgumentList &TemplateArgs);
   5054   TemplateName
   5055   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
   5056                     SourceLocation Loc,
   5057                     const MultiLevelTemplateArgumentList &TemplateArgs);
   5058   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
   5059              TemplateArgumentListInfo &Result,
   5060              const MultiLevelTemplateArgumentList &TemplateArgs);
   5061 
   5062   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
   5063                                      FunctionDecl *Function,
   5064                                      bool Recursive = false,
   5065                                      bool DefinitionRequired = false);
   5066   void InstantiateStaticDataMemberDefinition(
   5067                                      SourceLocation PointOfInstantiation,
   5068                                      VarDecl *Var,
   5069                                      bool Recursive = false,
   5070                                      bool DefinitionRequired = false);
   5071 
   5072   void InstantiateMemInitializers(CXXConstructorDecl *New,
   5073                                   const CXXConstructorDecl *Tmpl,
   5074                             const MultiLevelTemplateArgumentList &TemplateArgs);
   5075   bool InstantiateInitializer(Expr *Init,
   5076                             const MultiLevelTemplateArgumentList &TemplateArgs,
   5077                               SourceLocation &LParenLoc,
   5078                               ASTOwningVector<Expr*> &NewArgs,
   5079                               SourceLocation &RParenLoc);
   5080 
   5081   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   5082                           const MultiLevelTemplateArgumentList &TemplateArgs);
   5083   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
   5084                           const MultiLevelTemplateArgumentList &TemplateArgs);
   5085 
   5086   // Objective-C declarations.
   5087   Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
   5088                                  IdentifierInfo *ClassName,
   5089                                  SourceLocation ClassLoc,
   5090                                  IdentifierInfo *SuperName,
   5091                                  SourceLocation SuperLoc,
   5092                                  Decl * const *ProtoRefs,
   5093                                  unsigned NumProtoRefs,
   5094                                  const SourceLocation *ProtoLocs,
   5095                                  SourceLocation EndProtoLoc,
   5096                                  AttributeList *AttrList);
   5097 
   5098   Decl *ActOnCompatiblityAlias(
   5099                     SourceLocation AtCompatibilityAliasLoc,
   5100                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
   5101                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
   5102 
   5103   bool CheckForwardProtocolDeclarationForCircularDependency(
   5104     IdentifierInfo *PName,
   5105     SourceLocation &PLoc, SourceLocation PrevLoc,
   5106     const ObjCList<ObjCProtocolDecl> &PList);
   5107 
   5108   Decl *ActOnStartProtocolInterface(
   5109                     SourceLocation AtProtoInterfaceLoc,
   5110                     IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
   5111                     Decl * const *ProtoRefNames, unsigned NumProtoRefs,
   5112                     const SourceLocation *ProtoLocs,
   5113                     SourceLocation EndProtoLoc,
   5114                     AttributeList *AttrList);
   5115 
   5116   Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
   5117                                     IdentifierInfo *ClassName,
   5118                                     SourceLocation ClassLoc,
   5119                                     IdentifierInfo *CategoryName,
   5120                                     SourceLocation CategoryLoc,
   5121                                     Decl * const *ProtoRefs,
   5122                                     unsigned NumProtoRefs,
   5123                                     const SourceLocation *ProtoLocs,
   5124                                     SourceLocation EndProtoLoc);
   5125 
   5126   Decl *ActOnStartClassImplementation(
   5127                     SourceLocation AtClassImplLoc,
   5128                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
   5129                     IdentifierInfo *SuperClassname,
   5130                     SourceLocation SuperClassLoc);
   5131 
   5132   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
   5133                                          IdentifierInfo *ClassName,
   5134                                          SourceLocation ClassLoc,
   5135                                          IdentifierInfo *CatName,
   5136                                          SourceLocation CatLoc);
   5137 
   5138   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
   5139                                      IdentifierInfo **IdentList,
   5140                                      SourceLocation *IdentLocs,
   5141                                      unsigned NumElts);
   5142 
   5143   Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
   5144                                         const IdentifierLocPair *IdentList,
   5145                                         unsigned NumElts,
   5146                                         AttributeList *attrList);
   5147 
   5148   void FindProtocolDeclaration(bool WarnOnDeclarations,
   5149                                const IdentifierLocPair *ProtocolId,
   5150                                unsigned NumProtocols,
   5151                                SmallVectorImpl<Decl *> &Protocols);
   5152 
   5153   /// Ensure attributes are consistent with type.
   5154   /// \param [in, out] Attributes The attributes to check; they will
   5155   /// be modified to be consistent with \arg PropertyTy.
   5156   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
   5157                                    SourceLocation Loc,
   5158                                    unsigned &Attributes);
   5159 
   5160   /// Process the specified property declaration and create decls for the
   5161   /// setters and getters as needed.
   5162   /// \param property The property declaration being processed
   5163   /// \param DC The semantic container for the property
   5164   /// \param redeclaredProperty Declaration for property if redeclared
   5165   ///        in class extension.
   5166   /// \param lexicalDC Container for redeclaredProperty.
   5167   void ProcessPropertyDecl(ObjCPropertyDecl *property,
   5168                            ObjCContainerDecl *DC,
   5169                            ObjCPropertyDecl *redeclaredProperty = 0,
   5170                            ObjCContainerDecl *lexicalDC = 0);
   5171 
   5172   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
   5173                                 ObjCPropertyDecl *SuperProperty,
   5174                                 const IdentifierInfo *Name);
   5175   void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
   5176 
   5177   void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
   5178                                          ObjCMethodDecl *MethodDecl,
   5179                                          bool IsInstance);
   5180 
   5181   void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
   5182 
   5183   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
   5184                                         ObjCInterfaceDecl *ID);
   5185 
   5186   void MatchOneProtocolPropertiesInClass(Decl *CDecl,
   5187                                          ObjCProtocolDecl *PDecl);
   5188 
   5189   void ActOnAtEnd(Scope *S, SourceRange AtEnd,
   5190                   Decl **allMethods = 0, unsigned allNum = 0,
   5191                   Decl **allProperties = 0, unsigned pNum = 0,
   5192                   DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
   5193 
   5194   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
   5195                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
   5196                       Selector GetterSel, Selector SetterSel,
   5197                       bool *OverridingProperty,
   5198                       tok::ObjCKeywordKind MethodImplKind,
   5199                       DeclContext *lexicalDC = 0);
   5200 
   5201   Decl *ActOnPropertyImplDecl(Scope *S,
   5202                               SourceLocation AtLoc,
   5203                               SourceLocation PropertyLoc,
   5204                               bool ImplKind,
   5205                               IdentifierInfo *PropertyId,
   5206                               IdentifierInfo *PropertyIvar,
   5207                               SourceLocation PropertyIvarLoc);
   5208 
   5209   enum ObjCSpecialMethodKind {
   5210     OSMK_None,
   5211     OSMK_Alloc,
   5212     OSMK_New,
   5213     OSMK_Copy,
   5214     OSMK_RetainingInit,
   5215     OSMK_NonRetainingInit
   5216   };
   5217 
   5218   struct ObjCArgInfo {
   5219     IdentifierInfo *Name;
   5220     SourceLocation NameLoc;
   5221     // The Type is null if no type was specified, and the DeclSpec is invalid
   5222     // in this case.
   5223     ParsedType Type;
   5224     ObjCDeclSpec DeclSpec;
   5225 
   5226     /// ArgAttrs - Attribute list for this argument.
   5227     AttributeList *ArgAttrs;
   5228   };
   5229 
   5230   Decl *ActOnMethodDeclaration(
   5231     Scope *S,
   5232     SourceLocation BeginLoc, // location of the + or -.
   5233     SourceLocation EndLoc,   // location of the ; or {.
   5234     tok::TokenKind MethodType,
   5235     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
   5236     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
   5237     // optional arguments. The number of types/arguments is obtained
   5238     // from the Sel.getNumArgs().
   5239     ObjCArgInfo *ArgInfo,
   5240     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
   5241     AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
   5242     bool isVariadic, bool MethodDefinition);
   5243 
   5244   // Helper method for ActOnClassMethod/ActOnInstanceMethod.
   5245   // Will search "local" class/category implementations for a method decl.
   5246   // Will also search in class's root looking for instance method.
   5247   // Returns 0 if no method is found.
   5248   ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
   5249                                            ObjCInterfaceDecl *CDecl);
   5250   ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
   5251                                               ObjCInterfaceDecl *ClassDecl);
   5252   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
   5253                                               const ObjCObjectPointerType *OPT,
   5254                                               bool IsInstance);
   5255 
   5256   bool inferObjCARCLifetime(ValueDecl *decl);
   5257 
   5258   ExprResult
   5259   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
   5260                             Expr *BaseExpr,
   5261                             SourceLocation OpLoc,
   5262                             DeclarationName MemberName,
   5263                             SourceLocation MemberLoc,
   5264                             SourceLocation SuperLoc, QualType SuperType,
   5265                             bool Super);
   5266 
   5267   ExprResult
   5268   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
   5269                             IdentifierInfo &propertyName,
   5270                             SourceLocation receiverNameLoc,
   5271                             SourceLocation propertyNameLoc);
   5272 
   5273   ObjCMethodDecl *tryCaptureObjCSelf();
   5274 
   5275   /// \brief Describes the kind of message expression indicated by a message
   5276   /// send that starts with an identifier.
   5277   enum ObjCMessageKind {
   5278     /// \brief The message is sent to 'super'.
   5279     ObjCSuperMessage,
   5280     /// \brief The message is an instance message.
   5281     ObjCInstanceMessage,
   5282     /// \brief The message is a class message, and the identifier is a type
   5283     /// name.
   5284     ObjCClassMessage
   5285   };
   5286 
   5287   ObjCMessageKind getObjCMessageKind(Scope *S,
   5288                                      IdentifierInfo *Name,
   5289                                      SourceLocation NameLoc,
   5290                                      bool IsSuper,
   5291                                      bool HasTrailingDot,
   5292                                      ParsedType &ReceiverType);
   5293 
   5294   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
   5295                                Selector Sel,
   5296                                SourceLocation LBracLoc,
   5297                                ArrayRef<SourceLocation> SelectorLocs,
   5298                                SourceLocation RBracLoc,
   5299                                MultiExprArg Args);
   5300 
   5301   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
   5302                                QualType ReceiverType,
   5303                                SourceLocation SuperLoc,
   5304                                Selector Sel,
   5305                                ObjCMethodDecl *Method,
   5306                                SourceLocation LBracLoc,
   5307                                ArrayRef<SourceLocation> SelectorLocs,
   5308                                SourceLocation RBracLoc,
   5309                                MultiExprArg Args);
   5310 
   5311   ExprResult ActOnClassMessage(Scope *S,
   5312                                ParsedType Receiver,
   5313                                Selector Sel,
   5314                                SourceLocation LBracLoc,
   5315                                ArrayRef<SourceLocation> SelectorLocs,
   5316                                SourceLocation RBracLoc,
   5317                                MultiExprArg Args);
   5318 
   5319   ExprResult BuildInstanceMessage(Expr *Receiver,
   5320                                   QualType ReceiverType,
   5321                                   SourceLocation SuperLoc,
   5322                                   Selector Sel,
   5323                                   ObjCMethodDecl *Method,
   5324                                   SourceLocation LBracLoc,
   5325                                   ArrayRef<SourceLocation> SelectorLocs,
   5326                                   SourceLocation RBracLoc,
   5327                                   MultiExprArg Args);
   5328 
   5329   ExprResult ActOnInstanceMessage(Scope *S,
   5330                                   Expr *Receiver,
   5331                                   Selector Sel,
   5332                                   SourceLocation LBracLoc,
   5333                                   ArrayRef<SourceLocation> SelectorLocs,
   5334                                   SourceLocation RBracLoc,
   5335                                   MultiExprArg Args);
   5336 
   5337   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
   5338                                   ObjCBridgeCastKind Kind,
   5339                                   SourceLocation BridgeKeywordLoc,
   5340                                   TypeSourceInfo *TSInfo,
   5341                                   Expr *SubExpr);
   5342 
   5343   ExprResult ActOnObjCBridgedCast(Scope *S,
   5344                                   SourceLocation LParenLoc,
   5345                                   ObjCBridgeCastKind Kind,
   5346                                   SourceLocation BridgeKeywordLoc,
   5347                                   ParsedType Type,
   5348                                   SourceLocation RParenLoc,
   5349                                   Expr *SubExpr);
   5350 
   5351   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
   5352 
   5353   /// \brief Check whether the given new method is a valid override of the
   5354   /// given overridden method, and set any properties that should be inherited.
   5355   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
   5356                                const ObjCMethodDecl *Overridden,
   5357                                bool IsImplementation);
   5358 
   5359   /// \brief Check whether the given method overrides any methods in its class,
   5360   /// calling \c CheckObjCMethodOverride for each overridden method.
   5361   bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC);
   5362 
   5363   enum PragmaOptionsAlignKind {
   5364     POAK_Native,  // #pragma options align=native
   5365     POAK_Natural, // #pragma options align=natural
   5366     POAK_Packed,  // #pragma options align=packed
   5367     POAK_Power,   // #pragma options align=power
   5368     POAK_Mac68k,  // #pragma options align=mac68k
   5369     POAK_Reset    // #pragma options align=reset
   5370   };
   5371 
   5372   /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
   5373   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
   5374                                SourceLocation PragmaLoc,
   5375                                SourceLocation KindLoc);
   5376 
   5377   enum PragmaPackKind {
   5378     PPK_Default, // #pragma pack([n])
   5379     PPK_Show,    // #pragma pack(show), only supported by MSVC.
   5380     PPK_Push,    // #pragma pack(push, [identifier], [n])
   5381     PPK_Pop      // #pragma pack(pop, [identifier], [n])
   5382   };
   5383 
   5384   enum PragmaMSStructKind {
   5385     PMSST_OFF,  // #pragms ms_struct off
   5386     PMSST_ON    // #pragms ms_struct on
   5387   };
   5388 
   5389   /// ActOnPragmaPack - Called on well formed #pragma pack(...).
   5390   void ActOnPragmaPack(PragmaPackKind Kind,
   5391                        IdentifierInfo *Name,
   5392                        Expr *Alignment,
   5393                        SourceLocation PragmaLoc,
   5394                        SourceLocation LParenLoc,
   5395                        SourceLocation RParenLoc);
   5396 
   5397   /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
   5398   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
   5399 
   5400   /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
   5401   void ActOnPragmaUnused(const Token &Identifier,
   5402                          Scope *curScope,
   5403                          SourceLocation PragmaLoc);
   5404 
   5405   /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
   5406   void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
   5407                              SourceLocation PragmaLoc);
   5408 
   5409   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
   5410                                  SourceLocation Loc);
   5411   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
   5412 
   5413   /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
   5414   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
   5415                          SourceLocation PragmaLoc,
   5416                          SourceLocation WeakNameLoc);
   5417 
   5418   /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
   5419   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
   5420                             IdentifierInfo* AliasName,
   5421                             SourceLocation PragmaLoc,
   5422                             SourceLocation WeakNameLoc,
   5423                             SourceLocation AliasNameLoc);
   5424 
   5425   /// ActOnPragmaFPContract - Called on well formed
   5426   /// #pragma {STDC,OPENCL} FP_CONTRACT
   5427   void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
   5428 
   5429   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
   5430   /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
   5431   void AddAlignmentAttributesForRecord(RecordDecl *RD);
   5432 
   5433   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
   5434   void AddMsStructLayoutForRecord(RecordDecl *RD);
   5435 
   5436   /// FreePackedContext - Deallocate and null out PackContext.
   5437   void FreePackedContext();
   5438 
   5439   /// PushNamespaceVisibilityAttr - Note that we've entered a
   5440   /// namespace with a visibility attribute.
   5441   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
   5442 
   5443   /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
   5444   /// add an appropriate visibility attribute.
   5445   void AddPushedVisibilityAttribute(Decl *RD);
   5446 
   5447   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
   5448   /// for '#pragma GCC visibility' and visibility attributes on namespaces.
   5449   void PopPragmaVisibility();
   5450 
   5451   /// FreeVisContext - Deallocate and null out VisContext.
   5452   void FreeVisContext();
   5453 
   5454   /// AddCFAuditedAttribute - Check whether we're currently within
   5455   /// '#pragma clang arc_cf_code_audited' and, if so, consider adding
   5456   /// the appropriate attribute.
   5457   void AddCFAuditedAttribute(Decl *D);
   5458 
   5459   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
   5460   void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E);
   5461   void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T);
   5462 
   5463   /// \brief The kind of conversion being performed.
   5464   enum CheckedConversionKind {
   5465     /// \brief An implicit conversion.
   5466     CCK_ImplicitConversion,
   5467     /// \brief A C-style cast.
   5468     CCK_CStyleCast,
   5469     /// \brief A functional-style cast.
   5470     CCK_FunctionalCast,
   5471     /// \brief A cast other than a C-style cast.
   5472     CCK_OtherCast
   5473   };
   5474 
   5475   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
   5476   /// cast.  If there is already an implicit cast, merge into the existing one.
   5477   /// If isLvalue, the result of the cast is an lvalue.
   5478   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
   5479                                ExprValueKind VK = VK_RValue,
   5480                                const CXXCastPath *BasePath = 0,
   5481                                CheckedConversionKind CCK
   5482                                   = CCK_ImplicitConversion);
   5483 
   5484   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
   5485   /// to the conversion from scalar type ScalarTy to the Boolean type.
   5486   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
   5487 
   5488   /// IgnoredValueConversions - Given that an expression's result is
   5489   /// syntactically ignored, perform any conversions that are
   5490   /// required.
   5491   ExprResult IgnoredValueConversions(Expr *E);
   5492 
   5493   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
   5494   // functions and arrays to their respective pointers (C99 6.3.2.1).
   5495   ExprResult UsualUnaryConversions(Expr *E);
   5496 
   5497   // DefaultFunctionArrayConversion - converts functions and arrays
   5498   // to their respective pointers (C99 6.3.2.1).
   5499   ExprResult DefaultFunctionArrayConversion(Expr *E);
   5500 
   5501   // DefaultFunctionArrayLvalueConversion - converts functions and
   5502   // arrays to their respective pointers and performs the
   5503   // lvalue-to-rvalue conversion.
   5504   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
   5505 
   5506   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
   5507   // the operand.  This is DefaultFunctionArrayLvalueConversion,
   5508   // except that it assumes the operand isn't of function or array
   5509   // type.
   5510   ExprResult DefaultLvalueConversion(Expr *E);
   5511 
   5512   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
   5513   // do not have a prototype. Integer promotions are performed on each
   5514   // argument, and arguments that have type float are promoted to double.
   5515   ExprResult DefaultArgumentPromotion(Expr *E);
   5516 
   5517   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
   5518   enum VariadicCallType {
   5519     VariadicFunction,
   5520     VariadicBlock,
   5521     VariadicMethod,
   5522     VariadicConstructor,
   5523     VariadicDoesNotApply
   5524   };
   5525 
   5526   /// GatherArgumentsForCall - Collector argument expressions for various
   5527   /// form of call prototypes.
   5528   bool GatherArgumentsForCall(SourceLocation CallLoc,
   5529                               FunctionDecl *FDecl,
   5530                               const FunctionProtoType *Proto,
   5531                               unsigned FirstProtoArg,
   5532                               Expr **Args, unsigned NumArgs,
   5533                               SmallVector<Expr *, 8> &AllArgs,
   5534                               VariadicCallType CallType = VariadicDoesNotApply);
   5535 
   5536   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
   5537   // will warn if the resulting type is not a POD type.
   5538   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
   5539                                               FunctionDecl *FDecl);
   5540 
   5541   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
   5542   // operands and then handles various conversions that are common to binary
   5543   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
   5544   // routine returns the first non-arithmetic type found. The client is
   5545   // responsible for emitting appropriate error diagnostics.
   5546   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
   5547                                       bool IsCompAssign = false);
   5548 
   5549   /// AssignConvertType - All of the 'assignment' semantic checks return this
   5550   /// enum to indicate whether the assignment was allowed.  These checks are
   5551   /// done for simple assignments, as well as initialization, return from
   5552   /// function, argument passing, etc.  The query is phrased in terms of a
   5553   /// source and destination type.
   5554   enum AssignConvertType {
   5555     /// Compatible - the types are compatible according to the standard.
   5556     Compatible,
   5557 
   5558     /// PointerToInt - The assignment converts a pointer to an int, which we
   5559     /// accept as an extension.
   5560     PointerToInt,
   5561 
   5562     /// IntToPointer - The assignment converts an int to a pointer, which we
   5563     /// accept as an extension.
   5564     IntToPointer,
   5565 
   5566     /// FunctionVoidPointer - The assignment is between a function pointer and
   5567     /// void*, which the standard doesn't allow, but we accept as an extension.
   5568     FunctionVoidPointer,
   5569 
   5570     /// IncompatiblePointer - The assignment is between two pointers types that
   5571     /// are not compatible, but we accept them as an extension.
   5572     IncompatiblePointer,
   5573 
   5574     /// IncompatiblePointer - The assignment is between two pointers types which
   5575     /// point to integers which have a different sign, but are otherwise identical.
   5576     /// This is a subset of the above, but broken out because it's by far the most
   5577     /// common case of incompatible pointers.
   5578     IncompatiblePointerSign,
   5579 
   5580     /// CompatiblePointerDiscardsQualifiers - The assignment discards
   5581     /// c/v/r qualifiers, which we accept as an extension.
   5582     CompatiblePointerDiscardsQualifiers,
   5583 
   5584     /// IncompatiblePointerDiscardsQualifiers - The assignment
   5585     /// discards qualifiers that we don't permit to be discarded,
   5586     /// like address spaces.
   5587     IncompatiblePointerDiscardsQualifiers,
   5588 
   5589     /// IncompatibleNestedPointerQualifiers - The assignment is between two
   5590     /// nested pointer types, and the qualifiers other than the first two
   5591     /// levels differ e.g. char ** -> const char **, but we accept them as an
   5592     /// extension.
   5593     IncompatibleNestedPointerQualifiers,
   5594 
   5595     /// IncompatibleVectors - The assignment is between two vector types that
   5596     /// have the same size, which we accept as an extension.
   5597     IncompatibleVectors,
   5598 
   5599     /// IntToBlockPointer - The assignment converts an int to a block
   5600     /// pointer. We disallow this.
   5601     IntToBlockPointer,
   5602 
   5603     /// IncompatibleBlockPointer - The assignment is between two block
   5604     /// pointers types that are not compatible.
   5605     IncompatibleBlockPointer,
   5606 
   5607     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
   5608     /// id type and something else (that is incompatible with it). For example,
   5609     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
   5610     IncompatibleObjCQualifiedId,
   5611 
   5612     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
   5613     /// object with __weak qualifier.
   5614     IncompatibleObjCWeakRef,
   5615 
   5616     /// Incompatible - We reject this conversion outright, it is invalid to
   5617     /// represent it in the AST.
   5618     Incompatible
   5619   };
   5620 
   5621   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
   5622   /// assignment conversion type specified by ConvTy.  This returns true if the
   5623   /// conversion was invalid or false if the conversion was accepted.
   5624   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
   5625                                 SourceLocation Loc,
   5626                                 QualType DstType, QualType SrcType,
   5627                                 Expr *SrcExpr, AssignmentAction Action,
   5628                                 bool *Complained = 0);
   5629 
   5630   /// CheckAssignmentConstraints - Perform type checking for assignment,
   5631   /// argument passing, variable initialization, and function return values.
   5632   /// C99 6.5.16.
   5633   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
   5634                                                QualType LHSType,
   5635                                                QualType RHSType);
   5636 
   5637   /// Check assignment constraints and prepare for a conversion of the
   5638   /// RHS to the LHS type.
   5639   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
   5640                                                ExprResult &RHS,
   5641                                                CastKind &Kind);
   5642 
   5643   // CheckSingleAssignmentConstraints - Currently used by
   5644   // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
   5645   // this routine performs the default function/array converions.
   5646   AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
   5647                                                      ExprResult &RHS,
   5648                                                      bool Diagnose = true);
   5649 
   5650   // \brief If the lhs type is a transparent union, check whether we
   5651   // can initialize the transparent union with the given expression.
   5652   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
   5653                                                              ExprResult &RHS);
   5654 
   5655   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
   5656 
   5657   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
   5658 
   5659   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
   5660                                        AssignmentAction Action,
   5661                                        bool AllowExplicit = false);
   5662   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
   5663                                        AssignmentAction Action,
   5664                                        bool AllowExplicit,
   5665                                        ImplicitConversionSequence& ICS);
   5666   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
   5667                                        const ImplicitConversionSequence& ICS,
   5668                                        AssignmentAction Action,
   5669                                        CheckedConversionKind CCK
   5670                                           = CCK_ImplicitConversion);
   5671   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
   5672                                        const StandardConversionSequence& SCS,
   5673                                        AssignmentAction Action,
   5674                                        CheckedConversionKind CCK);
   5675 
   5676   /// the following "Check" methods will return a valid/converted QualType
   5677   /// or a null QualType (indicating an error diagnostic was issued).
   5678 
   5679   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
   5680   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
   5681                            ExprResult &RHS);
   5682   QualType CheckPointerToMemberOperands( // C++ 5.5
   5683     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
   5684     SourceLocation OpLoc, bool isIndirect);
   5685   QualType CheckMultiplyDivideOperands( // C99 6.5.5
   5686     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
   5687     bool IsDivide);
   5688   QualType CheckRemainderOperands( // C99 6.5.5
   5689     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
   5690     bool IsCompAssign = false);
   5691   QualType CheckAdditionOperands( // C99 6.5.6
   5692     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
   5693     QualType* CompLHSTy = 0);
   5694   QualType CheckSubtractionOperands( // C99 6.5.6
   5695     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
   5696     QualType* CompLHSTy = 0);
   5697   QualType CheckShiftOperands( // C99 6.5.7
   5698     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
   5699     bool IsCompAssign = false);
   5700   QualType CheckCompareOperands( // C99 6.5.8/9
   5701     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
   5702                                 bool isRelational);
   5703   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
   5704     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
   5705     bool IsCompAssign = false);
   5706   QualType CheckLogicalOperands( // C99 6.5.[13,14]
   5707     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
   5708   // CheckAssignmentOperands is used for both simple and compound assignment.
   5709   // For simple assignment, pass both expressions and a null converted type.
   5710   // For compound assignment, pass both expressions and the converted type.
   5711   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
   5712     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
   5713 
   5714   void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
   5715                                 QualType& LHSTy);
   5716   ExprResult ConvertPropertyForRValue(Expr *E);
   5717 
   5718   QualType CheckConditionalOperands( // C99 6.5.15
   5719     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
   5720     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
   5721   QualType CXXCheckConditionalOperands( // C++ 5.16
   5722     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
   5723     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
   5724   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
   5725                                     bool *NonStandardCompositeType = 0);
   5726   QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2,
   5727                                     bool *NonStandardCompositeType = 0) {
   5728     Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
   5729     QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType);
   5730     E1 = Owned(E1Tmp);
   5731     E2 = Owned(E2Tmp);
   5732     return Composite;
   5733   }
   5734 
   5735   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
   5736                                         SourceLocation QuestionLoc);
   5737 
   5738   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
   5739                                   SourceLocation QuestionLoc);
   5740 
   5741   /// type checking for vector binary operators.
   5742   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
   5743                                SourceLocation Loc, bool IsCompAssign);
   5744   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
   5745                                       SourceLocation Loc, bool isRelational);
   5746 
   5747   /// type checking declaration initializers (C99 6.7.8)
   5748   bool CheckForConstantInitializer(Expr *e, QualType t);
   5749 
   5750   // type checking C++ declaration initializers (C++ [dcl.init]).
   5751 
   5752   /// ReferenceCompareResult - Expresses the result of comparing two
   5753   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
   5754   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
   5755   enum ReferenceCompareResult {
   5756     /// Ref_Incompatible - The two types are incompatible, so direct
   5757     /// reference binding is not possible.
   5758     Ref_Incompatible = 0,
   5759     /// Ref_Related - The two types are reference-related, which means
   5760     /// that their unqualified forms (T1 and T2) are either the same
   5761     /// or T1 is a base class of T2.
   5762     Ref_Related,
   5763     /// Ref_Compatible_With_Added_Qualification - The two types are
   5764     /// reference-compatible with added qualification, meaning that
   5765     /// they are reference-compatible and the qualifiers on T1 (cv1)
   5766     /// are greater than the qualifiers on T2 (cv2).
   5767     Ref_Compatible_With_Added_Qualification,
   5768     /// Ref_Compatible - The two types are reference-compatible and
   5769     /// have equivalent qualifiers (cv1 == cv2).
   5770     Ref_Compatible
   5771   };
   5772 
   5773   ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
   5774                                                       QualType T1, QualType T2,
   5775                                                       bool &DerivedToBase,
   5776                                                       bool &ObjCConversion,
   5777                                                 bool &ObjCLifetimeConversion);
   5778 
   5779   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
   5780                                  Expr *CastExpr, CastKind &CastKind,
   5781                                  ExprValueKind &VK, CXXCastPath &Path);
   5782 
   5783   // CheckVectorCast - check type constraints for vectors.
   5784   // Since vectors are an extension, there are no C standard reference for this.
   5785   // We allow casting between vectors and integer datatypes of the same size.
   5786   // returns true if the cast is invalid
   5787   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
   5788                        CastKind &Kind);
   5789 
   5790   // CheckExtVectorCast - check type constraints for extended vectors.
   5791   // Since vectors are an extension, there are no C standard reference for this.
   5792   // We allow casting between vectors and integer datatypes of the same size,
   5793   // or vectors and the element type of that vector.
   5794   // returns the cast expr
   5795   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
   5796                                 CastKind &Kind);
   5797 
   5798   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
   5799                                         SourceLocation LParenLoc,
   5800                                         Expr *CastExpr,
   5801                                         SourceLocation RParenLoc);
   5802 
   5803   enum ARCConversionResult { ACR_okay, ACR_unbridged };
   5804 
   5805   /// \brief Checks for invalid conversions and casts between
   5806   /// retainable pointers and other pointer kinds.
   5807   ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
   5808                                              QualType castType, Expr *&op,
   5809                                              CheckedConversionKind CCK);
   5810 
   5811   Expr *stripARCUnbridgedCast(Expr *e);
   5812   void diagnoseARCUnbridgedCast(Expr *e);
   5813 
   5814   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
   5815                                              QualType ExprType);
   5816 
   5817   /// checkRetainCycles - Check whether an Objective-C message send
   5818   /// might create an obvious retain cycle.
   5819   void checkRetainCycles(ObjCMessageExpr *msg);
   5820   void checkRetainCycles(Expr *receiver, Expr *argument);
   5821 
   5822   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
   5823   /// to weak/__unsafe_unretained type.
   5824   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
   5825 
   5826   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
   5827   /// to weak/__unsafe_unretained expression.
   5828   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
   5829 
   5830   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
   5831   /// \param Method - May be null.
   5832   /// \param [out] ReturnType - The return type of the send.
   5833   /// \return true iff there were any incompatible types.
   5834   bool CheckMessageArgumentTypes(QualType ReceiverType,
   5835                                  Expr **Args, unsigned NumArgs, Selector Sel,
   5836                                  ObjCMethodDecl *Method, bool isClassMessage,
   5837                                  bool isSuperMessage,
   5838                                  SourceLocation lbrac, SourceLocation rbrac,
   5839                                  QualType &ReturnType, ExprValueKind &VK);
   5840 
   5841   /// \brief Determine the result of a message send expression based on
   5842   /// the type of the receiver, the method expected to receive the message,
   5843   /// and the form of the message send.
   5844   QualType getMessageSendResultType(QualType ReceiverType,
   5845                                     ObjCMethodDecl *Method,
   5846                                     bool isClassMessage, bool isSuperMessage);
   5847 
   5848   /// \brief If the given expression involves a message send to a method
   5849   /// with a related result type, emit a note describing what happened.
   5850   void EmitRelatedResultTypeNote(const Expr *E);
   5851 
   5852   /// CheckBooleanCondition - Diagnose problems involving the use of
   5853   /// the given expression as a boolean condition (e.g. in an if
   5854   /// statement).  Also performs the standard function and array
   5855   /// decays, possibly changing the input variable.
   5856   ///
   5857   /// \param Loc - A location associated with the condition, e.g. the
   5858   /// 'if' keyword.
   5859   /// \return true iff there were any errors
   5860   ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
   5861 
   5862   ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
   5863                                    Expr *SubExpr);
   5864 
   5865   /// DiagnoseAssignmentAsCondition - Given that an expression is
   5866   /// being used as a boolean condition, warn if it's an assignment.
   5867   void DiagnoseAssignmentAsCondition(Expr *E);
   5868 
   5869   /// \brief Redundant parentheses over an equality comparison can indicate
   5870   /// that the user intended an assignment used as condition.
   5871   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
   5872 
   5873   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
   5874   ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
   5875 
   5876   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
   5877   /// the specified width and sign.  If an overflow occurs, detect it and emit
   5878   /// the specified diagnostic.
   5879   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
   5880                                           unsigned NewWidth, bool NewSign,
   5881                                           SourceLocation Loc, unsigned DiagID);
   5882 
   5883   /// Checks that the Objective-C declaration is declared in the global scope.
   5884   /// Emits an error and marks the declaration as invalid if it's not declared
   5885   /// in the global scope.
   5886   bool CheckObjCDeclScope(Decl *D);
   5887 
   5888   /// VerifyIntegerConstantExpression - verifies that an expression is an ICE,
   5889   /// and reports the appropriate diagnostics. Returns false on success.
   5890   /// Can optionally return the value of the expression.
   5891   bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0);
   5892 
   5893   /// VerifyBitField - verifies that a bit field expression is an ICE and has
   5894   /// the correct width, and that the field type is valid.
   5895   /// Returns false on success.
   5896   /// Can optionally return whether the bit-field is of width 0
   5897   bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
   5898                       QualType FieldTy, const Expr *BitWidth,
   5899                       bool *ZeroWidth = 0);
   5900 
   5901   enum CUDAFunctionTarget {
   5902     CFT_Device,
   5903     CFT_Global,
   5904     CFT_Host,
   5905     CFT_HostDevice
   5906   };
   5907 
   5908   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
   5909 
   5910   bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
   5911                        CUDAFunctionTarget CalleeTarget);
   5912 
   5913   bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
   5914     return CheckCUDATarget(IdentifyCUDATarget(Caller),
   5915                            IdentifyCUDATarget(Callee));
   5916   }
   5917 
   5918   /// \name Code completion
   5919   //@{
   5920   /// \brief Describes the context in which code completion occurs.
   5921   enum ParserCompletionContext {
   5922     /// \brief Code completion occurs at top-level or namespace context.
   5923     PCC_Namespace,
   5924     /// \brief Code completion occurs within a class, struct, or union.
   5925     PCC_Class,
   5926     /// \brief Code completion occurs within an Objective-C interface, protocol,
   5927     /// or category.
   5928     PCC_ObjCInterface,
   5929     /// \brief Code completion occurs within an Objective-C implementation or
   5930     /// category implementation
   5931     PCC_ObjCImplementation,
   5932     /// \brief Code completion occurs within the list of instance variables
   5933     /// in an Objective-C interface, protocol, category, or implementation.
   5934     PCC_ObjCInstanceVariableList,
   5935     /// \brief Code completion occurs following one or more template
   5936     /// headers.
   5937     PCC_Template,
   5938     /// \brief Code completion occurs following one or more template
   5939     /// headers within a class.
   5940     PCC_MemberTemplate,
   5941     /// \brief Code completion occurs within an expression.
   5942     PCC_Expression,
   5943     /// \brief Code completion occurs within a statement, which may
   5944     /// also be an expression or a declaration.
   5945     PCC_Statement,
   5946     /// \brief Code completion occurs at the beginning of the
   5947     /// initialization statement (or expression) in a for loop.
   5948     PCC_ForInit,
   5949     /// \brief Code completion occurs within the condition of an if,
   5950     /// while, switch, or for statement.
   5951     PCC_Condition,
   5952     /// \brief Code completion occurs within the body of a function on a
   5953     /// recovery path, where we do not have a specific handle on our position
   5954     /// in the grammar.
   5955     PCC_RecoveryInFunction,
   5956     /// \brief Code completion occurs where only a type is permitted.
   5957     PCC_Type,
   5958     /// \brief Code completion occurs in a parenthesized expression, which
   5959     /// might also be a type cast.
   5960     PCC_ParenthesizedExpression,
   5961     /// \brief Code completion occurs within a sequence of declaration
   5962     /// specifiers within a function, method, or block.
   5963     PCC_LocalDeclarationSpecifiers
   5964   };
   5965 
   5966   void CodeCompleteOrdinaryName(Scope *S,
   5967                                 ParserCompletionContext CompletionContext);
   5968   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
   5969                             bool AllowNonIdentifiers,
   5970                             bool AllowNestedNameSpecifiers);
   5971 
   5972   struct CodeCompleteExpressionData;
   5973   void CodeCompleteExpression(Scope *S,
   5974                               const CodeCompleteExpressionData &Data);
   5975   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
   5976                                        SourceLocation OpLoc,
   5977                                        bool IsArrow);
   5978   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
   5979   void CodeCompleteTag(Scope *S, unsigned TagSpec);
   5980   void CodeCompleteTypeQualifiers(DeclSpec &DS);
   5981   void CodeCompleteCase(Scope *S);
   5982   void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
   5983   void CodeCompleteInitializer(Scope *S, Decl *D);
   5984   void CodeCompleteReturn(Scope *S);
   5985   void CodeCompleteAfterIf(Scope *S);
   5986   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
   5987 
   5988   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
   5989                                bool EnteringContext);
   5990   void CodeCompleteUsing(Scope *S);
   5991   void CodeCompleteUsingDirective(Scope *S);
   5992   void CodeCompleteNamespaceDecl(Scope *S);
   5993   void CodeCompleteNamespaceAliasDecl(Scope *S);
   5994   void CodeCompleteOperatorName(Scope *S);
   5995   void CodeCompleteConstructorInitializer(Decl *Constructor,
   5996                                           CXXCtorInitializer** Initializers,
   5997                                           unsigned NumInitializers);
   5998 
   5999   void CodeCompleteObjCAtDirective(Scope *S);
   6000   void CodeCompleteObjCAtVisibility(Scope *S);
   6001   void CodeCompleteObjCAtStatement(Scope *S);
   6002   void CodeCompleteObjCAtExpression(Scope *S);
   6003   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
   6004   void CodeCompleteObjCPropertyGetter(Scope *S);
   6005   void CodeCompleteObjCPropertySetter(Scope *S);
   6006   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
   6007                                    bool IsParameter);
   6008   void CodeCompleteObjCMessageReceiver(Scope *S);
   6009   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
   6010                                     IdentifierInfo **SelIdents,
   6011                                     unsigned NumSelIdents,
   6012                                     bool AtArgumentExpression);
   6013   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
   6014                                     IdentifierInfo **SelIdents,
   6015                                     unsigned NumSelIdents,
   6016                                     bool AtArgumentExpression,
   6017                                     bool IsSuper = false);
   6018   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
   6019                                        IdentifierInfo **SelIdents,
   6020                                        unsigned NumSelIdents,
   6021                                        bool AtArgumentExpression,
   6022                                        ObjCInterfaceDecl *Super = 0);
   6023   void CodeCompleteObjCForCollection(Scope *S,
   6024                                      DeclGroupPtrTy IterationVar);
   6025   void CodeCompleteObjCSelector(Scope *S,
   6026                                 IdentifierInfo **SelIdents,
   6027                                 unsigned NumSelIdents);
   6028   void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
   6029                                           unsigned NumProtocols);
   6030   void CodeCompleteObjCProtocolDecl(Scope *S);
   6031   void CodeCompleteObjCInterfaceDecl(Scope *S);
   6032   void CodeCompleteObjCSuperclass(Scope *S,
   6033                                   IdentifierInfo *ClassName,
   6034                                   SourceLocation ClassNameLoc);
   6035   void CodeCompleteObjCImplementationDecl(Scope *S);
   6036   void CodeCompleteObjCInterfaceCategory(Scope *S,
   6037                                          IdentifierInfo *ClassName,
   6038                                          SourceLocation ClassNameLoc);
   6039   void CodeCompleteObjCImplementationCategory(Scope *S,
   6040                                               IdentifierInfo *ClassName,
   6041                                               SourceLocation ClassNameLoc);
   6042   void CodeCompleteObjCPropertyDefinition(Scope *S);
   6043   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
   6044                                               IdentifierInfo *PropertyName);
   6045   void CodeCompleteObjCMethodDecl(Scope *S,
   6046                                   bool IsInstanceMethod,
   6047                                   ParsedType ReturnType);
   6048   void CodeCompleteObjCMethodDeclSelector(Scope *S,
   6049                                           bool IsInstanceMethod,
   6050                                           bool AtParameterName,
   6051                                           ParsedType ReturnType,
   6052                                           IdentifierInfo **SelIdents,
   6053                                           unsigned NumSelIdents);
   6054   void CodeCompletePreprocessorDirective(bool InConditional);
   6055   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
   6056   void CodeCompletePreprocessorMacroName(bool IsDefinition);
   6057   void CodeCompletePreprocessorExpression();
   6058   void CodeCompletePreprocessorMacroArgument(Scope *S,
   6059                                              IdentifierInfo *Macro,
   6060                                              MacroInfo *MacroInfo,
   6061                                              unsigned Argument);
   6062   void CodeCompleteNaturalLanguage();
   6063   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
   6064                   SmallVectorImpl<CodeCompletionResult> &Results);
   6065   //@}
   6066 
   6067   //===--------------------------------------------------------------------===//
   6068   // Extra semantic analysis beyond the C type system
   6069 
   6070 public:
   6071   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
   6072                                                 unsigned ByteNo) const;
   6073 
   6074 private:
   6075   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
   6076                         bool isSubscript=false, bool AllowOnePastEnd=true);
   6077   void CheckArrayAccess(const Expr *E);
   6078   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
   6079   bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
   6080 
   6081   bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
   6082   bool CheckObjCString(Expr *Arg);
   6083 
   6084   ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   6085   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   6086 
   6087   bool SemaBuiltinVAStart(CallExpr *TheCall);
   6088   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
   6089   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
   6090 
   6091 public:
   6092   // Used by C++ template instantiation.
   6093   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
   6094 
   6095 private:
   6096   bool SemaBuiltinPrefetch(CallExpr *TheCall);
   6097   bool SemaBuiltinObjectSize(CallExpr *TheCall);
   6098   bool SemaBuiltinLongjmp(CallExpr *TheCall);
   6099   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
   6100   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
   6101                                      AtomicExpr::AtomicOp Op);
   6102   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
   6103                               llvm::APSInt &Result);
   6104 
   6105   bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
   6106                               bool HasVAListArg, unsigned format_idx,
   6107                               unsigned firstDataArg, bool isPrintf);
   6108 
   6109   void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
   6110                          const CallExpr *TheCall, bool HasVAListArg,
   6111                          unsigned format_idx, unsigned firstDataArg,
   6112                          bool isPrintf);
   6113 
   6114   void CheckNonNullArguments(const NonNullAttr *NonNull,
   6115                              const Expr * const *ExprArgs,
   6116                              SourceLocation CallSiteLoc);
   6117 
   6118   void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
   6119                                  unsigned format_idx, unsigned firstDataArg,
   6120                                  bool isPrintf);
   6121 
   6122   /// \brief Enumeration used to describe which of the memory setting or copying
   6123   /// functions is being checked by \c CheckMemaccessArguments().
   6124   enum CheckedMemoryFunction {
   6125     CMF_Memset,
   6126     CMF_Memcpy,
   6127     CMF_Memmove,
   6128     CMF_Memcmp,
   6129     CMF_Strncpy,
   6130     CMF_Strncmp,
   6131     CMF_Strncasecmp,
   6132     CMF_Strncat,
   6133     CMF_Strndup
   6134   };
   6135 
   6136   void CheckMemaccessArguments(const CallExpr *Call, CheckedMemoryFunction CMF,
   6137                                IdentifierInfo *FnName);
   6138 
   6139   void CheckStrlcpycatArguments(const CallExpr *Call,
   6140                                 IdentifierInfo *FnName);
   6141 
   6142   void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
   6143                             SourceLocation ReturnLoc);
   6144   void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
   6145   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
   6146 
   6147   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
   6148                                    Expr *Init);
   6149 
   6150   /// \brief The parser's current scope.
   6151   ///
   6152   /// The parser maintains this state here.
   6153   Scope *CurScope;
   6154 
   6155 protected:
   6156   friend class Parser;
   6157   friend class InitializationSequence;
   6158   friend class ASTReader;
   6159   friend class ASTWriter;
   6160 
   6161 public:
   6162   /// \brief Retrieve the parser's current scope.
   6163   ///
   6164   /// This routine must only be used when it is certain that semantic analysis
   6165   /// and the parser are in precisely the same context, which is not the case
   6166   /// when, e.g., we are performing any kind of template instantiation.
   6167   /// Therefore, the only safe places to use this scope are in the parser
   6168   /// itself and in routines directly invoked from the parser and *never* from
   6169   /// template substitution or instantiation.
   6170   Scope *getCurScope() const { return CurScope; }
   6171 
   6172   Decl *getObjCDeclContext() const;
   6173 
   6174   DeclContext *getCurLexicalContext() const {
   6175     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
   6176   }
   6177 
   6178   AvailabilityResult getCurContextAvailability() const;
   6179 };
   6180 
   6181 /// \brief RAII object that enters a new expression evaluation context.
   6182 class EnterExpressionEvaluationContext {
   6183   Sema &Actions;
   6184 
   6185 public:
   6186   EnterExpressionEvaluationContext(Sema &Actions,
   6187                                    Sema::ExpressionEvaluationContext NewContext)
   6188     : Actions(Actions) {
   6189     Actions.PushExpressionEvaluationContext(NewContext);
   6190   }
   6191 
   6192   ~EnterExpressionEvaluationContext() {
   6193     Actions.PopExpressionEvaluationContext();
   6194   }
   6195 };
   6196 
   6197 }  // end namespace clang
   6198 
   6199 #endif
   6200