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