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