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