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