Sema.h revision f4bbbf0aaf741cc7d014e2cf059670a6756f8cbd
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
2005  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2006                              SourceLocation TryLoc,
2007                              Stmt *TryBlock,
2008                              Stmt *Handler);
2009
2010  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2011                                 Expr *FilterExpr,
2012                                 Stmt *Block);
2013
2014  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2015                                  Stmt *Block);
2016
2017  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2018
2019  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2020
2021  /// \brief If it's a file scoped decl that must warn if not used, keep track
2022  /// of it.
2023  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2024
2025  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2026  /// whose result is unused, warn.
2027  void DiagnoseUnusedExprResult(const Stmt *S);
2028  void DiagnoseUnusedDecl(const NamedDecl *ND);
2029
2030  ParsingDeclState PushParsingDeclaration() {
2031    return DelayedDiagnostics.pushParsingDecl();
2032  }
2033  void PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
2034    DelayedDiagnostics::popParsingDecl(*this, state, decl);
2035  }
2036
2037  typedef ProcessingContextState ParsingClassState;
2038  ParsingClassState PushParsingClass() {
2039    return DelayedDiagnostics.pushContext();
2040  }
2041  void PopParsingClass(ParsingClassState state) {
2042    DelayedDiagnostics.popContext(state);
2043  }
2044
2045  void EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
2046                              SourceLocation Loc,
2047                              const ObjCInterfaceDecl *UnknownObjCClass=0);
2048
2049  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2050
2051  //===--------------------------------------------------------------------===//
2052  // Expression Parsing Callbacks: SemaExpr.cpp.
2053
2054  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2055                         const ObjCInterfaceDecl *UnknownObjCClass=0);
2056  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2057  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2058                                        ObjCMethodDecl *Getter,
2059                                        SourceLocation Loc);
2060  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2061                             Expr **Args, unsigned NumArgs);
2062
2063  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext);
2064
2065  void PopExpressionEvaluationContext();
2066
2067  void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
2068  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
2069  void MarkDeclarationsReferencedInExpr(Expr *E);
2070
2071  /// \brief Conditionally issue a diagnostic based on the current
2072  /// evaluation context.
2073  ///
2074  /// \param stmt - If stmt is non-null, delay reporting the diagnostic until
2075  ///  the function body is parsed, and then do a basic reachability analysis to
2076  ///  determine if the statement is reachable.  If it is unreachable, the
2077  ///  diagnostic will not be emitted.
2078  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
2079                           const PartialDiagnostic &PD);
2080
2081  // Primary Expressions.
2082  SourceRange getExprRange(Expr *E) const;
2083
2084  ObjCIvarDecl *SynthesizeProvisionalIvar(LookupResult &Lookup,
2085                                          IdentifierInfo *II,
2086                                          SourceLocation NameLoc);
2087
2088  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Name,
2089                               bool HasTrailingLParen, bool IsAddressOfOperand);
2090
2091  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2092                           CorrectTypoContext CTC = CTC_Unknown);
2093
2094  ExprResult LookupInObjCMethod(LookupResult &R, Scope *S, IdentifierInfo *II,
2095                                bool AllowBuiltinCreation=false);
2096
2097  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
2098                                        const DeclarationNameInfo &NameInfo,
2099                                        bool isAddressOfOperand,
2100                                const TemplateArgumentListInfo *TemplateArgs);
2101
2102  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2103                              ExprValueKind VK,
2104                              SourceLocation Loc,
2105                              const CXXScopeSpec *SS = 0);
2106  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2107                              ExprValueKind VK,
2108                              const DeclarationNameInfo &NameInfo,
2109                              const CXXScopeSpec *SS = 0);
2110  ExprResult
2111  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
2112                                           SourceLocation nameLoc,
2113                                           IndirectFieldDecl *indirectField,
2114                                           Expr *baseObjectExpr = 0,
2115                                      SourceLocation opLoc = SourceLocation());
2116  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2117                                             LookupResult &R,
2118                                const TemplateArgumentListInfo *TemplateArgs);
2119  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2120                                     LookupResult &R,
2121                                const TemplateArgumentListInfo *TemplateArgs,
2122                                     bool IsDefiniteInstance);
2123  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
2124                                  const LookupResult &R,
2125                                  bool HasTrailingLParen);
2126
2127  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2128                                         const DeclarationNameInfo &NameInfo);
2129  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
2130                                const DeclarationNameInfo &NameInfo,
2131                                const TemplateArgumentListInfo *TemplateArgs);
2132
2133  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2134                                      LookupResult &R,
2135                                      bool ADL);
2136  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2137                                      const DeclarationNameInfo &NameInfo,
2138                                      NamedDecl *D);
2139
2140  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
2141  ExprResult ActOnNumericConstant(const Token &);
2142  ExprResult ActOnCharacterConstant(const Token &);
2143  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *Val);
2144  ExprResult ActOnParenOrParenListExpr(SourceLocation L,
2145                                       SourceLocation R,
2146                                       MultiExprArg Val,
2147                                       ParsedType TypeOfCast = ParsedType());
2148
2149  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2150  /// fragments (e.g. "foo" "bar" L"baz").
2151  ExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks);
2152
2153  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
2154                                       SourceLocation DefaultLoc,
2155                                       SourceLocation RParenLoc,
2156                                       Expr *ControllingExpr,
2157                                       MultiTypeArg Types,
2158                                       MultiExprArg Exprs);
2159  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
2160                                        SourceLocation DefaultLoc,
2161                                        SourceLocation RParenLoc,
2162                                        Expr *ControllingExpr,
2163                                        TypeSourceInfo **Types,
2164                                        Expr **Exprs,
2165                                        unsigned NumAssocs);
2166
2167  // Binary/Unary Operators.  'Tok' is the token for the operator.
2168  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
2169                                  Expr *InputArg);
2170  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
2171                          UnaryOperatorKind Opc, Expr *input);
2172  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
2173                          tok::TokenKind Op, Expr *Input);
2174
2175  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *T,
2176                                            SourceLocation OpLoc,
2177                                            UnaryExprOrTypeTrait ExprKind,
2178                                            SourceRange R);
2179  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2180                                            UnaryExprOrTypeTrait ExprKind,
2181                                            SourceRange R);
2182  ExprResult
2183    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2184                                  UnaryExprOrTypeTrait ExprKind,
2185                                  bool isType, void *TyOrEx,
2186                                  const SourceRange &ArgRange);
2187
2188  ExprResult CheckPlaceholderExpr(Expr *E);
2189  bool CheckVecStepExpr(Expr *E, SourceLocation OpLoc, SourceRange R);
2190
2191  bool CheckUnaryExprOrTypeTraitOperand(QualType type, SourceLocation OpLoc,
2192                                        SourceRange R,
2193                                        UnaryExprOrTypeTrait ExprKind);
2194  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
2195                                          SourceLocation OpLoc,
2196                                          IdentifierInfo &Name,
2197                                          SourceLocation NameLoc,
2198                                          SourceLocation RParenLoc);
2199  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2200                                 tok::TokenKind Kind, Expr *Input);
2201
2202  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2203                                     Expr *Idx, SourceLocation RLoc);
2204  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2205                                             Expr *Idx, SourceLocation RLoc);
2206
2207  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2208                                      SourceLocation OpLoc, bool IsArrow,
2209                                      CXXScopeSpec &SS,
2210                                      NamedDecl *FirstQualifierInScope,
2211                                const DeclarationNameInfo &NameInfo,
2212                                const TemplateArgumentListInfo *TemplateArgs);
2213
2214  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2215                                      SourceLocation OpLoc, bool IsArrow,
2216                                      const CXXScopeSpec &SS,
2217                                      NamedDecl *FirstQualifierInScope,
2218                                      LookupResult &R,
2219                                 const TemplateArgumentListInfo *TemplateArgs,
2220                                      bool SuppressQualifierCheck = false);
2221
2222  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
2223                              bool &IsArrow, SourceLocation OpLoc,
2224                              CXXScopeSpec &SS,
2225                              Decl *ObjCImpDecl,
2226                              bool HasTemplateArgs);
2227
2228  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
2229                                     const CXXScopeSpec &SS,
2230                                     const LookupResult &R);
2231
2232  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
2233                                      bool IsArrow, SourceLocation OpLoc,
2234                                      const CXXScopeSpec &SS,
2235                                      NamedDecl *FirstQualifierInScope,
2236                               const DeclarationNameInfo &NameInfo,
2237                               const TemplateArgumentListInfo *TemplateArgs);
2238
2239  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
2240                                   SourceLocation OpLoc,
2241                                   tok::TokenKind OpKind,
2242                                   CXXScopeSpec &SS,
2243                                   UnqualifiedId &Member,
2244                                   Decl *ObjCImpDecl,
2245                                   bool HasTrailingLParen);
2246
2247  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
2248  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2249                               FunctionDecl *FDecl,
2250                               const FunctionProtoType *Proto,
2251                               Expr **Args, unsigned NumArgs,
2252                               SourceLocation RParenLoc);
2253
2254  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2255  /// This provides the location of the left/right parens and a list of comma
2256  /// locations.
2257  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
2258                           MultiExprArg Args, SourceLocation RParenLoc,
2259                           Expr *ExecConfig = 0);
2260  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
2261                                   SourceLocation LParenLoc,
2262                                   Expr **Args, unsigned NumArgs,
2263                                   SourceLocation RParenLoc,
2264                                   Expr *ExecConfig = 0);
2265
2266  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
2267                                MultiExprArg ExecConfig, SourceLocation GGGLoc);
2268
2269  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
2270                           ParsedType Ty, SourceLocation RParenLoc,
2271                           Expr *Op);
2272  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
2273                                 TypeSourceInfo *Ty,
2274                                 SourceLocation RParenLoc,
2275                                 Expr *Op);
2276
2277  bool TypeIsVectorType(ParsedType Ty) {
2278    return GetTypeFromParser(Ty)->isVectorType();
2279  }
2280
2281  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
2282  ExprResult ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
2283                                      SourceLocation RParenLoc, Expr *E,
2284                                      TypeSourceInfo *TInfo);
2285
2286  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
2287                                  ParsedType Ty,
2288                                  SourceLocation RParenLoc,
2289                                  Expr *Op);
2290
2291  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
2292                                      TypeSourceInfo *TInfo,
2293                                      SourceLocation RParenLoc,
2294                                      Expr *InitExpr);
2295
2296  ExprResult ActOnInitList(SourceLocation LParenLoc,
2297                           MultiExprArg InitList,
2298                           SourceLocation RParenLoc);
2299
2300  ExprResult ActOnDesignatedInitializer(Designation &Desig,
2301                                        SourceLocation Loc,
2302                                        bool GNUSyntax,
2303                                        ExprResult Init);
2304
2305  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
2306                        tok::TokenKind Kind, Expr *LHS, Expr *RHS);
2307  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
2308                        BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2309  ExprResult CreateBuiltinBinOp(SourceLocation TokLoc,
2310                                BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2311
2312  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2313  /// in the case of a the GNU conditional expr extension.
2314  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
2315                                SourceLocation ColonLoc,
2316                                Expr *Cond, Expr *LHS, Expr *RHS);
2317
2318  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2319  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
2320                            LabelDecl *LD);
2321
2322  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
2323                           SourceLocation RPLoc); // "({..})"
2324
2325  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2326  struct OffsetOfComponent {
2327    SourceLocation LocStart, LocEnd;
2328    bool isBrackets;  // true if [expr], false if .ident
2329    union {
2330      IdentifierInfo *IdentInfo;
2331      ExprTy *E;
2332    } U;
2333  };
2334
2335  /// __builtin_offsetof(type, a.b[123][456].c)
2336  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
2337                                  TypeSourceInfo *TInfo,
2338                                  OffsetOfComponent *CompPtr,
2339                                  unsigned NumComponents,
2340                                  SourceLocation RParenLoc);
2341  ExprResult ActOnBuiltinOffsetOf(Scope *S,
2342                                  SourceLocation BuiltinLoc,
2343                                  SourceLocation TypeLoc,
2344                                  ParsedType Arg1,
2345                                  OffsetOfComponent *CompPtr,
2346                                  unsigned NumComponents,
2347                                  SourceLocation RParenLoc);
2348
2349  // __builtin_choose_expr(constExpr, expr1, expr2)
2350  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
2351                             Expr *cond, Expr *expr1,
2352                             Expr *expr2, SourceLocation RPLoc);
2353
2354  // __builtin_va_arg(expr, type)
2355  ExprResult ActOnVAArg(SourceLocation BuiltinLoc,
2356                        Expr *expr, ParsedType type,
2357                        SourceLocation RPLoc);
2358  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc,
2359                            Expr *expr, TypeSourceInfo *TInfo,
2360                            SourceLocation RPLoc);
2361
2362  // __null
2363  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
2364
2365  bool CheckCaseExpression(Expr *expr);
2366
2367  //===------------------------- "Block" Extension ------------------------===//
2368
2369  /// ActOnBlockStart - This callback is invoked when a block literal is
2370  /// started.
2371  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
2372
2373  /// ActOnBlockArguments - This callback allows processing of block arguments.
2374  /// If there are no arguments, this is still invoked.
2375  void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
2376
2377  /// ActOnBlockError - If there is an error parsing a block, this callback
2378  /// is invoked to pop the information about the block from the action impl.
2379  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
2380
2381  /// ActOnBlockStmtExpr - This is called when the body of a block statement
2382  /// literal was successfully completed.  ^(int x){...}
2383  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc,
2384                                        Stmt *Body, Scope *CurScope);
2385
2386  //===---------------------------- C++ Features --------------------------===//
2387
2388  // Act on C++ namespaces
2389  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
2390                               SourceLocation NamespaceLoc,
2391                               SourceLocation IdentLoc,
2392                               IdentifierInfo *Ident,
2393                               SourceLocation LBrace,
2394                               AttributeList *AttrList);
2395  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
2396
2397  NamespaceDecl *getStdNamespace() const;
2398  NamespaceDecl *getOrCreateStdNamespace();
2399
2400  CXXRecordDecl *getStdBadAlloc() const;
2401
2402  Decl *ActOnUsingDirective(Scope *CurScope,
2403                            SourceLocation UsingLoc,
2404                            SourceLocation NamespcLoc,
2405                            CXXScopeSpec &SS,
2406                            SourceLocation IdentLoc,
2407                            IdentifierInfo *NamespcName,
2408                            AttributeList *AttrList);
2409
2410  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
2411
2412  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
2413                               SourceLocation NamespaceLoc,
2414                               SourceLocation AliasLoc,
2415                               IdentifierInfo *Alias,
2416                               CXXScopeSpec &SS,
2417                               SourceLocation IdentLoc,
2418                               IdentifierInfo *Ident);
2419
2420  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
2421  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
2422                            const LookupResult &PreviousDecls);
2423  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
2424                                        NamedDecl *Target);
2425
2426  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
2427                                   bool isTypeName,
2428                                   const CXXScopeSpec &SS,
2429                                   SourceLocation NameLoc,
2430                                   const LookupResult &Previous);
2431  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
2432                               const CXXScopeSpec &SS,
2433                               SourceLocation NameLoc);
2434
2435  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2436                                   SourceLocation UsingLoc,
2437                                   CXXScopeSpec &SS,
2438                                   const DeclarationNameInfo &NameInfo,
2439                                   AttributeList *AttrList,
2440                                   bool IsInstantiation,
2441                                   bool IsTypeName,
2442                                   SourceLocation TypenameLoc);
2443
2444  bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
2445
2446  Decl *ActOnUsingDeclaration(Scope *CurScope,
2447                              AccessSpecifier AS,
2448                              bool HasUsingKeyword,
2449                              SourceLocation UsingLoc,
2450                              CXXScopeSpec &SS,
2451                              UnqualifiedId &Name,
2452                              AttributeList *AttrList,
2453                              bool IsTypeName,
2454                              SourceLocation TypenameLoc);
2455  Decl *ActOnAliasDeclaration(Scope *CurScope,
2456                              AccessSpecifier AS,
2457                              SourceLocation UsingLoc,
2458                              UnqualifiedId &Name,
2459                              TypeResult Type);
2460
2461  /// AddCXXDirectInitializerToDecl - This action is called immediately after
2462  /// ActOnDeclarator, when a C++ direct initializer is present.
2463  /// e.g: "int x(1);"
2464  void AddCXXDirectInitializerToDecl(Decl *Dcl,
2465                                     SourceLocation LParenLoc,
2466                                     MultiExprArg Exprs,
2467                                     SourceLocation RParenLoc,
2468                                     bool TypeMayContainAuto);
2469
2470  /// InitializeVarWithConstructor - Creates an CXXConstructExpr
2471  /// and sets it as the initializer for the the passed in VarDecl.
2472  bool InitializeVarWithConstructor(VarDecl *VD,
2473                                    CXXConstructorDecl *Constructor,
2474                                    MultiExprArg Exprs);
2475
2476  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
2477  /// including handling of its default argument expressions.
2478  ///
2479  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
2480  ExprResult
2481  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2482                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
2483                        bool RequiresZeroInit, unsigned ConstructKind,
2484                        SourceRange ParenRange);
2485
2486  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
2487  // the constructor can be elidable?
2488  ExprResult
2489  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2490                        CXXConstructorDecl *Constructor, bool Elidable,
2491                        MultiExprArg Exprs, bool RequiresZeroInit,
2492                        unsigned ConstructKind,
2493                        SourceRange ParenRange);
2494
2495  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
2496  /// the default expr if needed.
2497  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2498                                    FunctionDecl *FD,
2499                                    ParmVarDecl *Param);
2500
2501  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
2502  /// constructed variable.
2503  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
2504
2505  /// \brief Declare the implicit default constructor for the given class.
2506  ///
2507  /// \param ClassDecl The class declaration into which the implicit
2508  /// default constructor will be added.
2509  ///
2510  /// \returns The implicitly-declared default constructor.
2511  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
2512                                                     CXXRecordDecl *ClassDecl);
2513
2514  /// DefineImplicitDefaultConstructor - Checks for feasibility of
2515  /// defining this constructor as the default constructor.
2516  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2517                                        CXXConstructorDecl *Constructor);
2518
2519  /// \brief Declare the implicit destructor for the given class.
2520  ///
2521  /// \param ClassDecl The class declaration into which the implicit
2522  /// destructor will be added.
2523  ///
2524  /// \returns The implicitly-declared destructor.
2525  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
2526
2527  /// DefineImplicitDestructor - Checks for feasibility of
2528  /// defining this destructor as the default destructor.
2529  void DefineImplicitDestructor(SourceLocation CurrentLocation,
2530                                CXXDestructorDecl *Destructor);
2531
2532  /// \brief Declare all inherited constructors for the given class.
2533  ///
2534  /// \param ClassDecl The class declaration into which the inherited
2535  /// constructors will be added.
2536  void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
2537
2538  /// \brief Declare the implicit copy constructor for the given class.
2539  ///
2540  /// \param S The scope of the class, which may be NULL if this is a
2541  /// template instantiation.
2542  ///
2543  /// \param ClassDecl The class declaration into which the implicit
2544  /// copy constructor will be added.
2545  ///
2546  /// \returns The implicitly-declared copy constructor.
2547  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
2548
2549  /// DefineImplicitCopyConstructor - Checks for feasibility of
2550  /// defining this constructor as the copy constructor.
2551  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2552                                     CXXConstructorDecl *Constructor,
2553                                     unsigned TypeQuals);
2554
2555  /// \brief Declare the implicit copy assignment operator for the given class.
2556  ///
2557  /// \param S The scope of the class, which may be NULL if this is a
2558  /// template instantiation.
2559  ///
2560  /// \param ClassDecl The class declaration into which the implicit
2561  /// copy-assignment operator will be added.
2562  ///
2563  /// \returns The implicitly-declared copy assignment operator.
2564  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
2565
2566  /// \brief Defined an implicitly-declared copy assignment operator.
2567  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
2568                                    CXXMethodDecl *MethodDecl);
2569
2570  /// \brief Force the declaration of any implicitly-declared members of this
2571  /// class.
2572  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
2573
2574  /// MaybeBindToTemporary - If the passed in expression has a record type with
2575  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
2576  /// it simply returns the passed in expression.
2577  ExprResult MaybeBindToTemporary(Expr *E);
2578
2579  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
2580                               MultiExprArg ArgsPtr,
2581                               SourceLocation Loc,
2582                               ASTOwningVector<Expr*> &ConvertedArgs);
2583
2584  ParsedType getDestructorName(SourceLocation TildeLoc,
2585                               IdentifierInfo &II, SourceLocation NameLoc,
2586                               Scope *S, CXXScopeSpec &SS,
2587                               ParsedType ObjectType,
2588                               bool EnteringContext);
2589
2590  // Checks that reinterpret casts don't have undefined behavior.
2591  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2592                                      bool IsDereference, SourceRange Range);
2593
2594  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
2595  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
2596                               tok::TokenKind Kind,
2597                               SourceLocation LAngleBracketLoc,
2598                               ParsedType Ty,
2599                               SourceLocation RAngleBracketLoc,
2600                               SourceLocation LParenLoc,
2601                               Expr *E,
2602                               SourceLocation RParenLoc);
2603
2604  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
2605                               tok::TokenKind Kind,
2606                               TypeSourceInfo *Ty,
2607                               Expr *E,
2608                               SourceRange AngleBrackets,
2609                               SourceRange Parens);
2610
2611  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2612                            SourceLocation TypeidLoc,
2613                            TypeSourceInfo *Operand,
2614                            SourceLocation RParenLoc);
2615  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2616                            SourceLocation TypeidLoc,
2617                            Expr *Operand,
2618                            SourceLocation RParenLoc);
2619
2620  /// ActOnCXXTypeid - Parse typeid( something ).
2621  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
2622                            SourceLocation LParenLoc, bool isType,
2623                            void *TyOrExpr,
2624                            SourceLocation RParenLoc);
2625
2626  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2627                            SourceLocation TypeidLoc,
2628                            TypeSourceInfo *Operand,
2629                            SourceLocation RParenLoc);
2630  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2631                            SourceLocation TypeidLoc,
2632                            Expr *Operand,
2633                            SourceLocation RParenLoc);
2634
2635  /// ActOnCXXUuidof - Parse __uuidof( something ).
2636  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
2637                            SourceLocation LParenLoc, bool isType,
2638                            void *TyOrExpr,
2639                            SourceLocation RParenLoc);
2640
2641
2642  //// ActOnCXXThis -  Parse 'this' pointer.
2643  ExprResult ActOnCXXThis(SourceLocation loc);
2644
2645  /// tryCaptureCXXThis - Try to capture a 'this' pointer.  Returns a
2646  /// pointer to an instance method whose 'this' pointer is
2647  /// capturable, or null if this is not possible.
2648  CXXMethodDecl *tryCaptureCXXThis();
2649
2650  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
2651  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
2652
2653  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
2654  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
2655
2656  //// ActOnCXXThrow -  Parse throw expressions.
2657  ExprResult ActOnCXXThrow(SourceLocation OpLoc, Expr *expr);
2658  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E);
2659
2660  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
2661  /// Can be interpreted either as function-style casting ("int(x)")
2662  /// or class type construction ("ClassType(x,y,z)")
2663  /// or creation of a value-initialized type ("int()").
2664  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
2665                                       SourceLocation LParenLoc,
2666                                       MultiExprArg Exprs,
2667                                       SourceLocation RParenLoc);
2668
2669  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
2670                                       SourceLocation LParenLoc,
2671                                       MultiExprArg Exprs,
2672                                       SourceLocation RParenLoc);
2673
2674  /// ActOnCXXNew - Parsed a C++ 'new' expression.
2675  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2676                         SourceLocation PlacementLParen,
2677                         MultiExprArg PlacementArgs,
2678                         SourceLocation PlacementRParen,
2679                         SourceRange TypeIdParens, Declarator &D,
2680                         SourceLocation ConstructorLParen,
2681                         MultiExprArg ConstructorArgs,
2682                         SourceLocation ConstructorRParen);
2683  ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
2684                         SourceLocation PlacementLParen,
2685                         MultiExprArg PlacementArgs,
2686                         SourceLocation PlacementRParen,
2687                         SourceRange TypeIdParens,
2688                         QualType AllocType,
2689                         TypeSourceInfo *AllocTypeInfo,
2690                         Expr *ArraySize,
2691                         SourceLocation ConstructorLParen,
2692                         MultiExprArg ConstructorArgs,
2693                         SourceLocation ConstructorRParen,
2694                         bool TypeMayContainAuto = true);
2695
2696  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2697                          SourceRange R);
2698  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2699                               bool UseGlobal, QualType AllocType, bool IsArray,
2700                               Expr **PlaceArgs, unsigned NumPlaceArgs,
2701                               FunctionDecl *&OperatorNew,
2702                               FunctionDecl *&OperatorDelete);
2703  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
2704                              DeclarationName Name, Expr** Args,
2705                              unsigned NumArgs, DeclContext *Ctx,
2706                              bool AllowMissing, FunctionDecl *&Operator);
2707  void DeclareGlobalNewDelete();
2708  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
2709                                       QualType Argument,
2710                                       bool addMallocAttr = false);
2711
2712  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2713                                DeclarationName Name, FunctionDecl* &Operator);
2714
2715  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
2716  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
2717                            bool UseGlobal, bool ArrayForm,
2718                            Expr *Operand);
2719
2720  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
2721  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
2722                                    SourceLocation StmtLoc,
2723                                    bool ConvertToBoolean);
2724
2725  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
2726                               Expr *Operand, SourceLocation RParen);
2727  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
2728                                  SourceLocation RParen);
2729
2730  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
2731  /// pseudo-functions.
2732  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
2733                                 SourceLocation KWLoc,
2734                                 ParsedType Ty,
2735                                 SourceLocation RParen);
2736
2737  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
2738                                 SourceLocation KWLoc,
2739                                 TypeSourceInfo *T,
2740                                 SourceLocation RParen);
2741
2742  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
2743  /// pseudo-functions.
2744  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
2745                                  SourceLocation KWLoc,
2746                                  ParsedType LhsTy,
2747                                  ParsedType RhsTy,
2748                                  SourceLocation RParen);
2749
2750  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2751                                  SourceLocation KWLoc,
2752                                  TypeSourceInfo *LhsT,
2753                                  TypeSourceInfo *RhsT,
2754                                  SourceLocation RParen);
2755
2756  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
2757  /// pseudo-functions.
2758  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2759                                 SourceLocation KWLoc,
2760                                 ParsedType LhsTy,
2761                                 Expr *DimExpr,
2762                                 SourceLocation RParen);
2763
2764  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
2765                                 SourceLocation KWLoc,
2766                                 TypeSourceInfo *TSInfo,
2767                                 Expr *DimExpr,
2768                                 SourceLocation RParen);
2769
2770  /// ActOnExpressionTrait - Parsed one of the unary type trait support
2771  /// pseudo-functions.
2772  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
2773                                  SourceLocation KWLoc,
2774                                  Expr *Queried,
2775                                  SourceLocation RParen);
2776
2777  ExprResult BuildExpressionTrait(ExpressionTrait OET,
2778                                  SourceLocation KWLoc,
2779                                  Expr *Queried,
2780                                  SourceLocation RParen);
2781
2782  ExprResult ActOnStartCXXMemberReference(Scope *S,
2783                                          Expr *Base,
2784                                          SourceLocation OpLoc,
2785                                          tok::TokenKind OpKind,
2786                                          ParsedType &ObjectType,
2787                                          bool &MayBePseudoDestructor);
2788
2789  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
2790
2791  ExprResult BuildPseudoDestructorExpr(Expr *Base,
2792                                       SourceLocation OpLoc,
2793                                       tok::TokenKind OpKind,
2794                                       const CXXScopeSpec &SS,
2795                                       TypeSourceInfo *ScopeType,
2796                                       SourceLocation CCLoc,
2797                                       SourceLocation TildeLoc,
2798                                     PseudoDestructorTypeStorage DestroyedType,
2799                                       bool HasTrailingLParen);
2800
2801  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
2802                                       SourceLocation OpLoc,
2803                                       tok::TokenKind OpKind,
2804                                       CXXScopeSpec &SS,
2805                                       UnqualifiedId &FirstTypeName,
2806                                       SourceLocation CCLoc,
2807                                       SourceLocation TildeLoc,
2808                                       UnqualifiedId &SecondTypeName,
2809                                       bool HasTrailingLParen);
2810
2811  /// MaybeCreateExprWithCleanups - If the current full-expression
2812  /// requires any cleanups, surround it with a ExprWithCleanups node.
2813  /// Otherwise, just returns the passed-in expression.
2814  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
2815  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
2816  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
2817
2818  ExprResult ActOnFinishFullExpr(Expr *Expr);
2819  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
2820
2821  // Marks SS invalid if it represents an incomplete type.
2822  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
2823
2824  DeclContext *computeDeclContext(QualType T);
2825  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
2826                                  bool EnteringContext = false);
2827  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
2828  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
2829  bool isUnknownSpecialization(const CXXScopeSpec &SS);
2830
2831  /// \brief The parser has parsed a global nested-name-specifier '::'.
2832  ///
2833  /// \param S The scope in which this nested-name-specifier occurs.
2834  ///
2835  /// \param CCLoc The location of the '::'.
2836  ///
2837  /// \param SS The nested-name-specifier, which will be updated in-place
2838  /// to reflect the parsed nested-name-specifier.
2839  ///
2840  /// \returns true if an error occurred, false otherwise.
2841  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
2842                                    CXXScopeSpec &SS);
2843
2844  bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
2845  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
2846
2847  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
2848                                    SourceLocation IdLoc,
2849                                    IdentifierInfo &II,
2850                                    ParsedType ObjectType);
2851
2852  bool BuildCXXNestedNameSpecifier(Scope *S,
2853                                   IdentifierInfo &Identifier,
2854                                   SourceLocation IdentifierLoc,
2855                                   SourceLocation CCLoc,
2856                                   QualType ObjectType,
2857                                   bool EnteringContext,
2858                                   CXXScopeSpec &SS,
2859                                   NamedDecl *ScopeLookupResult,
2860                                   bool ErrorRecoveryLookup);
2861
2862  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
2863  ///
2864  /// \param S The scope in which this nested-name-specifier occurs.
2865  ///
2866  /// \param Identifier The identifier preceding the '::'.
2867  ///
2868  /// \param IdentifierLoc The location of the identifier.
2869  ///
2870  /// \param CCLoc The location of the '::'.
2871  ///
2872  /// \param ObjectType The type of the object, if we're parsing
2873  /// nested-name-specifier in a member access expression.
2874  ///
2875  /// \param EnteringContext Whether we're entering the context nominated by
2876  /// this nested-name-specifier.
2877  ///
2878  /// \param SS The nested-name-specifier, which is both an input
2879  /// parameter (the nested-name-specifier before this type) and an
2880  /// output parameter (containing the full nested-name-specifier,
2881  /// including this new type).
2882  ///
2883  /// \returns true if an error occurred, false otherwise.
2884  bool ActOnCXXNestedNameSpecifier(Scope *S,
2885                                   IdentifierInfo &Identifier,
2886                                   SourceLocation IdentifierLoc,
2887                                   SourceLocation CCLoc,
2888                                   ParsedType ObjectType,
2889                                   bool EnteringContext,
2890                                   CXXScopeSpec &SS);
2891
2892  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
2893                                 IdentifierInfo &Identifier,
2894                                 SourceLocation IdentifierLoc,
2895                                 SourceLocation ColonLoc,
2896                                 ParsedType ObjectType,
2897                                 bool EnteringContext);
2898
2899  /// \brief The parser has parsed a nested-name-specifier
2900  /// 'template[opt] template-name < template-args >::'.
2901  ///
2902  /// \param S The scope in which this nested-name-specifier occurs.
2903  ///
2904  /// \param TemplateLoc The location of the 'template' keyword, if any.
2905  ///
2906  /// \param SS The nested-name-specifier, which is both an input
2907  /// parameter (the nested-name-specifier before this type) and an
2908  /// output parameter (containing the full nested-name-specifier,
2909  /// including this new type).
2910  ///
2911  /// \param TemplateLoc the location of the 'template' keyword, if any.
2912  /// \param TemplateName The template name.
2913  /// \param TemplateNameLoc The location of the template name.
2914  /// \param LAngleLoc The location of the opening angle bracket  ('<').
2915  /// \param TemplateArgs The template arguments.
2916  /// \param RAngleLoc The location of the closing angle bracket  ('>').
2917  /// \param CCLoc The location of the '::'.
2918
2919  /// \param EnteringContext Whether we're entering the context of the
2920  /// nested-name-specifier.
2921  ///
2922  ///
2923  /// \returns true if an error occurred, false otherwise.
2924  bool ActOnCXXNestedNameSpecifier(Scope *S,
2925                                   SourceLocation TemplateLoc,
2926                                   CXXScopeSpec &SS,
2927                                   TemplateTy Template,
2928                                   SourceLocation TemplateNameLoc,
2929                                   SourceLocation LAngleLoc,
2930                                   ASTTemplateArgsPtr TemplateArgs,
2931                                   SourceLocation RAngleLoc,
2932                                   SourceLocation CCLoc,
2933                                   bool EnteringContext);
2934
2935  /// \brief Given a C++ nested-name-specifier, produce an annotation value
2936  /// that the parser can use later to reconstruct the given
2937  /// nested-name-specifier.
2938  ///
2939  /// \param SS A nested-name-specifier.
2940  ///
2941  /// \returns A pointer containing all of the information in the
2942  /// nested-name-specifier \p SS.
2943  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
2944
2945  /// \brief Given an annotation pointer for a nested-name-specifier, restore
2946  /// the nested-name-specifier structure.
2947  ///
2948  /// \param Annotation The annotation pointer, produced by
2949  /// \c SaveNestedNameSpecifierAnnotation().
2950  ///
2951  /// \param AnnotationRange The source range corresponding to the annotation.
2952  ///
2953  /// \param SS The nested-name-specifier that will be updated with the contents
2954  /// of the annotation pointer.
2955  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
2956                                            SourceRange AnnotationRange,
2957                                            CXXScopeSpec &SS);
2958
2959  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2960
2961  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
2962  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
2963  /// After this method is called, according to [C++ 3.4.3p3], names should be
2964  /// looked up in the declarator-id's scope, until the declarator is parsed and
2965  /// ActOnCXXExitDeclaratorScope is called.
2966  /// The 'SS' should be a non-empty valid CXXScopeSpec.
2967  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
2968
2969  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
2970  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
2971  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
2972  /// Used to indicate that names should revert to being looked up in the
2973  /// defining scope.
2974  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2975
2976  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
2977  /// initializer for the declaration 'Dcl'.
2978  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
2979  /// static data member of class X, names should be looked up in the scope of
2980  /// class X.
2981  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
2982
2983  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
2984  /// initializer for the declaration 'Dcl'.
2985  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
2986
2987  // ParseObjCStringLiteral - Parse Objective-C string literals.
2988  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
2989                                    Expr **Strings,
2990                                    unsigned NumStrings);
2991
2992  Expr *BuildObjCEncodeExpression(SourceLocation AtLoc,
2993                                  TypeSourceInfo *EncodedTypeInfo,
2994                                  SourceLocation RParenLoc);
2995  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
2996                                    CXXMethodDecl *Method);
2997
2998  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
2999                                       SourceLocation EncodeLoc,
3000                                       SourceLocation LParenLoc,
3001                                       ParsedType Ty,
3002                                       SourceLocation RParenLoc);
3003
3004  // ParseObjCSelectorExpression - Build selector expression for @selector
3005  ExprResult ParseObjCSelectorExpression(Selector Sel,
3006                                         SourceLocation AtLoc,
3007                                         SourceLocation SelLoc,
3008                                         SourceLocation LParenLoc,
3009                                         SourceLocation RParenLoc);
3010
3011  // ParseObjCProtocolExpression - Build protocol expression for @protocol
3012  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
3013                                         SourceLocation AtLoc,
3014                                         SourceLocation ProtoLoc,
3015                                         SourceLocation LParenLoc,
3016                                         SourceLocation RParenLoc);
3017
3018  //===--------------------------------------------------------------------===//
3019  // C++ Declarations
3020  //
3021  Decl *ActOnStartLinkageSpecification(Scope *S,
3022                                       SourceLocation ExternLoc,
3023                                       SourceLocation LangLoc,
3024                                       llvm::StringRef Lang,
3025                                       SourceLocation LBraceLoc);
3026  Decl *ActOnFinishLinkageSpecification(Scope *S,
3027                                        Decl *LinkageSpec,
3028                                        SourceLocation RBraceLoc);
3029
3030
3031  //===--------------------------------------------------------------------===//
3032  // C++ Classes
3033  //
3034  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
3035                          const CXXScopeSpec *SS = 0);
3036
3037  Decl *ActOnAccessSpecifier(AccessSpecifier Access,
3038                             SourceLocation ASLoc,
3039                             SourceLocation ColonLoc);
3040
3041  Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
3042                                 Declarator &D,
3043                                 MultiTemplateParamsArg TemplateParameterLists,
3044                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
3045                                 Expr *Init, bool IsDefinition,
3046                                 bool Deleted = false);
3047
3048  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3049                                    Scope *S,
3050                                    CXXScopeSpec &SS,
3051                                    IdentifierInfo *MemberOrBase,
3052                                    ParsedType TemplateTypeTy,
3053                                    SourceLocation IdLoc,
3054                                    SourceLocation LParenLoc,
3055                                    Expr **Args, unsigned NumArgs,
3056                                    SourceLocation RParenLoc,
3057                                    SourceLocation EllipsisLoc);
3058
3059  MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr **Args,
3060                                       unsigned NumArgs, SourceLocation IdLoc,
3061                                       SourceLocation LParenLoc,
3062                                       SourceLocation RParenLoc);
3063
3064  MemInitResult BuildBaseInitializer(QualType BaseType,
3065                                     TypeSourceInfo *BaseTInfo,
3066                                     Expr **Args, unsigned NumArgs,
3067                                     SourceLocation LParenLoc,
3068                                     SourceLocation RParenLoc,
3069                                     CXXRecordDecl *ClassDecl,
3070                                     SourceLocation EllipsisLoc);
3071
3072  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
3073                                           Expr **Args, unsigned NumArgs,
3074                                           SourceLocation BaseLoc,
3075                                           SourceLocation RParenLoc,
3076                                           SourceLocation LParenLoc,
3077                                           CXXRecordDecl *ClassDecl);
3078
3079  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3080                                CXXCtorInitializer *Initializer);
3081
3082  bool SetCtorInitializers(CXXConstructorDecl *Constructor,
3083                           CXXCtorInitializer **Initializers,
3084                           unsigned NumInitializers, bool AnyErrors);
3085
3086  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
3087
3088
3089  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
3090  /// mark all the non-trivial destructors of its members and bases as
3091  /// referenced.
3092  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
3093                                              CXXRecordDecl *Record);
3094
3095  /// \brief The list of classes whose vtables have been used within
3096  /// this translation unit, and the source locations at which the
3097  /// first use occurred.
3098  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
3099
3100  /// \brief The list of vtables that are required but have not yet been
3101  /// materialized.
3102  llvm::SmallVector<VTableUse, 16> VTableUses;
3103
3104  /// \brief The set of classes whose vtables have been used within
3105  /// this translation unit, and a bit that will be true if the vtable is
3106  /// required to be emitted (otherwise, it should be emitted only if needed
3107  /// by code generation).
3108  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
3109
3110  /// \brief A list of all of the dynamic classes in this translation
3111  /// unit.
3112  llvm::SmallVector<CXXRecordDecl *, 16> DynamicClasses;
3113
3114  /// \brief Note that the vtable for the given class was used at the
3115  /// given location.
3116  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
3117                      bool DefinitionRequired = false);
3118
3119  /// MarkVirtualMembersReferenced - Will mark all members of the given
3120  /// CXXRecordDecl referenced.
3121  void MarkVirtualMembersReferenced(SourceLocation Loc,
3122                                    const CXXRecordDecl *RD);
3123
3124  /// \brief Define all of the vtables that have been used in this
3125  /// translation unit and reference any virtual members used by those
3126  /// vtables.
3127  ///
3128  /// \returns true if any work was done, false otherwise.
3129  bool DefineUsedVTables();
3130
3131  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
3132
3133  void ActOnMemInitializers(Decl *ConstructorDecl,
3134                            SourceLocation ColonLoc,
3135                            MemInitTy **MemInits, unsigned NumMemInits,
3136                            bool AnyErrors);
3137
3138  void CheckCompletedCXXClass(CXXRecordDecl *Record);
3139  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3140                                         Decl *TagDecl,
3141                                         SourceLocation LBrac,
3142                                         SourceLocation RBrac,
3143                                         AttributeList *AttrList);
3144
3145  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
3146  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
3147  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
3148  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3149  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
3150  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3151  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
3152  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
3153  bool IsInsideALocalClassWithinATemplateFunction();
3154
3155  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
3156                                     Expr *AssertExpr,
3157                                     Expr *AssertMessageExpr,
3158                                     SourceLocation RParenLoc);
3159
3160  FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
3161                                  TypeSourceInfo *TSInfo);
3162  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
3163                                MultiTemplateParamsArg TemplateParams);
3164  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
3165                                    MultiTemplateParamsArg TemplateParams);
3166
3167  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
3168                                      StorageClass& SC);
3169  void CheckConstructor(CXXConstructorDecl *Constructor);
3170  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
3171                                     StorageClass& SC);
3172  bool CheckDestructor(CXXDestructorDecl *Destructor);
3173  void CheckConversionDeclarator(Declarator &D, QualType &R,
3174                                 StorageClass& SC);
3175  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
3176
3177  //===--------------------------------------------------------------------===//
3178  // C++ Derived Classes
3179  //
3180
3181  /// ActOnBaseSpecifier - Parsed a base specifier
3182  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
3183                                       SourceRange SpecifierRange,
3184                                       bool Virtual, AccessSpecifier Access,
3185                                       TypeSourceInfo *TInfo,
3186                                       SourceLocation EllipsisLoc);
3187
3188  BaseResult ActOnBaseSpecifier(Decl *classdecl,
3189                                SourceRange SpecifierRange,
3190                                bool Virtual, AccessSpecifier Access,
3191                                ParsedType basetype,
3192                                SourceLocation BaseLoc,
3193                                SourceLocation EllipsisLoc);
3194
3195  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
3196                            unsigned NumBases);
3197  void ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, unsigned NumBases);
3198
3199  bool IsDerivedFrom(QualType Derived, QualType Base);
3200  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
3201
3202  // FIXME: I don't like this name.
3203  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
3204
3205  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
3206
3207  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3208                                    SourceLocation Loc, SourceRange Range,
3209                                    CXXCastPath *BasePath = 0,
3210                                    bool IgnoreAccess = false);
3211  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3212                                    unsigned InaccessibleBaseID,
3213                                    unsigned AmbigiousBaseConvID,
3214                                    SourceLocation Loc, SourceRange Range,
3215                                    DeclarationName Name,
3216                                    CXXCastPath *BasePath);
3217
3218  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
3219
3220  /// CheckOverridingFunctionReturnType - Checks whether the return types are
3221  /// covariant, according to C++ [class.virtual]p5.
3222  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3223                                         const CXXMethodDecl *Old);
3224
3225  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
3226  /// spec is a subset of base spec.
3227  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3228                                            const CXXMethodDecl *Old);
3229
3230  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
3231
3232  /// CheckOverrideControl - Check C++0x override control semantics.
3233  void CheckOverrideControl(const Decl *D);
3234
3235  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
3236  /// overrides a virtual member function marked 'final', according to
3237  /// C++0x [class.virtual]p3.
3238  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3239                                              const CXXMethodDecl *Old);
3240
3241
3242  //===--------------------------------------------------------------------===//
3243  // C++ Access Control
3244  //
3245
3246  enum AccessResult {
3247    AR_accessible,
3248    AR_inaccessible,
3249    AR_dependent,
3250    AR_delayed
3251  };
3252
3253  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
3254                                NamedDecl *PrevMemberDecl,
3255                                AccessSpecifier LexicalAS);
3256
3257  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
3258                                           DeclAccessPair FoundDecl);
3259  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
3260                                           DeclAccessPair FoundDecl);
3261  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
3262                                     SourceRange PlacementRange,
3263                                     CXXRecordDecl *NamingClass,
3264                                     DeclAccessPair FoundDecl);
3265  AccessResult CheckConstructorAccess(SourceLocation Loc,
3266                                      CXXConstructorDecl *D,
3267                                      const InitializedEntity &Entity,
3268                                      AccessSpecifier Access,
3269                                      bool IsCopyBindingRefToTemp = false);
3270  AccessResult CheckDestructorAccess(SourceLocation Loc,
3271                                     CXXDestructorDecl *Dtor,
3272                                     const PartialDiagnostic &PDiag);
3273  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
3274                                       NamedDecl *D,
3275                                       const PartialDiagnostic &PDiag);
3276  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
3277                                         Expr *ObjectExpr,
3278                                         Expr *ArgExpr,
3279                                         DeclAccessPair FoundDecl);
3280  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
3281                                          DeclAccessPair FoundDecl);
3282  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
3283                                    QualType Base, QualType Derived,
3284                                    const CXXBasePath &Path,
3285                                    unsigned DiagID,
3286                                    bool ForceCheck = false,
3287                                    bool ForceUnprivileged = false);
3288  void CheckLookupAccess(const LookupResult &R);
3289
3290  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
3291                         const MultiLevelTemplateArgumentList &TemplateArgs);
3292  void PerformDependentDiagnostics(const DeclContext *Pattern,
3293                        const MultiLevelTemplateArgumentList &TemplateArgs);
3294
3295  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3296
3297  /// A flag to suppress access checking.
3298  bool SuppressAccessChecking;
3299
3300  /// \brief When true, access checking violations are treated as SFINAE
3301  /// failures rather than hard errors.
3302  bool AccessCheckingSFINAE;
3303
3304  void ActOnStartSuppressingAccessChecks();
3305  void ActOnStopSuppressingAccessChecks();
3306
3307  enum AbstractDiagSelID {
3308    AbstractNone = -1,
3309    AbstractReturnType,
3310    AbstractParamType,
3311    AbstractVariableType,
3312    AbstractFieldType,
3313    AbstractArrayType
3314  };
3315
3316  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
3317                              const PartialDiagnostic &PD);
3318  void DiagnoseAbstractType(const CXXRecordDecl *RD);
3319
3320  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
3321                              AbstractDiagSelID SelID = AbstractNone);
3322
3323  //===--------------------------------------------------------------------===//
3324  // C++ Overloaded Operators [C++ 13.5]
3325  //
3326
3327  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
3328
3329  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
3330
3331  //===--------------------------------------------------------------------===//
3332  // C++ Templates [C++ 14]
3333  //
3334  void FilterAcceptableTemplateNames(LookupResult &R);
3335  bool hasAnyAcceptableTemplateNames(LookupResult &R);
3336
3337  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
3338                          QualType ObjectType, bool EnteringContext,
3339                          bool &MemberOfUnknownSpecialization);
3340
3341  TemplateNameKind isTemplateName(Scope *S,
3342                                  CXXScopeSpec &SS,
3343                                  bool hasTemplateKeyword,
3344                                  UnqualifiedId &Name,
3345                                  ParsedType ObjectType,
3346                                  bool EnteringContext,
3347                                  TemplateTy &Template,
3348                                  bool &MemberOfUnknownSpecialization);
3349
3350  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
3351                                   SourceLocation IILoc,
3352                                   Scope *S,
3353                                   const CXXScopeSpec *SS,
3354                                   TemplateTy &SuggestedTemplate,
3355                                   TemplateNameKind &SuggestedKind);
3356
3357  bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
3358  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
3359
3360  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
3361                           SourceLocation EllipsisLoc,
3362                           SourceLocation KeyLoc,
3363                           IdentifierInfo *ParamName,
3364                           SourceLocation ParamNameLoc,
3365                           unsigned Depth, unsigned Position,
3366                           SourceLocation EqualLoc,
3367                           ParsedType DefaultArg);
3368
3369  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
3370  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
3371                                      unsigned Depth,
3372                                      unsigned Position,
3373                                      SourceLocation EqualLoc,
3374                                      Expr *DefaultArg);
3375  Decl *ActOnTemplateTemplateParameter(Scope *S,
3376                                       SourceLocation TmpLoc,
3377                                       TemplateParamsTy *Params,
3378                                       SourceLocation EllipsisLoc,
3379                                       IdentifierInfo *ParamName,
3380                                       SourceLocation ParamNameLoc,
3381                                       unsigned Depth,
3382                                       unsigned Position,
3383                                       SourceLocation EqualLoc,
3384                                       ParsedTemplateArgument DefaultArg);
3385
3386  TemplateParamsTy *
3387  ActOnTemplateParameterList(unsigned Depth,
3388                             SourceLocation ExportLoc,
3389                             SourceLocation TemplateLoc,
3390                             SourceLocation LAngleLoc,
3391                             Decl **Params, unsigned NumParams,
3392                             SourceLocation RAngleLoc);
3393
3394  /// \brief The context in which we are checking a template parameter
3395  /// list.
3396  enum TemplateParamListContext {
3397    TPC_ClassTemplate,
3398    TPC_FunctionTemplate,
3399    TPC_ClassTemplateMember,
3400    TPC_FriendFunctionTemplate,
3401    TPC_FriendFunctionTemplateDefinition
3402  };
3403
3404  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
3405                                  TemplateParameterList *OldParams,
3406                                  TemplateParamListContext TPC);
3407  TemplateParameterList *
3408  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
3409                                          const CXXScopeSpec &SS,
3410                                          TemplateParameterList **ParamLists,
3411                                          unsigned NumParamLists,
3412                                          bool IsFriend,
3413                                          bool &IsExplicitSpecialization,
3414                                          bool &Invalid);
3415
3416  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
3417                                SourceLocation KWLoc, CXXScopeSpec &SS,
3418                                IdentifierInfo *Name, SourceLocation NameLoc,
3419                                AttributeList *Attr,
3420                                TemplateParameterList *TemplateParams,
3421                                AccessSpecifier AS,
3422                                unsigned NumOuterTemplateParamLists,
3423                            TemplateParameterList **OuterTemplateParamLists);
3424
3425  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
3426                                  TemplateArgumentListInfo &Out);
3427
3428  void NoteAllFoundTemplates(TemplateName Name);
3429
3430  QualType CheckTemplateIdType(TemplateName Template,
3431                               SourceLocation TemplateLoc,
3432                              TemplateArgumentListInfo &TemplateArgs);
3433
3434  TypeResult
3435  ActOnTemplateIdType(CXXScopeSpec &SS,
3436                      TemplateTy Template, SourceLocation TemplateLoc,
3437                      SourceLocation LAngleLoc,
3438                      ASTTemplateArgsPtr TemplateArgs,
3439                      SourceLocation RAngleLoc);
3440
3441  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
3442  /// such as \c class T::template apply<U>.
3443  ///
3444  /// \param TUK
3445  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
3446                                    TypeSpecifierType TagSpec,
3447                                    SourceLocation TagLoc,
3448                                    CXXScopeSpec &SS,
3449                                    TemplateTy TemplateD,
3450                                    SourceLocation TemplateLoc,
3451                                    SourceLocation LAngleLoc,
3452                                    ASTTemplateArgsPtr TemplateArgsIn,
3453                                    SourceLocation RAngleLoc);
3454
3455
3456  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
3457                                 LookupResult &R,
3458                                 bool RequiresADL,
3459                               const TemplateArgumentListInfo &TemplateArgs);
3460  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3461                               const DeclarationNameInfo &NameInfo,
3462                               const TemplateArgumentListInfo &TemplateArgs);
3463
3464  TemplateNameKind ActOnDependentTemplateName(Scope *S,
3465                                              SourceLocation TemplateKWLoc,
3466                                              CXXScopeSpec &SS,
3467                                              UnqualifiedId &Name,
3468                                              ParsedType ObjectType,
3469                                              bool EnteringContext,
3470                                              TemplateTy &Template);
3471
3472  DeclResult
3473  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
3474                                   SourceLocation KWLoc,
3475                                   CXXScopeSpec &SS,
3476                                   TemplateTy Template,
3477                                   SourceLocation TemplateNameLoc,
3478                                   SourceLocation LAngleLoc,
3479                                   ASTTemplateArgsPtr TemplateArgs,
3480                                   SourceLocation RAngleLoc,
3481                                   AttributeList *Attr,
3482                                 MultiTemplateParamsArg TemplateParameterLists);
3483
3484  Decl *ActOnTemplateDeclarator(Scope *S,
3485                                MultiTemplateParamsArg TemplateParameterLists,
3486                                Declarator &D);
3487
3488  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3489                                  MultiTemplateParamsArg TemplateParameterLists,
3490                                        Declarator &D);
3491
3492  bool
3493  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3494                                         TemplateSpecializationKind NewTSK,
3495                                         NamedDecl *PrevDecl,
3496                                         TemplateSpecializationKind PrevTSK,
3497                                         SourceLocation PrevPtOfInstantiation,
3498                                         bool &SuppressNew);
3499
3500  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
3501                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
3502                                                    LookupResult &Previous);
3503
3504  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3505                         TemplateArgumentListInfo *ExplicitTemplateArgs,
3506                                           LookupResult &Previous);
3507  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
3508
3509  DeclResult
3510  ActOnExplicitInstantiation(Scope *S,
3511                             SourceLocation ExternLoc,
3512                             SourceLocation TemplateLoc,
3513                             unsigned TagSpec,
3514                             SourceLocation KWLoc,
3515                             const CXXScopeSpec &SS,
3516                             TemplateTy Template,
3517                             SourceLocation TemplateNameLoc,
3518                             SourceLocation LAngleLoc,
3519                             ASTTemplateArgsPtr TemplateArgs,
3520                             SourceLocation RAngleLoc,
3521                             AttributeList *Attr);
3522
3523  DeclResult
3524  ActOnExplicitInstantiation(Scope *S,
3525                             SourceLocation ExternLoc,
3526                             SourceLocation TemplateLoc,
3527                             unsigned TagSpec,
3528                             SourceLocation KWLoc,
3529                             CXXScopeSpec &SS,
3530                             IdentifierInfo *Name,
3531                             SourceLocation NameLoc,
3532                             AttributeList *Attr);
3533
3534  DeclResult ActOnExplicitInstantiation(Scope *S,
3535                                        SourceLocation ExternLoc,
3536                                        SourceLocation TemplateLoc,
3537                                        Declarator &D);
3538
3539  TemplateArgumentLoc
3540  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3541                                          SourceLocation TemplateLoc,
3542                                          SourceLocation RAngleLoc,
3543                                          Decl *Param,
3544                          llvm::SmallVectorImpl<TemplateArgument> &Converted);
3545
3546  /// \brief Specifies the context in which a particular template
3547  /// argument is being checked.
3548  enum CheckTemplateArgumentKind {
3549    /// \brief The template argument was specified in the code or was
3550    /// instantiated with some deduced template arguments.
3551    CTAK_Specified,
3552
3553    /// \brief The template argument was deduced via template argument
3554    /// deduction.
3555    CTAK_Deduced,
3556
3557    /// \brief The template argument was deduced from an array bound
3558    /// via template argument deduction.
3559    CTAK_DeducedFromArrayBound
3560  };
3561
3562  bool CheckTemplateArgument(NamedDecl *Param,
3563                             const TemplateArgumentLoc &Arg,
3564                             NamedDecl *Template,
3565                             SourceLocation TemplateLoc,
3566                             SourceLocation RAngleLoc,
3567                             unsigned ArgumentPackIndex,
3568                           llvm::SmallVectorImpl<TemplateArgument> &Converted,
3569                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
3570
3571  /// \brief Check that the given template arguments can be be provided to
3572  /// the given template, converting the arguments along the way.
3573  ///
3574  /// \param Template The template to which the template arguments are being
3575  /// provided.
3576  ///
3577  /// \param TemplateLoc The location of the template name in the source.
3578  ///
3579  /// \param TemplateArgs The list of template arguments. If the template is
3580  /// a template template parameter, this function may extend the set of
3581  /// template arguments to also include substituted, defaulted template
3582  /// arguments.
3583  ///
3584  /// \param PartialTemplateArgs True if the list of template arguments is
3585  /// intentionally partial, e.g., because we're checking just the initial
3586  /// set of template arguments.
3587  ///
3588  /// \param Converted Will receive the converted, canonicalized template
3589  /// arguments.
3590  ///
3591  /// \returns True if an error occurred, false otherwise.
3592  bool CheckTemplateArgumentList(TemplateDecl *Template,
3593                                 SourceLocation TemplateLoc,
3594                                 TemplateArgumentListInfo &TemplateArgs,
3595                                 bool PartialTemplateArgs,
3596                           llvm::SmallVectorImpl<TemplateArgument> &Converted);
3597
3598  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3599                                 const TemplateArgumentLoc &Arg,
3600                           llvm::SmallVectorImpl<TemplateArgument> &Converted);
3601
3602  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
3603                             TypeSourceInfo *Arg);
3604  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
3605                                            TemplateArgument &Converted);
3606  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3607                                   QualType InstantiatedParamType, Expr *Arg,
3608                                   TemplateArgument &Converted,
3609                                   CheckTemplateArgumentKind CTAK = CTAK_Specified);
3610  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3611                             const TemplateArgumentLoc &Arg);
3612
3613  ExprResult
3614  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3615                                          QualType ParamType,
3616                                          SourceLocation Loc);
3617  ExprResult
3618  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3619                                              SourceLocation Loc);
3620
3621  /// \brief Enumeration describing how template parameter lists are compared
3622  /// for equality.
3623  enum TemplateParameterListEqualKind {
3624    /// \brief We are matching the template parameter lists of two templates
3625    /// that might be redeclarations.
3626    ///
3627    /// \code
3628    /// template<typename T> struct X;
3629    /// template<typename T> struct X;
3630    /// \endcode
3631    TPL_TemplateMatch,
3632
3633    /// \brief We are matching the template parameter lists of two template
3634    /// template parameters as part of matching the template parameter lists
3635    /// of two templates that might be redeclarations.
3636    ///
3637    /// \code
3638    /// template<template<int I> class TT> struct X;
3639    /// template<template<int Value> class Other> struct X;
3640    /// \endcode
3641    TPL_TemplateTemplateParmMatch,
3642
3643    /// \brief We are matching the template parameter lists of a template
3644    /// template argument against the template parameter lists of a template
3645    /// template parameter.
3646    ///
3647    /// \code
3648    /// template<template<int Value> class Metafun> struct X;
3649    /// template<int Value> struct integer_c;
3650    /// X<integer_c> xic;
3651    /// \endcode
3652    TPL_TemplateTemplateArgumentMatch
3653  };
3654
3655  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
3656                                      TemplateParameterList *Old,
3657                                      bool Complain,
3658                                      TemplateParameterListEqualKind Kind,
3659                                      SourceLocation TemplateArgLoc
3660                                        = SourceLocation());
3661
3662  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
3663
3664  /// \brief Called when the parser has parsed a C++ typename
3665  /// specifier, e.g., "typename T::type".
3666  ///
3667  /// \param S The scope in which this typename type occurs.
3668  /// \param TypenameLoc the location of the 'typename' keyword
3669  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3670  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
3671  /// \param IdLoc the location of the identifier.
3672  TypeResult
3673  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3674                    const CXXScopeSpec &SS, const IdentifierInfo &II,
3675                    SourceLocation IdLoc);
3676
3677  /// \brief Called when the parser has parsed a C++ typename
3678  /// specifier that ends in a template-id, e.g.,
3679  /// "typename MetaFun::template apply<T1, T2>".
3680  ///
3681  /// \param S The scope in which this typename type occurs.
3682  /// \param TypenameLoc the location of the 'typename' keyword
3683  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3684  /// \param TemplateLoc the location of the 'template' keyword, if any.
3685  /// \param TemplateName The template name.
3686  /// \param TemplateNameLoc The location of the template name.
3687  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3688  /// \param TemplateArgs The template arguments.
3689  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3690  TypeResult
3691  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3692                    const CXXScopeSpec &SS,
3693                    SourceLocation TemplateLoc,
3694                    TemplateTy Template,
3695                    SourceLocation TemplateNameLoc,
3696                    SourceLocation LAngleLoc,
3697                    ASTTemplateArgsPtr TemplateArgs,
3698                    SourceLocation RAngleLoc);
3699
3700  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
3701                             SourceLocation KeywordLoc,
3702                             NestedNameSpecifierLoc QualifierLoc,
3703                             const IdentifierInfo &II,
3704                             SourceLocation IILoc);
3705
3706  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
3707                                                    SourceLocation Loc,
3708                                                    DeclarationName Name);
3709  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
3710
3711  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
3712
3713  std::string
3714  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3715                                  const TemplateArgumentList &Args);
3716
3717  std::string
3718  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3719                                  const TemplateArgument *Args,
3720                                  unsigned NumArgs);
3721
3722  //===--------------------------------------------------------------------===//
3723  // C++ Variadic Templates (C++0x [temp.variadic])
3724  //===--------------------------------------------------------------------===//
3725
3726  /// \brief The context in which an unexpanded parameter pack is
3727  /// being diagnosed.
3728  ///
3729  /// Note that the values of this enumeration line up with the first
3730  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
3731  enum UnexpandedParameterPackContext {
3732    /// \brief An arbitrary expression.
3733    UPPC_Expression = 0,
3734
3735    /// \brief The base type of a class type.
3736    UPPC_BaseType,
3737
3738    /// \brief The type of an arbitrary declaration.
3739    UPPC_DeclarationType,
3740
3741    /// \brief The type of a data member.
3742    UPPC_DataMemberType,
3743
3744    /// \brief The size of a bit-field.
3745    UPPC_BitFieldWidth,
3746
3747    /// \brief The expression in a static assertion.
3748    UPPC_StaticAssertExpression,
3749
3750    /// \brief The fixed underlying type of an enumeration.
3751    UPPC_FixedUnderlyingType,
3752
3753    /// \brief The enumerator value.
3754    UPPC_EnumeratorValue,
3755
3756    /// \brief A using declaration.
3757    UPPC_UsingDeclaration,
3758
3759    /// \brief A friend declaration.
3760    UPPC_FriendDeclaration,
3761
3762    /// \brief A declaration qualifier.
3763    UPPC_DeclarationQualifier,
3764
3765    /// \brief An initializer.
3766    UPPC_Initializer,
3767
3768    /// \brief A default argument.
3769    UPPC_DefaultArgument,
3770
3771    /// \brief The type of a non-type template parameter.
3772    UPPC_NonTypeTemplateParameterType,
3773
3774    /// \brief The type of an exception.
3775    UPPC_ExceptionType,
3776
3777    /// \brief Partial specialization.
3778    UPPC_PartialSpecialization
3779  };
3780
3781  /// \brief If the given type contains an unexpanded parameter pack,
3782  /// diagnose the error.
3783  ///
3784  /// \param Loc The source location where a diagnostc should be emitted.
3785  ///
3786  /// \param T The type that is being checked for unexpanded parameter
3787  /// packs.
3788  ///
3789  /// \returns true if an error occurred, false otherwise.
3790  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
3791                                       UnexpandedParameterPackContext UPPC);
3792
3793  /// \brief If the given expression contains an unexpanded parameter
3794  /// pack, diagnose the error.
3795  ///
3796  /// \param E The expression that is being checked for unexpanded
3797  /// parameter packs.
3798  ///
3799  /// \returns true if an error occurred, false otherwise.
3800  bool DiagnoseUnexpandedParameterPack(Expr *E,
3801                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
3802
3803  /// \brief If the given nested-name-specifier contains an unexpanded
3804  /// parameter pack, diagnose the error.
3805  ///
3806  /// \param SS The nested-name-specifier that is being checked for
3807  /// unexpanded parameter packs.
3808  ///
3809  /// \returns true if an error occurred, false otherwise.
3810  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
3811                                       UnexpandedParameterPackContext UPPC);
3812
3813  /// \brief If the given name contains an unexpanded parameter pack,
3814  /// diagnose the error.
3815  ///
3816  /// \param NameInfo The name (with source location information) that
3817  /// is being checked for unexpanded parameter packs.
3818  ///
3819  /// \returns true if an error occurred, false otherwise.
3820  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
3821                                       UnexpandedParameterPackContext UPPC);
3822
3823  /// \brief If the given template name contains an unexpanded parameter pack,
3824  /// diagnose the error.
3825  ///
3826  /// \param Loc The location of the template name.
3827  ///
3828  /// \param Template The template name that is being checked for unexpanded
3829  /// parameter packs.
3830  ///
3831  /// \returns true if an error occurred, false otherwise.
3832  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
3833                                       TemplateName Template,
3834                                       UnexpandedParameterPackContext UPPC);
3835
3836  /// \brief If the given template argument contains an unexpanded parameter
3837  /// pack, diagnose the error.
3838  ///
3839  /// \param Arg The template argument that is being checked for unexpanded
3840  /// parameter packs.
3841  ///
3842  /// \returns true if an error occurred, false otherwise.
3843  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
3844                                       UnexpandedParameterPackContext UPPC);
3845
3846  /// \brief Collect the set of unexpanded parameter packs within the given
3847  /// template argument.
3848  ///
3849  /// \param Arg The template argument that will be traversed to find
3850  /// unexpanded parameter packs.
3851  void collectUnexpandedParameterPacks(TemplateArgument Arg,
3852                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3853
3854  /// \brief Collect the set of unexpanded parameter packs within the given
3855  /// template argument.
3856  ///
3857  /// \param Arg The template argument that will be traversed to find
3858  /// unexpanded parameter packs.
3859  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
3860                    llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3861
3862  /// \brief Collect the set of unexpanded parameter packs within the given
3863  /// type.
3864  ///
3865  /// \param T The type that will be traversed to find
3866  /// unexpanded parameter packs.
3867  void collectUnexpandedParameterPacks(QualType T,
3868                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3869
3870  /// \brief Collect the set of unexpanded parameter packs within the given
3871  /// type.
3872  ///
3873  /// \param TL The type that will be traversed to find
3874  /// unexpanded parameter packs.
3875  void collectUnexpandedParameterPacks(TypeLoc TL,
3876                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3877
3878  /// \brief Invoked when parsing a template argument followed by an
3879  /// ellipsis, which creates a pack expansion.
3880  ///
3881  /// \param Arg The template argument preceding the ellipsis, which
3882  /// may already be invalid.
3883  ///
3884  /// \param EllipsisLoc The location of the ellipsis.
3885  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
3886                                            SourceLocation EllipsisLoc);
3887
3888  /// \brief Invoked when parsing a type followed by an ellipsis, which
3889  /// creates a pack expansion.
3890  ///
3891  /// \param Type The type preceding the ellipsis, which will become
3892  /// the pattern of the pack expansion.
3893  ///
3894  /// \param EllipsisLoc The location of the ellipsis.
3895  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
3896
3897  /// \brief Construct a pack expansion type from the pattern of the pack
3898  /// expansion.
3899  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
3900                                     SourceLocation EllipsisLoc,
3901                                     llvm::Optional<unsigned> NumExpansions);
3902
3903  /// \brief Construct a pack expansion type from the pattern of the pack
3904  /// expansion.
3905  QualType CheckPackExpansion(QualType Pattern,
3906                              SourceRange PatternRange,
3907                              SourceLocation EllipsisLoc,
3908                              llvm::Optional<unsigned> NumExpansions);
3909
3910  /// \brief Invoked when parsing an expression followed by an ellipsis, which
3911  /// creates a pack expansion.
3912  ///
3913  /// \param Pattern The expression preceding the ellipsis, which will become
3914  /// the pattern of the pack expansion.
3915  ///
3916  /// \param EllipsisLoc The location of the ellipsis.
3917  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
3918
3919  /// \brief Invoked when parsing an expression followed by an ellipsis, which
3920  /// creates a pack expansion.
3921  ///
3922  /// \param Pattern The expression preceding the ellipsis, which will become
3923  /// the pattern of the pack expansion.
3924  ///
3925  /// \param EllipsisLoc The location of the ellipsis.
3926  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3927                                llvm::Optional<unsigned> NumExpansions);
3928
3929  /// \brief Determine whether we could expand a pack expansion with the
3930  /// given set of parameter packs into separate arguments by repeatedly
3931  /// transforming the pattern.
3932  ///
3933  /// \param EllipsisLoc The location of the ellipsis that identifies the
3934  /// pack expansion.
3935  ///
3936  /// \param PatternRange The source range that covers the entire pattern of
3937  /// the pack expansion.
3938  ///
3939  /// \param Unexpanded The set of unexpanded parameter packs within the
3940  /// pattern.
3941  ///
3942  /// \param NumUnexpanded The number of unexpanded parameter packs in
3943  /// \p Unexpanded.
3944  ///
3945  /// \param ShouldExpand Will be set to \c true if the transformer should
3946  /// expand the corresponding pack expansions into separate arguments. When
3947  /// set, \c NumExpansions must also be set.
3948  ///
3949  /// \param RetainExpansion Whether the caller should add an unexpanded
3950  /// pack expansion after all of the expanded arguments. This is used
3951  /// when extending explicitly-specified template argument packs per
3952  /// C++0x [temp.arg.explicit]p9.
3953  ///
3954  /// \param NumExpansions The number of separate arguments that will be in
3955  /// the expanded form of the corresponding pack expansion. This is both an
3956  /// input and an output parameter, which can be set by the caller if the
3957  /// number of expansions is known a priori (e.g., due to a prior substitution)
3958  /// and will be set by the callee when the number of expansions is known.
3959  /// The callee must set this value when \c ShouldExpand is \c true; it may
3960  /// set this value in other cases.
3961  ///
3962  /// \returns true if an error occurred (e.g., because the parameter packs
3963  /// are to be instantiated with arguments of different lengths), false
3964  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
3965  /// must be set.
3966  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
3967                                       SourceRange PatternRange,
3968                                     const UnexpandedParameterPack *Unexpanded,
3969                                       unsigned NumUnexpanded,
3970                             const MultiLevelTemplateArgumentList &TemplateArgs,
3971                                       bool &ShouldExpand,
3972                                       bool &RetainExpansion,
3973                                       llvm::Optional<unsigned> &NumExpansions);
3974
3975  /// \brief Determine the number of arguments in the given pack expansion
3976  /// type.
3977  ///
3978  /// This routine already assumes that the pack expansion type can be
3979  /// expanded and that the number of arguments in the expansion is
3980  /// consistent across all of the unexpanded parameter packs in its pattern.
3981  unsigned getNumArgumentsInExpansion(QualType T,
3982                            const MultiLevelTemplateArgumentList &TemplateArgs);
3983
3984  /// \brief Determine whether the given declarator contains any unexpanded
3985  /// parameter packs.
3986  ///
3987  /// This routine is used by the parser to disambiguate function declarators
3988  /// with an ellipsis prior to the ')', e.g.,
3989  ///
3990  /// \code
3991  ///   void f(T...);
3992  /// \endcode
3993  ///
3994  /// To determine whether we have an (unnamed) function parameter pack or
3995  /// a variadic function.
3996  ///
3997  /// \returns true if the declarator contains any unexpanded parameter packs,
3998  /// false otherwise.
3999  bool containsUnexpandedParameterPacks(Declarator &D);
4000
4001  //===--------------------------------------------------------------------===//
4002  // C++ Template Argument Deduction (C++ [temp.deduct])
4003  //===--------------------------------------------------------------------===//
4004
4005  /// \brief Describes the result of template argument deduction.
4006  ///
4007  /// The TemplateDeductionResult enumeration describes the result of
4008  /// template argument deduction, as returned from
4009  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
4010  /// structure provides additional information about the results of
4011  /// template argument deduction, e.g., the deduced template argument
4012  /// list (if successful) or the specific template parameters or
4013  /// deduced arguments that were involved in the failure.
4014  enum TemplateDeductionResult {
4015    /// \brief Template argument deduction was successful.
4016    TDK_Success = 0,
4017    /// \brief Template argument deduction exceeded the maximum template
4018    /// instantiation depth (which has already been diagnosed).
4019    TDK_InstantiationDepth,
4020    /// \brief Template argument deduction did not deduce a value
4021    /// for every template parameter.
4022    TDK_Incomplete,
4023    /// \brief Template argument deduction produced inconsistent
4024    /// deduced values for the given template parameter.
4025    TDK_Inconsistent,
4026    /// \brief Template argument deduction failed due to inconsistent
4027    /// cv-qualifiers on a template parameter type that would
4028    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
4029    /// but were given a non-const "X".
4030    TDK_Underqualified,
4031    /// \brief Substitution of the deduced template argument values
4032    /// resulted in an error.
4033    TDK_SubstitutionFailure,
4034    /// \brief Substitution of the deduced template argument values
4035    /// into a non-deduced context produced a type or value that
4036    /// produces a type that does not match the original template
4037    /// arguments provided.
4038    TDK_NonDeducedMismatch,
4039    /// \brief When performing template argument deduction for a function
4040    /// template, there were too many call arguments.
4041    TDK_TooManyArguments,
4042    /// \brief When performing template argument deduction for a function
4043    /// template, there were too few call arguments.
4044    TDK_TooFewArguments,
4045    /// \brief The explicitly-specified template arguments were not valid
4046    /// template arguments for the given template.
4047    TDK_InvalidExplicitArguments,
4048    /// \brief The arguments included an overloaded function name that could
4049    /// not be resolved to a suitable function.
4050    TDK_FailedOverloadResolution
4051  };
4052
4053  TemplateDeductionResult
4054  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
4055                          const TemplateArgumentList &TemplateArgs,
4056                          sema::TemplateDeductionInfo &Info);
4057
4058  TemplateDeductionResult
4059  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4060                              TemplateArgumentListInfo &ExplicitTemplateArgs,
4061                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4062                                 llvm::SmallVectorImpl<QualType> &ParamTypes,
4063                                      QualType *FunctionType,
4064                                      sema::TemplateDeductionInfo &Info);
4065
4066  TemplateDeductionResult
4067  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
4068                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4069                                  unsigned NumExplicitlySpecified,
4070                                  FunctionDecl *&Specialization,
4071                                  sema::TemplateDeductionInfo &Info);
4072
4073  TemplateDeductionResult
4074  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4075                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4076                          Expr **Args, unsigned NumArgs,
4077                          FunctionDecl *&Specialization,
4078                          sema::TemplateDeductionInfo &Info);
4079
4080  TemplateDeductionResult
4081  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4082                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4083                          QualType ArgFunctionType,
4084                          FunctionDecl *&Specialization,
4085                          sema::TemplateDeductionInfo &Info);
4086
4087  TemplateDeductionResult
4088  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4089                          QualType ToType,
4090                          CXXConversionDecl *&Specialization,
4091                          sema::TemplateDeductionInfo &Info);
4092
4093  TemplateDeductionResult
4094  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4095                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4096                          FunctionDecl *&Specialization,
4097                          sema::TemplateDeductionInfo &Info);
4098
4099  bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer,
4100                      TypeSourceInfo *&Result);
4101
4102  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4103                                                   FunctionTemplateDecl *FT2,
4104                                                   SourceLocation Loc,
4105                                           TemplatePartialOrderingContext TPOC,
4106                                                   unsigned NumCallArguments);
4107  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
4108                                           UnresolvedSetIterator SEnd,
4109                                           TemplatePartialOrderingContext TPOC,
4110                                           unsigned NumCallArguments,
4111                                           SourceLocation Loc,
4112                                           const PartialDiagnostic &NoneDiag,
4113                                           const PartialDiagnostic &AmbigDiag,
4114                                        const PartialDiagnostic &CandidateDiag,
4115                                        bool Complain = true);
4116
4117  ClassTemplatePartialSpecializationDecl *
4118  getMoreSpecializedPartialSpecialization(
4119                                  ClassTemplatePartialSpecializationDecl *PS1,
4120                                  ClassTemplatePartialSpecializationDecl *PS2,
4121                                  SourceLocation Loc);
4122
4123  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4124                                  bool OnlyDeduced,
4125                                  unsigned Depth,
4126                                  llvm::SmallVectorImpl<bool> &Used);
4127  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4128                                     llvm::SmallVectorImpl<bool> &Deduced);
4129
4130  //===--------------------------------------------------------------------===//
4131  // C++ Template Instantiation
4132  //
4133
4134  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
4135                                     const TemplateArgumentList *Innermost = 0,
4136                                                bool RelativeToPrimary = false,
4137                                               const FunctionDecl *Pattern = 0);
4138
4139  /// \brief A template instantiation that is currently in progress.
4140  struct ActiveTemplateInstantiation {
4141    /// \brief The kind of template instantiation we are performing
4142    enum InstantiationKind {
4143      /// We are instantiating a template declaration. The entity is
4144      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
4145      TemplateInstantiation,
4146
4147      /// We are instantiating a default argument for a template
4148      /// parameter. The Entity is the template, and
4149      /// TemplateArgs/NumTemplateArguments provides the template
4150      /// arguments as specified.
4151      /// FIXME: Use a TemplateArgumentList
4152      DefaultTemplateArgumentInstantiation,
4153
4154      /// We are instantiating a default argument for a function.
4155      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
4156      /// provides the template arguments as specified.
4157      DefaultFunctionArgumentInstantiation,
4158
4159      /// We are substituting explicit template arguments provided for
4160      /// a function template. The entity is a FunctionTemplateDecl.
4161      ExplicitTemplateArgumentSubstitution,
4162
4163      /// We are substituting template argument determined as part of
4164      /// template argument deduction for either a class template
4165      /// partial specialization or a function template. The
4166      /// Entity is either a ClassTemplatePartialSpecializationDecl or
4167      /// a FunctionTemplateDecl.
4168      DeducedTemplateArgumentSubstitution,
4169
4170      /// We are substituting prior template arguments into a new
4171      /// template parameter. The template parameter itself is either a
4172      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
4173      PriorTemplateArgumentSubstitution,
4174
4175      /// We are checking the validity of a default template argument that
4176      /// has been used when naming a template-id.
4177      DefaultTemplateArgumentChecking
4178    } Kind;
4179
4180    /// \brief The point of instantiation within the source code.
4181    SourceLocation PointOfInstantiation;
4182
4183    /// \brief The template (or partial specialization) in which we are
4184    /// performing the instantiation, for substitutions of prior template
4185    /// arguments.
4186    NamedDecl *Template;
4187
4188    /// \brief The entity that is being instantiated.
4189    uintptr_t Entity;
4190
4191    /// \brief The list of template arguments we are substituting, if they
4192    /// are not part of the entity.
4193    const TemplateArgument *TemplateArgs;
4194
4195    /// \brief The number of template arguments in TemplateArgs.
4196    unsigned NumTemplateArgs;
4197
4198    /// \brief The template deduction info object associated with the
4199    /// substitution or checking of explicit or deduced template arguments.
4200    sema::TemplateDeductionInfo *DeductionInfo;
4201
4202    /// \brief The source range that covers the construct that cause
4203    /// the instantiation, e.g., the template-id that causes a class
4204    /// template instantiation.
4205    SourceRange InstantiationRange;
4206
4207    ActiveTemplateInstantiation()
4208      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
4209        NumTemplateArgs(0), DeductionInfo(0) {}
4210
4211    /// \brief Determines whether this template is an actual instantiation
4212    /// that should be counted toward the maximum instantiation depth.
4213    bool isInstantiationRecord() const;
4214
4215    friend bool operator==(const ActiveTemplateInstantiation &X,
4216                           const ActiveTemplateInstantiation &Y) {
4217      if (X.Kind != Y.Kind)
4218        return false;
4219
4220      if (X.Entity != Y.Entity)
4221        return false;
4222
4223      switch (X.Kind) {
4224      case TemplateInstantiation:
4225        return true;
4226
4227      case PriorTemplateArgumentSubstitution:
4228      case DefaultTemplateArgumentChecking:
4229        if (X.Template != Y.Template)
4230          return false;
4231
4232        // Fall through
4233
4234      case DefaultTemplateArgumentInstantiation:
4235      case ExplicitTemplateArgumentSubstitution:
4236      case DeducedTemplateArgumentSubstitution:
4237      case DefaultFunctionArgumentInstantiation:
4238        return X.TemplateArgs == Y.TemplateArgs;
4239
4240      }
4241
4242      return true;
4243    }
4244
4245    friend bool operator!=(const ActiveTemplateInstantiation &X,
4246                           const ActiveTemplateInstantiation &Y) {
4247      return !(X == Y);
4248    }
4249  };
4250
4251  /// \brief List of active template instantiations.
4252  ///
4253  /// This vector is treated as a stack. As one template instantiation
4254  /// requires another template instantiation, additional
4255  /// instantiations are pushed onto the stack up to a
4256  /// user-configurable limit LangOptions::InstantiationDepth.
4257  llvm::SmallVector<ActiveTemplateInstantiation, 16>
4258    ActiveTemplateInstantiations;
4259
4260  /// \brief Whether we are in a SFINAE context that is not associated with
4261  /// template instantiation.
4262  ///
4263  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
4264  /// of a template instantiation or template argument deduction.
4265  bool InNonInstantiationSFINAEContext;
4266
4267  /// \brief The number of ActiveTemplateInstantiation entries in
4268  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
4269  /// therefore, should not be counted as part of the instantiation depth.
4270  unsigned NonInstantiationEntries;
4271
4272  /// \brief The last template from which a template instantiation
4273  /// error or warning was produced.
4274  ///
4275  /// This value is used to suppress printing of redundant template
4276  /// instantiation backtraces when there are multiple errors in the
4277  /// same instantiation. FIXME: Does this belong in Sema? It's tough
4278  /// to implement it anywhere else.
4279  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
4280
4281  /// \brief The current index into pack expansion arguments that will be
4282  /// used for substitution of parameter packs.
4283  ///
4284  /// The pack expansion index will be -1 to indicate that parameter packs
4285  /// should be instantiated as themselves. Otherwise, the index specifies
4286  /// which argument within the parameter pack will be used for substitution.
4287  int ArgumentPackSubstitutionIndex;
4288
4289  /// \brief RAII object used to change the argument pack substitution index
4290  /// within a \c Sema object.
4291  ///
4292  /// See \c ArgumentPackSubstitutionIndex for more information.
4293  class ArgumentPackSubstitutionIndexRAII {
4294    Sema &Self;
4295    int OldSubstitutionIndex;
4296
4297  public:
4298    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
4299      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
4300      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
4301    }
4302
4303    ~ArgumentPackSubstitutionIndexRAII() {
4304      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
4305    }
4306  };
4307
4308  friend class ArgumentPackSubstitutionRAII;
4309
4310  /// \brief The stack of calls expression undergoing template instantiation.
4311  ///
4312  /// The top of this stack is used by a fixit instantiating unresolved
4313  /// function calls to fix the AST to match the textual change it prints.
4314  llvm::SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
4315
4316  /// \brief For each declaration that involved template argument deduction, the
4317  /// set of diagnostics that were suppressed during that template argument
4318  /// deduction.
4319  ///
4320  /// FIXME: Serialize this structure to the AST file.
4321  llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >
4322    SuppressedDiagnostics;
4323
4324  /// \brief A stack object to be created when performing template
4325  /// instantiation.
4326  ///
4327  /// Construction of an object of type \c InstantiatingTemplate
4328  /// pushes the current instantiation onto the stack of active
4329  /// instantiations. If the size of this stack exceeds the maximum
4330  /// number of recursive template instantiations, construction
4331  /// produces an error and evaluates true.
4332  ///
4333  /// Destruction of this object will pop the named instantiation off
4334  /// the stack.
4335  struct InstantiatingTemplate {
4336    /// \brief Note that we are instantiating a class template,
4337    /// function template, or a member thereof.
4338    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4339                          Decl *Entity,
4340                          SourceRange InstantiationRange = SourceRange());
4341
4342    /// \brief Note that we are instantiating a default argument in a
4343    /// template-id.
4344    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4345                          TemplateDecl *Template,
4346                          const TemplateArgument *TemplateArgs,
4347                          unsigned NumTemplateArgs,
4348                          SourceRange InstantiationRange = SourceRange());
4349
4350    /// \brief Note that we are instantiating a default argument in a
4351    /// template-id.
4352    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4353                          FunctionTemplateDecl *FunctionTemplate,
4354                          const TemplateArgument *TemplateArgs,
4355                          unsigned NumTemplateArgs,
4356                          ActiveTemplateInstantiation::InstantiationKind Kind,
4357                          sema::TemplateDeductionInfo &DeductionInfo,
4358                          SourceRange InstantiationRange = SourceRange());
4359
4360    /// \brief Note that we are instantiating as part of template
4361    /// argument deduction for a class template partial
4362    /// specialization.
4363    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4364                          ClassTemplatePartialSpecializationDecl *PartialSpec,
4365                          const TemplateArgument *TemplateArgs,
4366                          unsigned NumTemplateArgs,
4367                          sema::TemplateDeductionInfo &DeductionInfo,
4368                          SourceRange InstantiationRange = SourceRange());
4369
4370    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4371                          ParmVarDecl *Param,
4372                          const TemplateArgument *TemplateArgs,
4373                          unsigned NumTemplateArgs,
4374                          SourceRange InstantiationRange = SourceRange());
4375
4376    /// \brief Note that we are substituting prior template arguments into a
4377    /// non-type or template template parameter.
4378    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4379                          NamedDecl *Template,
4380                          NonTypeTemplateParmDecl *Param,
4381                          const TemplateArgument *TemplateArgs,
4382                          unsigned NumTemplateArgs,
4383                          SourceRange InstantiationRange);
4384
4385    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4386                          NamedDecl *Template,
4387                          TemplateTemplateParmDecl *Param,
4388                          const TemplateArgument *TemplateArgs,
4389                          unsigned NumTemplateArgs,
4390                          SourceRange InstantiationRange);
4391
4392    /// \brief Note that we are checking the default template argument
4393    /// against the template parameter for a given template-id.
4394    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4395                          TemplateDecl *Template,
4396                          NamedDecl *Param,
4397                          const TemplateArgument *TemplateArgs,
4398                          unsigned NumTemplateArgs,
4399                          SourceRange InstantiationRange);
4400
4401
4402    /// \brief Note that we have finished instantiating this template.
4403    void Clear();
4404
4405    ~InstantiatingTemplate() { Clear(); }
4406
4407    /// \brief Determines whether we have exceeded the maximum
4408    /// recursive template instantiations.
4409    operator bool() const { return Invalid; }
4410
4411  private:
4412    Sema &SemaRef;
4413    bool Invalid;
4414    bool SavedInNonInstantiationSFINAEContext;
4415    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
4416                                 SourceRange InstantiationRange);
4417
4418    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
4419
4420    InstantiatingTemplate&
4421    operator=(const InstantiatingTemplate&); // not implemented
4422  };
4423
4424  void PrintInstantiationStack();
4425
4426  /// \brief Determines whether we are currently in a context where
4427  /// template argument substitution failures are not considered
4428  /// errors.
4429  ///
4430  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
4431  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
4432  /// template-deduction context object, which can be used to capture
4433  /// diagnostics that will be suppressed.
4434  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
4435
4436  /// \brief RAII class used to determine whether SFINAE has
4437  /// trapped any errors that occur during template argument
4438  /// deduction.`
4439  class SFINAETrap {
4440    Sema &SemaRef;
4441    unsigned PrevSFINAEErrors;
4442    bool PrevInNonInstantiationSFINAEContext;
4443    bool PrevAccessCheckingSFINAE;
4444
4445  public:
4446    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
4447      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
4448        PrevInNonInstantiationSFINAEContext(
4449                                      SemaRef.InNonInstantiationSFINAEContext),
4450        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
4451    {
4452      if (!SemaRef.isSFINAEContext())
4453        SemaRef.InNonInstantiationSFINAEContext = true;
4454      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
4455    }
4456
4457    ~SFINAETrap() {
4458      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
4459      SemaRef.InNonInstantiationSFINAEContext
4460        = PrevInNonInstantiationSFINAEContext;
4461      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
4462    }
4463
4464    /// \brief Determine whether any SFINAE errors have been trapped.
4465    bool hasErrorOccurred() const {
4466      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
4467    }
4468  };
4469
4470  /// \brief The current instantiation scope used to store local
4471  /// variables.
4472  LocalInstantiationScope *CurrentInstantiationScope;
4473
4474  /// \brief The number of typos corrected by CorrectTypo.
4475  unsigned TyposCorrected;
4476
4477  typedef llvm::DenseMap<IdentifierInfo *, std::pair<llvm::StringRef, bool> >
4478    UnqualifiedTyposCorrectedMap;
4479
4480  /// \brief A cache containing the results of typo correction for unqualified
4481  /// name lookup.
4482  ///
4483  /// The string is the string that we corrected to (which may be empty, if
4484  /// there was no correction), while the boolean will be true when the
4485  /// string represents a keyword.
4486  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
4487
4488  /// \brief Worker object for performing CFG-based warnings.
4489  sema::AnalysisBasedWarnings AnalysisWarnings;
4490
4491  /// \brief An entity for which implicit template instantiation is required.
4492  ///
4493  /// The source location associated with the declaration is the first place in
4494  /// the source code where the declaration was "used". It is not necessarily
4495  /// the point of instantiation (which will be either before or after the
4496  /// namespace-scope declaration that triggered this implicit instantiation),
4497  /// However, it is the location that diagnostics should generally refer to,
4498  /// because users will need to know what code triggered the instantiation.
4499  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
4500
4501  /// \brief The queue of implicit template instantiations that are required
4502  /// but have not yet been performed.
4503  std::deque<PendingImplicitInstantiation> PendingInstantiations;
4504
4505  /// \brief The queue of implicit template instantiations that are required
4506  /// and must be performed within the current local scope.
4507  ///
4508  /// This queue is only used for member functions of local classes in
4509  /// templates, which must be instantiated in the same scope as their
4510  /// enclosing function, so that they can reference function-local
4511  /// types, static variables, enumerators, etc.
4512  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
4513
4514  bool PerformPendingInstantiations(bool LocalOnly = false);
4515
4516  TypeSourceInfo *SubstType(TypeSourceInfo *T,
4517                            const MultiLevelTemplateArgumentList &TemplateArgs,
4518                            SourceLocation Loc, DeclarationName Entity);
4519
4520  QualType SubstType(QualType T,
4521                     const MultiLevelTemplateArgumentList &TemplateArgs,
4522                     SourceLocation Loc, DeclarationName Entity);
4523
4524  TypeSourceInfo *SubstType(TypeLoc TL,
4525                            const MultiLevelTemplateArgumentList &TemplateArgs,
4526                            SourceLocation Loc, DeclarationName Entity);
4527
4528  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
4529                            const MultiLevelTemplateArgumentList &TemplateArgs,
4530                                        SourceLocation Loc,
4531                                        DeclarationName Entity);
4532  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
4533                            const MultiLevelTemplateArgumentList &TemplateArgs,
4534                                int indexAdjustment,
4535                                llvm::Optional<unsigned> NumExpansions);
4536  bool SubstParmTypes(SourceLocation Loc,
4537                      ParmVarDecl **Params, unsigned NumParams,
4538                      const MultiLevelTemplateArgumentList &TemplateArgs,
4539                      llvm::SmallVectorImpl<QualType> &ParamTypes,
4540                      llvm::SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
4541  ExprResult SubstExpr(Expr *E,
4542                       const MultiLevelTemplateArgumentList &TemplateArgs);
4543
4544  /// \brief Substitute the given template arguments into a list of
4545  /// expressions, expanding pack expansions if required.
4546  ///
4547  /// \param Exprs The list of expressions to substitute into.
4548  ///
4549  /// \param NumExprs The number of expressions in \p Exprs.
4550  ///
4551  /// \param IsCall Whether this is some form of call, in which case
4552  /// default arguments will be dropped.
4553  ///
4554  /// \param TemplateArgs The set of template arguments to substitute.
4555  ///
4556  /// \param Outputs Will receive all of the substituted arguments.
4557  ///
4558  /// \returns true if an error occurred, false otherwise.
4559  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
4560                  const MultiLevelTemplateArgumentList &TemplateArgs,
4561                  llvm::SmallVectorImpl<Expr *> &Outputs);
4562
4563  StmtResult SubstStmt(Stmt *S,
4564                       const MultiLevelTemplateArgumentList &TemplateArgs);
4565
4566  Decl *SubstDecl(Decl *D, DeclContext *Owner,
4567                  const MultiLevelTemplateArgumentList &TemplateArgs);
4568
4569  bool
4570  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
4571                      CXXRecordDecl *Pattern,
4572                      const MultiLevelTemplateArgumentList &TemplateArgs);
4573
4574  bool
4575  InstantiateClass(SourceLocation PointOfInstantiation,
4576                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
4577                   const MultiLevelTemplateArgumentList &TemplateArgs,
4578                   TemplateSpecializationKind TSK,
4579                   bool Complain = true);
4580
4581  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
4582                        Decl *Pattern, Decl *Inst);
4583
4584  bool
4585  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
4586                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4587                           TemplateSpecializationKind TSK,
4588                           bool Complain = true);
4589
4590  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
4591                               CXXRecordDecl *Instantiation,
4592                            const MultiLevelTemplateArgumentList &TemplateArgs,
4593                               TemplateSpecializationKind TSK);
4594
4595  void InstantiateClassTemplateSpecializationMembers(
4596                                          SourceLocation PointOfInstantiation,
4597                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4598                                                TemplateSpecializationKind TSK);
4599
4600  NestedNameSpecifierLoc
4601  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4602                           const MultiLevelTemplateArgumentList &TemplateArgs);
4603
4604  DeclarationNameInfo
4605  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4606                           const MultiLevelTemplateArgumentList &TemplateArgs);
4607  TemplateName
4608  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
4609                    SourceLocation Loc,
4610                    const MultiLevelTemplateArgumentList &TemplateArgs);
4611  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
4612             TemplateArgumentListInfo &Result,
4613             const MultiLevelTemplateArgumentList &TemplateArgs);
4614
4615  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4616                                     FunctionDecl *Function,
4617                                     bool Recursive = false,
4618                                     bool DefinitionRequired = false);
4619  void InstantiateStaticDataMemberDefinition(
4620                                     SourceLocation PointOfInstantiation,
4621                                     VarDecl *Var,
4622                                     bool Recursive = false,
4623                                     bool DefinitionRequired = false);
4624
4625  void InstantiateMemInitializers(CXXConstructorDecl *New,
4626                                  const CXXConstructorDecl *Tmpl,
4627                            const MultiLevelTemplateArgumentList &TemplateArgs);
4628
4629  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4630                          const MultiLevelTemplateArgumentList &TemplateArgs);
4631  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
4632                          const MultiLevelTemplateArgumentList &TemplateArgs);
4633
4634  // Objective-C declarations.
4635  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
4636                                 IdentifierInfo *ClassName,
4637                                 SourceLocation ClassLoc,
4638                                 IdentifierInfo *SuperName,
4639                                 SourceLocation SuperLoc,
4640                                 Decl * const *ProtoRefs,
4641                                 unsigned NumProtoRefs,
4642                                 const SourceLocation *ProtoLocs,
4643                                 SourceLocation EndProtoLoc,
4644                                 AttributeList *AttrList);
4645
4646  Decl *ActOnCompatiblityAlias(
4647                    SourceLocation AtCompatibilityAliasLoc,
4648                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
4649                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
4650
4651  void CheckForwardProtocolDeclarationForCircularDependency(
4652    IdentifierInfo *PName,
4653    SourceLocation &PLoc, SourceLocation PrevLoc,
4654    const ObjCList<ObjCProtocolDecl> &PList);
4655
4656  Decl *ActOnStartProtocolInterface(
4657                    SourceLocation AtProtoInterfaceLoc,
4658                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
4659                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
4660                    const SourceLocation *ProtoLocs,
4661                    SourceLocation EndProtoLoc,
4662                    AttributeList *AttrList);
4663
4664  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
4665                                    IdentifierInfo *ClassName,
4666                                    SourceLocation ClassLoc,
4667                                    IdentifierInfo *CategoryName,
4668                                    SourceLocation CategoryLoc,
4669                                    Decl * const *ProtoRefs,
4670                                    unsigned NumProtoRefs,
4671                                    const SourceLocation *ProtoLocs,
4672                                    SourceLocation EndProtoLoc);
4673
4674  Decl *ActOnStartClassImplementation(
4675                    SourceLocation AtClassImplLoc,
4676                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
4677                    IdentifierInfo *SuperClassname,
4678                    SourceLocation SuperClassLoc);
4679
4680  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
4681                                         IdentifierInfo *ClassName,
4682                                         SourceLocation ClassLoc,
4683                                         IdentifierInfo *CatName,
4684                                         SourceLocation CatLoc);
4685
4686  Decl *ActOnForwardClassDeclaration(SourceLocation Loc,
4687                                     IdentifierInfo **IdentList,
4688                                     SourceLocation *IdentLocs,
4689                                     unsigned NumElts);
4690
4691  Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
4692                                        const IdentifierLocPair *IdentList,
4693                                        unsigned NumElts,
4694                                        AttributeList *attrList);
4695
4696  void FindProtocolDeclaration(bool WarnOnDeclarations,
4697                               const IdentifierLocPair *ProtocolId,
4698                               unsigned NumProtocols,
4699                               llvm::SmallVectorImpl<Decl *> &Protocols);
4700
4701  /// Ensure attributes are consistent with type.
4702  /// \param [in, out] Attributes The attributes to check; they will
4703  /// be modified to be consistent with \arg PropertyTy.
4704  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
4705                                   SourceLocation Loc,
4706                                   unsigned &Attributes);
4707
4708  /// Process the specified property declaration and create decls for the
4709  /// setters and getters as needed.
4710  /// \param property The property declaration being processed
4711  /// \param DC The semantic container for the property
4712  /// \param redeclaredProperty Declaration for property if redeclared
4713  ///        in class extension.
4714  /// \param lexicalDC Container for redeclaredProperty.
4715  void ProcessPropertyDecl(ObjCPropertyDecl *property,
4716                           ObjCContainerDecl *DC,
4717                           ObjCPropertyDecl *redeclaredProperty = 0,
4718                           ObjCContainerDecl *lexicalDC = 0);
4719
4720  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
4721                                ObjCPropertyDecl *SuperProperty,
4722                                const IdentifierInfo *Name);
4723  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
4724
4725  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
4726                                         ObjCMethodDecl *MethodDecl,
4727                                         bool IsInstance);
4728
4729  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
4730
4731  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
4732                                        ObjCInterfaceDecl *ID);
4733
4734  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
4735                                         ObjCProtocolDecl *PDecl);
4736
4737  void ActOnAtEnd(Scope *S, SourceRange AtEnd, Decl *classDecl,
4738                  Decl **allMethods = 0, unsigned allNum = 0,
4739                  Decl **allProperties = 0, unsigned pNum = 0,
4740                  DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
4741
4742  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
4743                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
4744                      Selector GetterSel, Selector SetterSel,
4745                      Decl *ClassCategory,
4746                      bool *OverridingProperty,
4747                      tok::ObjCKeywordKind MethodImplKind,
4748                      DeclContext *lexicalDC = 0);
4749
4750  Decl *ActOnPropertyImplDecl(Scope *S,
4751                              SourceLocation AtLoc,
4752                              SourceLocation PropertyLoc,
4753                              bool ImplKind,Decl *ClassImplDecl,
4754                              IdentifierInfo *PropertyId,
4755                              IdentifierInfo *PropertyIvar,
4756                              SourceLocation PropertyIvarLoc);
4757
4758  struct ObjCArgInfo {
4759    IdentifierInfo *Name;
4760    SourceLocation NameLoc;
4761    // The Type is null if no type was specified, and the DeclSpec is invalid
4762    // in this case.
4763    ParsedType Type;
4764    ObjCDeclSpec DeclSpec;
4765
4766    /// ArgAttrs - Attribute list for this argument.
4767    AttributeList *ArgAttrs;
4768  };
4769
4770  Decl *ActOnMethodDeclaration(
4771    Scope *S,
4772    SourceLocation BeginLoc, // location of the + or -.
4773    SourceLocation EndLoc,   // location of the ; or {.
4774    tok::TokenKind MethodType,
4775    Decl *ClassDecl, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4776    Selector Sel,
4777    // optional arguments. The number of types/arguments is obtained
4778    // from the Sel.getNumArgs().
4779    ObjCArgInfo *ArgInfo,
4780    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
4781    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
4782    bool isVariadic, bool MethodDefinition);
4783
4784  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
4785  // Will search "local" class/category implementations for a method decl.
4786  // Will also search in class's root looking for instance method.
4787  // Returns 0 if no method is found.
4788  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
4789                                           ObjCInterfaceDecl *CDecl);
4790  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
4791                                              ObjCInterfaceDecl *ClassDecl);
4792  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
4793                                              const ObjCObjectPointerType *OPT,
4794                                              bool IsInstance);
4795
4796  ExprResult
4797  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
4798                            Expr *BaseExpr,
4799                            DeclarationName MemberName,
4800                            SourceLocation MemberLoc,
4801                            SourceLocation SuperLoc, QualType SuperType,
4802                            bool Super);
4803
4804  ExprResult
4805  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
4806                            IdentifierInfo &propertyName,
4807                            SourceLocation receiverNameLoc,
4808                            SourceLocation propertyNameLoc);
4809
4810  ObjCMethodDecl *tryCaptureObjCSelf();
4811
4812  /// \brief Describes the kind of message expression indicated by a message
4813  /// send that starts with an identifier.
4814  enum ObjCMessageKind {
4815    /// \brief The message is sent to 'super'.
4816    ObjCSuperMessage,
4817    /// \brief The message is an instance message.
4818    ObjCInstanceMessage,
4819    /// \brief The message is a class message, and the identifier is a type
4820    /// name.
4821    ObjCClassMessage
4822  };
4823
4824  ObjCMessageKind getObjCMessageKind(Scope *S,
4825                                     IdentifierInfo *Name,
4826                                     SourceLocation NameLoc,
4827                                     bool IsSuper,
4828                                     bool HasTrailingDot,
4829                                     ParsedType &ReceiverType);
4830
4831  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
4832                               Selector Sel,
4833                               SourceLocation LBracLoc,
4834                               SourceLocation SelectorLoc,
4835                               SourceLocation RBracLoc,
4836                               MultiExprArg Args);
4837
4838  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
4839                               QualType ReceiverType,
4840                               SourceLocation SuperLoc,
4841                               Selector Sel,
4842                               ObjCMethodDecl *Method,
4843                               SourceLocation LBracLoc,
4844                               SourceLocation SelectorLoc,
4845                               SourceLocation RBracLoc,
4846                               MultiExprArg Args);
4847
4848  ExprResult ActOnClassMessage(Scope *S,
4849                               ParsedType Receiver,
4850                               Selector Sel,
4851                               SourceLocation LBracLoc,
4852                               SourceLocation SelectorLoc,
4853                               SourceLocation RBracLoc,
4854                               MultiExprArg Args);
4855
4856  ExprResult BuildInstanceMessage(Expr *Receiver,
4857                                  QualType ReceiverType,
4858                                  SourceLocation SuperLoc,
4859                                  Selector Sel,
4860                                  ObjCMethodDecl *Method,
4861                                  SourceLocation LBracLoc,
4862                                  SourceLocation SelectorLoc,
4863                                  SourceLocation RBracLoc,
4864                                  MultiExprArg Args);
4865
4866  ExprResult ActOnInstanceMessage(Scope *S,
4867                                  Expr *Receiver,
4868                                  Selector Sel,
4869                                  SourceLocation LBracLoc,
4870                                  SourceLocation SelectorLoc,
4871                                  SourceLocation RBracLoc,
4872                                  MultiExprArg Args);
4873
4874
4875  enum PragmaOptionsAlignKind {
4876    POAK_Native,  // #pragma options align=native
4877    POAK_Natural, // #pragma options align=natural
4878    POAK_Packed,  // #pragma options align=packed
4879    POAK_Power,   // #pragma options align=power
4880    POAK_Mac68k,  // #pragma options align=mac68k
4881    POAK_Reset    // #pragma options align=reset
4882  };
4883
4884  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
4885  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
4886                               SourceLocation PragmaLoc,
4887                               SourceLocation KindLoc);
4888
4889  enum PragmaPackKind {
4890    PPK_Default, // #pragma pack([n])
4891    PPK_Show,    // #pragma pack(show), only supported by MSVC.
4892    PPK_Push,    // #pragma pack(push, [identifier], [n])
4893    PPK_Pop      // #pragma pack(pop, [identifier], [n])
4894  };
4895
4896  enum PragmaMSStructKind {
4897    PMSST_OFF,  // #pragms ms_struct off
4898    PMSST_ON    // #pragms ms_struct on
4899  };
4900
4901  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
4902  void ActOnPragmaPack(PragmaPackKind Kind,
4903                       IdentifierInfo *Name,
4904                       Expr *Alignment,
4905                       SourceLocation PragmaLoc,
4906                       SourceLocation LParenLoc,
4907                       SourceLocation RParenLoc);
4908
4909  /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
4910  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
4911
4912  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
4913  void ActOnPragmaUnused(const Token &Identifier,
4914                         Scope *curScope,
4915                         SourceLocation PragmaLoc);
4916
4917  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
4918  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
4919                             SourceLocation PragmaLoc);
4920
4921  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II);
4922  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
4923
4924  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
4925  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
4926                         SourceLocation PragmaLoc,
4927                         SourceLocation WeakNameLoc);
4928
4929  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
4930  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
4931                            IdentifierInfo* AliasName,
4932                            SourceLocation PragmaLoc,
4933                            SourceLocation WeakNameLoc,
4934                            SourceLocation AliasNameLoc);
4935
4936  /// ActOnPragmaFPContract - Called on well formed
4937  /// #pragma {STDC,OPENCL} FP_CONTRACT
4938  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
4939
4940  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
4941  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
4942  void AddAlignmentAttributesForRecord(RecordDecl *RD);
4943
4944  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
4945  void AddMsStructLayoutForRecord(RecordDecl *RD);
4946
4947  /// FreePackedContext - Deallocate and null out PackContext.
4948  void FreePackedContext();
4949
4950  /// PushNamespaceVisibilityAttr - Note that we've entered a
4951  /// namespace with a visibility attribute.
4952  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
4953
4954  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
4955  /// add an appropriate visibility attribute.
4956  void AddPushedVisibilityAttribute(Decl *RD);
4957
4958  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
4959  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
4960  void PopPragmaVisibility();
4961
4962  /// FreeVisContext - Deallocate and null out VisContext.
4963  void FreeVisContext();
4964
4965  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
4966  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E);
4967  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T);
4968
4969  /// CastCategory - Get the correct forwarded implicit cast result category
4970  /// from the inner expression.
4971  ExprValueKind CastCategory(Expr *E);
4972
4973  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
4974  /// cast.  If there is already an implicit cast, merge into the existing one.
4975  /// If isLvalue, the result of the cast is an lvalue.
4976  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
4977                               ExprValueKind VK = VK_RValue,
4978                               const CXXCastPath *BasePath = 0);
4979
4980  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
4981  /// to the conversion from scalar type ScalarTy to the Boolean type.
4982  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
4983
4984  /// IgnoredValueConversions - Given that an expression's result is
4985  /// syntactically ignored, perform any conversions that are
4986  /// required.
4987  ExprResult IgnoredValueConversions(Expr *E);
4988
4989  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
4990  // functions and arrays to their respective pointers (C99 6.3.2.1).
4991  ExprResult UsualUnaryConversions(Expr *E);
4992
4993  // DefaultFunctionArrayConversion - converts functions and arrays
4994  // to their respective pointers (C99 6.3.2.1).
4995  ExprResult DefaultFunctionArrayConversion(Expr *E);
4996
4997  // DefaultFunctionArrayLvalueConversion - converts functions and
4998  // arrays to their respective pointers and performs the
4999  // lvalue-to-rvalue conversion.
5000  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
5001
5002  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
5003  // the operand.  This is DefaultFunctionArrayLvalueConversion,
5004  // except that it assumes the operand isn't of function or array
5005  // type.
5006  ExprResult DefaultLvalueConversion(Expr *E);
5007
5008  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
5009  // do not have a prototype. Integer promotions are performed on each
5010  // argument, and arguments that have type float are promoted to double.
5011  ExprResult DefaultArgumentPromotion(Expr *E);
5012
5013  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
5014  enum VariadicCallType {
5015    VariadicFunction,
5016    VariadicBlock,
5017    VariadicMethod,
5018    VariadicConstructor,
5019    VariadicDoesNotApply
5020  };
5021
5022  /// GatherArgumentsForCall - Collector argument expressions for various
5023  /// form of call prototypes.
5024  bool GatherArgumentsForCall(SourceLocation CallLoc,
5025                              FunctionDecl *FDecl,
5026                              const FunctionProtoType *Proto,
5027                              unsigned FirstProtoArg,
5028                              Expr **Args, unsigned NumArgs,
5029                              llvm::SmallVector<Expr *, 8> &AllArgs,
5030                              VariadicCallType CallType = VariadicDoesNotApply);
5031
5032  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
5033  // will warn if the resulting type is not a POD type.
5034  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
5035                                              FunctionDecl *FDecl);
5036
5037  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
5038  // operands and then handles various conversions that are common to binary
5039  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
5040  // routine returns the first non-arithmetic type found. The client is
5041  // responsible for emitting appropriate error diagnostics.
5042  QualType UsualArithmeticConversions(ExprResult &lExpr, ExprResult &rExpr,
5043                                      bool isCompAssign = false);
5044
5045  /// AssignConvertType - All of the 'assignment' semantic checks return this
5046  /// enum to indicate whether the assignment was allowed.  These checks are
5047  /// done for simple assignments, as well as initialization, return from
5048  /// function, argument passing, etc.  The query is phrased in terms of a
5049  /// source and destination type.
5050  enum AssignConvertType {
5051    /// Compatible - the types are compatible according to the standard.
5052    Compatible,
5053
5054    /// PointerToInt - The assignment converts a pointer to an int, which we
5055    /// accept as an extension.
5056    PointerToInt,
5057
5058    /// IntToPointer - The assignment converts an int to a pointer, which we
5059    /// accept as an extension.
5060    IntToPointer,
5061
5062    /// FunctionVoidPointer - The assignment is between a function pointer and
5063    /// void*, which the standard doesn't allow, but we accept as an extension.
5064    FunctionVoidPointer,
5065
5066    /// IncompatiblePointer - The assignment is between two pointers types that
5067    /// are not compatible, but we accept them as an extension.
5068    IncompatiblePointer,
5069
5070    /// IncompatiblePointer - The assignment is between two pointers types which
5071    /// point to integers which have a different sign, but are otherwise identical.
5072    /// This is a subset of the above, but broken out because it's by far the most
5073    /// common case of incompatible pointers.
5074    IncompatiblePointerSign,
5075
5076    /// CompatiblePointerDiscardsQualifiers - The assignment discards
5077    /// c/v/r qualifiers, which we accept as an extension.
5078    CompatiblePointerDiscardsQualifiers,
5079
5080    /// IncompatiblePointerDiscardsQualifiers - The assignment
5081    /// discards qualifiers that we don't permit to be discarded,
5082    /// like address spaces.
5083    IncompatiblePointerDiscardsQualifiers,
5084
5085    /// IncompatibleNestedPointerQualifiers - The assignment is between two
5086    /// nested pointer types, and the qualifiers other than the first two
5087    /// levels differ e.g. char ** -> const char **, but we accept them as an
5088    /// extension.
5089    IncompatibleNestedPointerQualifiers,
5090
5091    /// IncompatibleVectors - The assignment is between two vector types that
5092    /// have the same size, which we accept as an extension.
5093    IncompatibleVectors,
5094
5095    /// IntToBlockPointer - The assignment converts an int to a block
5096    /// pointer. We disallow this.
5097    IntToBlockPointer,
5098
5099    /// IncompatibleBlockPointer - The assignment is between two block
5100    /// pointers types that are not compatible.
5101    IncompatibleBlockPointer,
5102
5103    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
5104    /// id type and something else (that is incompatible with it). For example,
5105    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
5106    IncompatibleObjCQualifiedId,
5107
5108    /// Incompatible - We reject this conversion outright, it is invalid to
5109    /// represent it in the AST.
5110    Incompatible
5111  };
5112
5113  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
5114  /// assignment conversion type specified by ConvTy.  This returns true if the
5115  /// conversion was invalid or false if the conversion was accepted.
5116  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
5117                                SourceLocation Loc,
5118                                QualType DstType, QualType SrcType,
5119                                Expr *SrcExpr, AssignmentAction Action,
5120                                bool *Complained = 0);
5121
5122  /// CheckAssignmentConstraints - Perform type checking for assignment,
5123  /// argument passing, variable initialization, and function return values.
5124  /// C99 6.5.16.
5125  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
5126                                               QualType lhs, QualType rhs);
5127
5128  /// Check assignment constraints and prepare for a conversion of the
5129  /// RHS to the LHS type.
5130  AssignConvertType CheckAssignmentConstraints(QualType lhs, ExprResult &rhs,
5131                                               CastKind &Kind);
5132
5133  // CheckSingleAssignmentConstraints - Currently used by
5134  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
5135  // this routine performs the default function/array converions.
5136  AssignConvertType CheckSingleAssignmentConstraints(QualType lhs,
5137                                                     ExprResult &rExprRes);
5138
5139  // \brief If the lhs type is a transparent union, check whether we
5140  // can initialize the transparent union with the given expression.
5141  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType lhs,
5142                                                             ExprResult &rExpr);
5143
5144  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
5145
5146  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
5147
5148  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5149                                       AssignmentAction Action,
5150                                       bool AllowExplicit = false);
5151  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5152                                       AssignmentAction Action,
5153                                       bool AllowExplicit,
5154                                       ImplicitConversionSequence& ICS);
5155  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5156                                       const ImplicitConversionSequence& ICS,
5157                                       AssignmentAction Action,
5158                                       bool CStyle = false);
5159  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5160                                       const StandardConversionSequence& SCS,
5161                                       AssignmentAction Action,
5162                                       bool CStyle);
5163
5164  /// the following "Check" methods will return a valid/converted QualType
5165  /// or a null QualType (indicating an error diagnostic was issued).
5166
5167  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
5168  QualType InvalidOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
5169  QualType CheckPointerToMemberOperands( // C++ 5.5
5170    ExprResult &lex, ExprResult &rex, ExprValueKind &VK,
5171    SourceLocation OpLoc, bool isIndirect);
5172  QualType CheckMultiplyDivideOperands( // C99 6.5.5
5173    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign,
5174                                       bool isDivide);
5175  QualType CheckRemainderOperands( // C99 6.5.5
5176    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
5177  QualType CheckAdditionOperands( // C99 6.5.6
5178    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
5179  QualType CheckSubtractionOperands( // C99 6.5.6
5180    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
5181  QualType CheckShiftOperands( // C99 6.5.7
5182    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
5183    bool isCompAssign = false);
5184  QualType CheckCompareOperands( // C99 6.5.8/9
5185    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
5186                                bool isRelational);
5187  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
5188    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
5189  QualType CheckLogicalOperands( // C99 6.5.[13,14]
5190    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc);
5191  // CheckAssignmentOperands is used for both simple and compound assignment.
5192  // For simple assignment, pass both expressions and a null converted type.
5193  // For compound assignment, pass both expressions and the converted type.
5194  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
5195    Expr *lex, ExprResult &rex, SourceLocation OpLoc, QualType convertedType);
5196
5197  void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType& LHSTy);
5198  ExprResult ConvertPropertyForRValue(Expr *E);
5199
5200  QualType CheckConditionalOperands( // C99 6.5.15
5201    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5202    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5203  QualType CXXCheckConditionalOperands( // C++ 5.16
5204    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5205    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5206  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
5207                                    bool *NonStandardCompositeType = 0);
5208  QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2,
5209                                    bool *NonStandardCompositeType = 0) {
5210    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
5211    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType);
5212    E1 = Owned(E1Tmp);
5213    E2 = Owned(E2Tmp);
5214    return Composite;
5215  }
5216
5217  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5218                                        SourceLocation questionLoc);
5219
5220  bool DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5221                                  SourceLocation QuestionLoc);
5222
5223  /// type checking for vector binary operators.
5224  QualType CheckVectorOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
5225  QualType CheckVectorCompareOperands(ExprResult &lex, ExprResult &rx,
5226                                      SourceLocation l, bool isRel);
5227
5228  /// type checking declaration initializers (C99 6.7.8)
5229  bool CheckInitList(const InitializedEntity &Entity,
5230                     InitListExpr *&InitList, QualType &DeclType);
5231  bool CheckForConstantInitializer(Expr *e, QualType t);
5232
5233  // type checking C++ declaration initializers (C++ [dcl.init]).
5234
5235  /// ReferenceCompareResult - Expresses the result of comparing two
5236  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
5237  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
5238  enum ReferenceCompareResult {
5239    /// Ref_Incompatible - The two types are incompatible, so direct
5240    /// reference binding is not possible.
5241    Ref_Incompatible = 0,
5242    /// Ref_Related - The two types are reference-related, which means
5243    /// that their unqualified forms (T1 and T2) are either the same
5244    /// or T1 is a base class of T2.
5245    Ref_Related,
5246    /// Ref_Compatible_With_Added_Qualification - The two types are
5247    /// reference-compatible with added qualification, meaning that
5248    /// they are reference-compatible and the qualifiers on T1 (cv1)
5249    /// are greater than the qualifiers on T2 (cv2).
5250    Ref_Compatible_With_Added_Qualification,
5251    /// Ref_Compatible - The two types are reference-compatible and
5252    /// have equivalent qualifiers (cv1 == cv2).
5253    Ref_Compatible
5254  };
5255
5256  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
5257                                                      QualType T1, QualType T2,
5258                                                      bool &DerivedToBase,
5259                                                      bool &ObjCConversion);
5260
5261  /// CheckCastTypes - Check type constraints for casting between types under
5262  /// C semantics, or forward to CXXCheckCStyleCast in C++.
5263  ExprResult CheckCastTypes(SourceRange TyRange, QualType CastTy, Expr *CastExpr,
5264                            CastKind &Kind, ExprValueKind &VK, CXXCastPath &BasePath,
5265                            bool FunctionalStyle = false);
5266
5267  ExprResult checkUnknownAnyCast(SourceRange TyRange, QualType castType,
5268                                 Expr *castExpr, CastKind &castKind,
5269                                 ExprValueKind &valueKind, CXXCastPath &BasePath);
5270
5271  // CheckVectorCast - check type constraints for vectors.
5272  // Since vectors are an extension, there are no C standard reference for this.
5273  // We allow casting between vectors and integer datatypes of the same size.
5274  // returns true if the cast is invalid
5275  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5276                       CastKind &Kind);
5277
5278  // CheckExtVectorCast - check type constraints for extended vectors.
5279  // Since vectors are an extension, there are no C standard reference for this.
5280  // We allow casting between vectors and integer datatypes of the same size,
5281  // or vectors and the element type of that vector.
5282  // returns the cast expr
5283  ExprResult CheckExtVectorCast(SourceRange R, QualType VectorTy, Expr *CastExpr,
5284                                CastKind &Kind);
5285
5286  /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
5287  /// cast under C++ semantics.
5288  ExprResult CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
5289                                Expr *CastExpr, CastKind &Kind,
5290                                CXXCastPath &BasePath, bool FunctionalStyle);
5291
5292  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
5293  /// \param Method - May be null.
5294  /// \param [out] ReturnType - The return type of the send.
5295  /// \return true iff there were any incompatible types.
5296  bool CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, Selector Sel,
5297                                 ObjCMethodDecl *Method, bool isClassMessage,
5298                                 SourceLocation lbrac, SourceLocation rbrac,
5299                                 QualType &ReturnType, ExprValueKind &VK);
5300
5301  /// CheckBooleanCondition - Diagnose problems involving the use of
5302  /// the given expression as a boolean condition (e.g. in an if
5303  /// statement).  Also performs the standard function and array
5304  /// decays, possibly changing the input variable.
5305  ///
5306  /// \param Loc - A location associated with the condition, e.g. the
5307  /// 'if' keyword.
5308  /// \return true iff there were any errors
5309  ExprResult CheckBooleanCondition(Expr *CondExpr, SourceLocation Loc);
5310
5311  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
5312                                           Expr *SubExpr);
5313
5314  /// DiagnoseAssignmentAsCondition - Given that an expression is
5315  /// being used as a boolean condition, warn if it's an assignment.
5316  void DiagnoseAssignmentAsCondition(Expr *E);
5317
5318  /// \brief Redundant parentheses over an equality comparison can indicate
5319  /// that the user intended an assignment used as condition.
5320  void DiagnoseEqualityWithExtraParens(ParenExpr *parenE);
5321
5322  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
5323  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
5324
5325  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
5326  /// the specified width and sign.  If an overflow occurs, detect it and emit
5327  /// the specified diagnostic.
5328  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
5329                                          unsigned NewWidth, bool NewSign,
5330                                          SourceLocation Loc, unsigned DiagID);
5331
5332  /// Checks that the Objective-C declaration is declared in the global scope.
5333  /// Emits an error and marks the declaration as invalid if it's not declared
5334  /// in the global scope.
5335  bool CheckObjCDeclScope(Decl *D);
5336
5337  /// VerifyIntegerConstantExpression - verifies that an expression is an ICE,
5338  /// and reports the appropriate diagnostics. Returns false on success.
5339  /// Can optionally return the value of the expression.
5340  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0);
5341
5342  /// VerifyBitField - verifies that a bit field expression is an ICE and has
5343  /// the correct width, and that the field type is valid.
5344  /// Returns false on success.
5345  /// Can optionally return whether the bit-field is of width 0
5346  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5347                      QualType FieldTy, const Expr *BitWidth,
5348                      bool *ZeroWidth = 0);
5349
5350  /// \name Code completion
5351  //@{
5352  /// \brief Describes the context in which code completion occurs.
5353  enum ParserCompletionContext {
5354    /// \brief Code completion occurs at top-level or namespace context.
5355    PCC_Namespace,
5356    /// \brief Code completion occurs within a class, struct, or union.
5357    PCC_Class,
5358    /// \brief Code completion occurs within an Objective-C interface, protocol,
5359    /// or category.
5360    PCC_ObjCInterface,
5361    /// \brief Code completion occurs within an Objective-C implementation or
5362    /// category implementation
5363    PCC_ObjCImplementation,
5364    /// \brief Code completion occurs within the list of instance variables
5365    /// in an Objective-C interface, protocol, category, or implementation.
5366    PCC_ObjCInstanceVariableList,
5367    /// \brief Code completion occurs following one or more template
5368    /// headers.
5369    PCC_Template,
5370    /// \brief Code completion occurs following one or more template
5371    /// headers within a class.
5372    PCC_MemberTemplate,
5373    /// \brief Code completion occurs within an expression.
5374    PCC_Expression,
5375    /// \brief Code completion occurs within a statement, which may
5376    /// also be an expression or a declaration.
5377    PCC_Statement,
5378    /// \brief Code completion occurs at the beginning of the
5379    /// initialization statement (or expression) in a for loop.
5380    PCC_ForInit,
5381    /// \brief Code completion occurs within the condition of an if,
5382    /// while, switch, or for statement.
5383    PCC_Condition,
5384    /// \brief Code completion occurs within the body of a function on a
5385    /// recovery path, where we do not have a specific handle on our position
5386    /// in the grammar.
5387    PCC_RecoveryInFunction,
5388    /// \brief Code completion occurs where only a type is permitted.
5389    PCC_Type,
5390    /// \brief Code completion occurs in a parenthesized expression, which
5391    /// might also be a type cast.
5392    PCC_ParenthesizedExpression,
5393    /// \brief Code completion occurs within a sequence of declaration
5394    /// specifiers within a function, method, or block.
5395    PCC_LocalDeclarationSpecifiers
5396  };
5397
5398  void CodeCompleteOrdinaryName(Scope *S,
5399                                ParserCompletionContext CompletionContext);
5400  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
5401                            bool AllowNonIdentifiers,
5402                            bool AllowNestedNameSpecifiers);
5403
5404  struct CodeCompleteExpressionData;
5405  void CodeCompleteExpression(Scope *S,
5406                              const CodeCompleteExpressionData &Data);
5407  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5408                                       SourceLocation OpLoc,
5409                                       bool IsArrow);
5410  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
5411  void CodeCompleteTag(Scope *S, unsigned TagSpec);
5412  void CodeCompleteTypeQualifiers(DeclSpec &DS);
5413  void CodeCompleteCase(Scope *S);
5414  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
5415  void CodeCompleteInitializer(Scope *S, Decl *D);
5416  void CodeCompleteReturn(Scope *S);
5417  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
5418
5419  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
5420                               bool EnteringContext);
5421  void CodeCompleteUsing(Scope *S);
5422  void CodeCompleteUsingDirective(Scope *S);
5423  void CodeCompleteNamespaceDecl(Scope *S);
5424  void CodeCompleteNamespaceAliasDecl(Scope *S);
5425  void CodeCompleteOperatorName(Scope *S);
5426  void CodeCompleteConstructorInitializer(Decl *Constructor,
5427                                          CXXCtorInitializer** Initializers,
5428                                          unsigned NumInitializers);
5429
5430  void CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
5431                                   bool InInterface);
5432  void CodeCompleteObjCAtVisibility(Scope *S);
5433  void CodeCompleteObjCAtStatement(Scope *S);
5434  void CodeCompleteObjCAtExpression(Scope *S);
5435  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
5436  void CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl);
5437  void CodeCompleteObjCPropertySetter(Scope *S, Decl *ClassDecl);
5438  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5439                                   bool IsParameter);
5440  void CodeCompleteObjCMessageReceiver(Scope *S);
5441  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5442                                    IdentifierInfo **SelIdents,
5443                                    unsigned NumSelIdents,
5444                                    bool AtArgumentExpression);
5445  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5446                                    IdentifierInfo **SelIdents,
5447                                    unsigned NumSelIdents,
5448                                    bool AtArgumentExpression,
5449                                    bool IsSuper = false);
5450  void CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
5451                                       IdentifierInfo **SelIdents,
5452                                       unsigned NumSelIdents,
5453                                       bool AtArgumentExpression,
5454                                       ObjCInterfaceDecl *Super = 0);
5455  void CodeCompleteObjCForCollection(Scope *S,
5456                                     DeclGroupPtrTy IterationVar);
5457  void CodeCompleteObjCSelector(Scope *S,
5458                                IdentifierInfo **SelIdents,
5459                                unsigned NumSelIdents);
5460  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5461                                          unsigned NumProtocols);
5462  void CodeCompleteObjCProtocolDecl(Scope *S);
5463  void CodeCompleteObjCInterfaceDecl(Scope *S);
5464  void CodeCompleteObjCSuperclass(Scope *S,
5465                                  IdentifierInfo *ClassName,
5466                                  SourceLocation ClassNameLoc);
5467  void CodeCompleteObjCImplementationDecl(Scope *S);
5468  void CodeCompleteObjCInterfaceCategory(Scope *S,
5469                                         IdentifierInfo *ClassName,
5470                                         SourceLocation ClassNameLoc);
5471  void CodeCompleteObjCImplementationCategory(Scope *S,
5472                                              IdentifierInfo *ClassName,
5473                                              SourceLocation ClassNameLoc);
5474  void CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl);
5475  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5476                                              IdentifierInfo *PropertyName,
5477                                              Decl *ObjCImpDecl);
5478  void CodeCompleteObjCMethodDecl(Scope *S,
5479                                  bool IsInstanceMethod,
5480                                  ParsedType ReturnType,
5481                                  Decl *IDecl);
5482  void CodeCompleteObjCMethodDeclSelector(Scope *S,
5483                                          bool IsInstanceMethod,
5484                                          bool AtParameterName,
5485                                          ParsedType ReturnType,
5486                                          IdentifierInfo **SelIdents,
5487                                          unsigned NumSelIdents);
5488  void CodeCompletePreprocessorDirective(bool InConditional);
5489  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
5490  void CodeCompletePreprocessorMacroName(bool IsDefinition);
5491  void CodeCompletePreprocessorExpression();
5492  void CodeCompletePreprocessorMacroArgument(Scope *S,
5493                                             IdentifierInfo *Macro,
5494                                             MacroInfo *MacroInfo,
5495                                             unsigned Argument);
5496  void CodeCompleteNaturalLanguage();
5497  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
5498                  llvm::SmallVectorImpl<CodeCompletionResult> &Results);
5499  //@}
5500
5501  void PrintStats() const {}
5502
5503  //===--------------------------------------------------------------------===//
5504  // Extra semantic analysis beyond the C type system
5505
5506public:
5507  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
5508                                                unsigned ByteNo) const;
5509
5510private:
5511  void CheckArrayAccess(const Expr *E);
5512  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
5513  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
5514
5515  bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
5516  bool CheckObjCString(Expr *Arg);
5517
5518  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5519  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5520
5521  bool SemaBuiltinVAStart(CallExpr *TheCall);
5522  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
5523  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
5524
5525public:
5526  // Used by C++ template instantiation.
5527  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
5528
5529private:
5530  bool SemaBuiltinPrefetch(CallExpr *TheCall);
5531  bool SemaBuiltinObjectSize(CallExpr *TheCall);
5532  bool SemaBuiltinLongjmp(CallExpr *TheCall);
5533  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
5534  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5535                              llvm::APSInt &Result);
5536
5537  bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
5538                              bool HasVAListArg, unsigned format_idx,
5539                              unsigned firstDataArg, bool isPrintf);
5540
5541  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
5542                         const CallExpr *TheCall, bool HasVAListArg,
5543                         unsigned format_idx, unsigned firstDataArg,
5544                         bool isPrintf);
5545
5546  void CheckNonNullArguments(const NonNullAttr *NonNull,
5547                             const Expr * const *ExprArgs,
5548                             SourceLocation CallSiteLoc);
5549
5550  void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
5551                                 unsigned format_idx, unsigned firstDataArg,
5552                                 bool isPrintf);
5553
5554  void CheckMemsetArguments(const CallExpr *Call);
5555
5556  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
5557                            SourceLocation ReturnLoc);
5558  void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex);
5559  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
5560
5561  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
5562                                   Expr *Init);
5563
5564  /// \brief The parser's current scope.
5565  ///
5566  /// The parser maintains this state here.
5567  Scope *CurScope;
5568
5569protected:
5570  friend class Parser;
5571  friend class InitializationSequence;
5572
5573  /// \brief Retrieve the parser's current scope.
5574  Scope *getCurScope() const { return CurScope; }
5575};
5576
5577/// \brief RAII object that enters a new expression evaluation context.
5578class EnterExpressionEvaluationContext {
5579  Sema &Actions;
5580
5581public:
5582  EnterExpressionEvaluationContext(Sema &Actions,
5583                                   Sema::ExpressionEvaluationContext NewContext)
5584    : Actions(Actions) {
5585    Actions.PushExpressionEvaluationContext(NewContext);
5586  }
5587
5588  ~EnterExpressionEvaluationContext() {
5589    Actions.PopExpressionEvaluationContext();
5590  }
5591};
5592
5593}  // end namespace clang
5594
5595#endif
5596