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