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