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