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