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