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