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