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