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