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