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