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