Sema.h revision c640058aa7f224a71ce3b1d2601d84e1b57f82d3
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  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) {
939    return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR));
940  }
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  ExprResult
3028  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
3029                                           SourceLocation nameLoc,
3030                                           IndirectFieldDecl *indirectField,
3031                                           Expr *baseObjectExpr = 0,
3032                                      SourceLocation opLoc = SourceLocation());
3033  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3034                                             SourceLocation TemplateKWLoc,
3035                                             LookupResult &R,
3036                                const TemplateArgumentListInfo *TemplateArgs);
3037  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3038                                     SourceLocation TemplateKWLoc,
3039                                     LookupResult &R,
3040                                const TemplateArgumentListInfo *TemplateArgs,
3041                                     bool IsDefiniteInstance);
3042  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3043                                  const LookupResult &R,
3044                                  bool HasTrailingLParen);
3045
3046  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3047                                         const DeclarationNameInfo &NameInfo,
3048                                               bool IsAddressOfOperand);
3049  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3050                                       SourceLocation TemplateKWLoc,
3051                                const DeclarationNameInfo &NameInfo,
3052                                const TemplateArgumentListInfo *TemplateArgs);
3053
3054  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3055                                      LookupResult &R,
3056                                      bool NeedsADL);
3057  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3058                                      const DeclarationNameInfo &NameInfo,
3059                                      NamedDecl *D);
3060
3061  ExprResult BuildLiteralOperatorCall(LookupResult &R,
3062                                      DeclarationNameInfo &SuffixInfo,
3063                                      ArrayRef<Expr*> Args,
3064                                      SourceLocation LitEndLoc,
3065                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
3066
3067  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3068  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3069  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
3070  ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
3071  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3072  ExprResult ActOnParenListExpr(SourceLocation L,
3073                                SourceLocation R,
3074                                MultiExprArg Val);
3075
3076  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3077  /// fragments (e.g. "foo" "bar" L"baz").
3078  ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
3079                                Scope *UDLScope = 0);
3080
3081  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3082                                       SourceLocation DefaultLoc,
3083                                       SourceLocation RParenLoc,
3084                                       Expr *ControllingExpr,
3085                                       MultiTypeArg ArgTypes,
3086                                       MultiExprArg ArgExprs);
3087  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3088                                        SourceLocation DefaultLoc,
3089                                        SourceLocation RParenLoc,
3090                                        Expr *ControllingExpr,
3091                                        TypeSourceInfo **Types,
3092                                        Expr **Exprs,
3093                                        unsigned NumAssocs);
3094
3095  // Binary/Unary Operators.  'Tok' is the token for the operator.
3096  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3097                                  Expr *InputExpr);
3098  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3099                          UnaryOperatorKind Opc, Expr *Input);
3100  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3101                          tok::TokenKind Op, Expr *Input);
3102
3103  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3104                                            SourceLocation OpLoc,
3105                                            UnaryExprOrTypeTrait ExprKind,
3106                                            SourceRange R);
3107  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3108                                            UnaryExprOrTypeTrait ExprKind);
3109  ExprResult
3110    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3111                                  UnaryExprOrTypeTrait ExprKind,
3112                                  bool IsType, void *TyOrEx,
3113                                  const SourceRange &ArgRange);
3114
3115  ExprResult CheckPlaceholderExpr(Expr *E);
3116  bool CheckVecStepExpr(Expr *E);
3117
3118  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3119  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3120                                        SourceRange ExprRange,
3121                                        UnaryExprOrTypeTrait ExprKind);
3122  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3123                                          SourceLocation OpLoc,
3124                                          IdentifierInfo &Name,
3125                                          SourceLocation NameLoc,
3126                                          SourceLocation RParenLoc);
3127  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3128                                 tok::TokenKind Kind, Expr *Input);
3129
3130  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3131                                     Expr *Idx, SourceLocation RLoc);
3132  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3133                                             Expr *Idx, SourceLocation RLoc);
3134
3135  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3136                                      SourceLocation OpLoc, bool IsArrow,
3137                                      CXXScopeSpec &SS,
3138                                      SourceLocation TemplateKWLoc,
3139                                      NamedDecl *FirstQualifierInScope,
3140                                const DeclarationNameInfo &NameInfo,
3141                                const TemplateArgumentListInfo *TemplateArgs);
3142
3143  // This struct is for use by ActOnMemberAccess to allow
3144  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3145  // changing the access operator from a '.' to a '->' (to see if that is the
3146  // change needed to fix an error about an unknown member, e.g. when the class
3147  // defines a custom operator->).
3148  struct ActOnMemberAccessExtraArgs {
3149    Scope *S;
3150    UnqualifiedId &Id;
3151    Decl *ObjCImpDecl;
3152    bool HasTrailingLParen;
3153  };
3154
3155  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3156                                      SourceLocation OpLoc, bool IsArrow,
3157                                      const CXXScopeSpec &SS,
3158                                      SourceLocation TemplateKWLoc,
3159                                      NamedDecl *FirstQualifierInScope,
3160                                      LookupResult &R,
3161                                 const TemplateArgumentListInfo *TemplateArgs,
3162                                      bool SuppressQualifierCheck = false,
3163                                     ActOnMemberAccessExtraArgs *ExtraArgs = 0);
3164
3165  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3166  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
3167                              bool &IsArrow, SourceLocation OpLoc,
3168                              CXXScopeSpec &SS,
3169                              Decl *ObjCImpDecl,
3170                              bool HasTemplateArgs);
3171
3172  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3173                                     const CXXScopeSpec &SS,
3174                                     const LookupResult &R);
3175
3176  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3177                                      bool IsArrow, SourceLocation OpLoc,
3178                                      const CXXScopeSpec &SS,
3179                                      SourceLocation TemplateKWLoc,
3180                                      NamedDecl *FirstQualifierInScope,
3181                               const DeclarationNameInfo &NameInfo,
3182                               const TemplateArgumentListInfo *TemplateArgs);
3183
3184  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3185                                   SourceLocation OpLoc,
3186                                   tok::TokenKind OpKind,
3187                                   CXXScopeSpec &SS,
3188                                   SourceLocation TemplateKWLoc,
3189                                   UnqualifiedId &Member,
3190                                   Decl *ObjCImpDecl,
3191                                   bool HasTrailingLParen);
3192
3193  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3194  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3195                               FunctionDecl *FDecl,
3196                               const FunctionProtoType *Proto,
3197                               Expr **Args, unsigned NumArgs,
3198                               SourceLocation RParenLoc,
3199                               bool ExecConfig = false);
3200  void CheckStaticArrayArgument(SourceLocation CallLoc,
3201                                ParmVarDecl *Param,
3202                                const Expr *ArgExpr);
3203
3204  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3205  /// This provides the location of the left/right parens and a list of comma
3206  /// locations.
3207  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3208                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
3209                           Expr *ExecConfig = 0, bool IsExecConfig = false);
3210  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3211                                   SourceLocation LParenLoc,
3212                                   Expr **Args, unsigned NumArgs,
3213                                   SourceLocation RParenLoc,
3214                                   Expr *Config = 0,
3215                                   bool IsExecConfig = false);
3216
3217  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3218                                     MultiExprArg ExecConfig,
3219                                     SourceLocation GGGLoc);
3220
3221  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3222                           Declarator &D, ParsedType &Ty,
3223                           SourceLocation RParenLoc, Expr *CastExpr);
3224  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3225                                 TypeSourceInfo *Ty,
3226                                 SourceLocation RParenLoc,
3227                                 Expr *Op);
3228  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3229
3230  /// \brief Build an altivec or OpenCL literal.
3231  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3232                                SourceLocation RParenLoc, Expr *E,
3233                                TypeSourceInfo *TInfo);
3234
3235  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3236
3237  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3238                                  ParsedType Ty,
3239                                  SourceLocation RParenLoc,
3240                                  Expr *InitExpr);
3241
3242  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3243                                      TypeSourceInfo *TInfo,
3244                                      SourceLocation RParenLoc,
3245                                      Expr *LiteralExpr);
3246
3247  ExprResult ActOnInitList(SourceLocation LBraceLoc,
3248                           MultiExprArg InitArgList,
3249                           SourceLocation RBraceLoc);
3250
3251  ExprResult ActOnDesignatedInitializer(Designation &Desig,
3252                                        SourceLocation Loc,
3253                                        bool GNUSyntax,
3254                                        ExprResult Init);
3255
3256  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3257                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3258  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3259                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3260  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3261                                Expr *LHSExpr, Expr *RHSExpr);
3262
3263  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3264  /// in the case of a the GNU conditional expr extension.
3265  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3266                                SourceLocation ColonLoc,
3267                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3268
3269  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3270  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3271                            LabelDecl *TheDecl);
3272
3273  void ActOnStartStmtExpr();
3274  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3275                           SourceLocation RPLoc); // "({..})"
3276  void ActOnStmtExprError();
3277
3278  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3279  struct OffsetOfComponent {
3280    SourceLocation LocStart, LocEnd;
3281    bool isBrackets;  // true if [expr], false if .ident
3282    union {
3283      IdentifierInfo *IdentInfo;
3284      Expr *E;
3285    } U;
3286  };
3287
3288  /// __builtin_offsetof(type, a.b[123][456].c)
3289  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3290                                  TypeSourceInfo *TInfo,
3291                                  OffsetOfComponent *CompPtr,
3292                                  unsigned NumComponents,
3293                                  SourceLocation RParenLoc);
3294  ExprResult ActOnBuiltinOffsetOf(Scope *S,
3295                                  SourceLocation BuiltinLoc,
3296                                  SourceLocation TypeLoc,
3297                                  ParsedType ParsedArgTy,
3298                                  OffsetOfComponent *CompPtr,
3299                                  unsigned NumComponents,
3300                                  SourceLocation RParenLoc);
3301
3302  // __builtin_choose_expr(constExpr, expr1, expr2)
3303  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3304                             Expr *CondExpr, Expr *LHSExpr,
3305                             Expr *RHSExpr, SourceLocation RPLoc);
3306
3307  // __builtin_va_arg(expr, type)
3308  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3309                        SourceLocation RPLoc);
3310  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3311                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
3312
3313  // __null
3314  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3315
3316  bool CheckCaseExpression(Expr *E);
3317
3318  /// \brief Describes the result of an "if-exists" condition check.
3319  enum IfExistsResult {
3320    /// \brief The symbol exists.
3321    IER_Exists,
3322
3323    /// \brief The symbol does not exist.
3324    IER_DoesNotExist,
3325
3326    /// \brief The name is a dependent name, so the results will differ
3327    /// from one instantiation to the next.
3328    IER_Dependent,
3329
3330    /// \brief An error occurred.
3331    IER_Error
3332  };
3333
3334  IfExistsResult
3335  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3336                               const DeclarationNameInfo &TargetNameInfo);
3337
3338  IfExistsResult
3339  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3340                               bool IsIfExists, CXXScopeSpec &SS,
3341                               UnqualifiedId &Name);
3342
3343  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3344                                        bool IsIfExists,
3345                                        NestedNameSpecifierLoc QualifierLoc,
3346                                        DeclarationNameInfo NameInfo,
3347                                        Stmt *Nested);
3348  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3349                                        bool IsIfExists,
3350                                        CXXScopeSpec &SS, UnqualifiedId &Name,
3351                                        Stmt *Nested);
3352
3353  //===------------------------- "Block" Extension ------------------------===//
3354
3355  /// ActOnBlockStart - This callback is invoked when a block literal is
3356  /// started.
3357  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3358
3359  /// ActOnBlockArguments - This callback allows processing of block arguments.
3360  /// If there are no arguments, this is still invoked.
3361  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3362                           Scope *CurScope);
3363
3364  /// ActOnBlockError - If there is an error parsing a block, this callback
3365  /// is invoked to pop the information about the block from the action impl.
3366  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3367
3368  /// ActOnBlockStmtExpr - This is called when the body of a block statement
3369  /// literal was successfully completed.  ^(int x){...}
3370  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3371                                Scope *CurScope);
3372
3373  //===---------------------------- OpenCL Features -----------------------===//
3374
3375  /// __builtin_astype(...)
3376  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3377                             SourceLocation BuiltinLoc,
3378                             SourceLocation RParenLoc);
3379
3380  //===---------------------------- C++ Features --------------------------===//
3381
3382  // Act on C++ namespaces
3383  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3384                               SourceLocation NamespaceLoc,
3385                               SourceLocation IdentLoc,
3386                               IdentifierInfo *Ident,
3387                               SourceLocation LBrace,
3388                               AttributeList *AttrList);
3389  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3390
3391  NamespaceDecl *getStdNamespace() const;
3392  NamespaceDecl *getOrCreateStdNamespace();
3393
3394  CXXRecordDecl *getStdBadAlloc() const;
3395
3396  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3397  /// it is and Element is not NULL, assigns the element type to Element.
3398  bool isStdInitializerList(QualType Ty, QualType *Element);
3399
3400  /// \brief Looks for the std::initializer_list template and instantiates it
3401  /// with Element, or emits an error if it's not found.
3402  ///
3403  /// \returns The instantiated template, or null on error.
3404  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3405
3406  /// \brief Determine whether Ctor is an initializer-list constructor, as
3407  /// defined in [dcl.init.list]p2.
3408  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3409
3410  Decl *ActOnUsingDirective(Scope *CurScope,
3411                            SourceLocation UsingLoc,
3412                            SourceLocation NamespcLoc,
3413                            CXXScopeSpec &SS,
3414                            SourceLocation IdentLoc,
3415                            IdentifierInfo *NamespcName,
3416                            AttributeList *AttrList);
3417
3418  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3419
3420  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3421                               SourceLocation NamespaceLoc,
3422                               SourceLocation AliasLoc,
3423                               IdentifierInfo *Alias,
3424                               CXXScopeSpec &SS,
3425                               SourceLocation IdentLoc,
3426                               IdentifierInfo *Ident);
3427
3428  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3429  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3430                            const LookupResult &PreviousDecls);
3431  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3432                                        NamedDecl *Target);
3433
3434  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3435                                   bool isTypeName,
3436                                   const CXXScopeSpec &SS,
3437                                   SourceLocation NameLoc,
3438                                   const LookupResult &Previous);
3439  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3440                               const CXXScopeSpec &SS,
3441                               SourceLocation NameLoc);
3442
3443  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3444                                   SourceLocation UsingLoc,
3445                                   CXXScopeSpec &SS,
3446                                   const DeclarationNameInfo &NameInfo,
3447                                   AttributeList *AttrList,
3448                                   bool IsInstantiation,
3449                                   bool IsTypeName,
3450                                   SourceLocation TypenameLoc);
3451
3452  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3453
3454  Decl *ActOnUsingDeclaration(Scope *CurScope,
3455                              AccessSpecifier AS,
3456                              bool HasUsingKeyword,
3457                              SourceLocation UsingLoc,
3458                              CXXScopeSpec &SS,
3459                              UnqualifiedId &Name,
3460                              AttributeList *AttrList,
3461                              bool IsTypeName,
3462                              SourceLocation TypenameLoc);
3463  Decl *ActOnAliasDeclaration(Scope *CurScope,
3464                              AccessSpecifier AS,
3465                              MultiTemplateParamsArg TemplateParams,
3466                              SourceLocation UsingLoc,
3467                              UnqualifiedId &Name,
3468                              AttributeList *AttrList,
3469                              TypeResult Type);
3470
3471  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3472  /// including handling of its default argument expressions.
3473  ///
3474  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3475  ExprResult
3476  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3477                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3478                        bool HadMultipleCandidates, bool IsListInitialization,
3479                        bool RequiresZeroInit, unsigned ConstructKind,
3480                        SourceRange ParenRange);
3481
3482  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3483  // the constructor can be elidable?
3484  ExprResult
3485  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3486                        CXXConstructorDecl *Constructor, bool Elidable,
3487                        MultiExprArg Exprs, bool HadMultipleCandidates,
3488                        bool IsListInitialization, bool RequiresZeroInit,
3489                        unsigned ConstructKind, SourceRange ParenRange);
3490
3491  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3492  /// the default expr if needed.
3493  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3494                                    FunctionDecl *FD,
3495                                    ParmVarDecl *Param);
3496
3497  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3498  /// constructed variable.
3499  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3500
3501  /// \brief Helper class that collects exception specifications for
3502  /// implicitly-declared special member functions.
3503  class ImplicitExceptionSpecification {
3504    // Pointer to allow copying
3505    Sema *Self;
3506    // We order exception specifications thus:
3507    // noexcept is the most restrictive, but is only used in C++11.
3508    // throw() comes next.
3509    // Then a throw(collected exceptions)
3510    // Finally no specification, which is expressed as noexcept(false).
3511    // throw(...) is used instead if any called function uses it.
3512    ExceptionSpecificationType ComputedEST;
3513    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3514    SmallVector<QualType, 4> Exceptions;
3515
3516    void ClearExceptions() {
3517      ExceptionsSeen.clear();
3518      Exceptions.clear();
3519    }
3520
3521  public:
3522    explicit ImplicitExceptionSpecification(Sema &Self)
3523      : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3524      if (!Self.getLangOpts().CPlusPlus11)
3525        ComputedEST = EST_DynamicNone;
3526    }
3527
3528    /// \brief Get the computed exception specification type.
3529    ExceptionSpecificationType getExceptionSpecType() const {
3530      assert(ComputedEST != EST_ComputedNoexcept &&
3531             "noexcept(expr) should not be a possible result");
3532      return ComputedEST;
3533    }
3534
3535    /// \brief The number of exceptions in the exception specification.
3536    unsigned size() const { return Exceptions.size(); }
3537
3538    /// \brief The set of exceptions in the exception specification.
3539    const QualType *data() const { return Exceptions.data(); }
3540
3541    /// \brief Integrate another called method into the collected data.
3542    void CalledDecl(SourceLocation CallLoc, CXXMethodDecl *Method);
3543
3544    /// \brief Integrate an invoked expression into the collected data.
3545    void CalledExpr(Expr *E);
3546
3547    /// \brief Overwrite an EPI's exception specification with this
3548    /// computed exception specification.
3549    void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3550      EPI.ExceptionSpecType = getExceptionSpecType();
3551      if (EPI.ExceptionSpecType == EST_Dynamic) {
3552        EPI.NumExceptions = size();
3553        EPI.Exceptions = data();
3554      } else if (EPI.ExceptionSpecType == EST_None) {
3555        /// C++11 [except.spec]p14:
3556        ///   The exception-specification is noexcept(false) if the set of
3557        ///   potential exceptions of the special member function contains "any"
3558        EPI.ExceptionSpecType = EST_ComputedNoexcept;
3559        EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3560                                                     tok::kw_false).take();
3561      }
3562    }
3563    FunctionProtoType::ExtProtoInfo getEPI() const {
3564      FunctionProtoType::ExtProtoInfo EPI;
3565      getEPI(EPI);
3566      return EPI;
3567    }
3568  };
3569
3570  /// \brief Determine what sort of exception specification a defaulted
3571  /// copy constructor of a class will have.
3572  ImplicitExceptionSpecification
3573  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3574                                           CXXMethodDecl *MD);
3575
3576  /// \brief Determine what sort of exception specification a defaulted
3577  /// default constructor of a class will have, and whether the parameter
3578  /// will be const.
3579  ImplicitExceptionSpecification
3580  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3581
3582  /// \brief Determine what sort of exception specification a defautled
3583  /// copy assignment operator of a class will have, and whether the
3584  /// parameter will be const.
3585  ImplicitExceptionSpecification
3586  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3587
3588  /// \brief Determine what sort of exception specification a defaulted move
3589  /// constructor of a class will have.
3590  ImplicitExceptionSpecification
3591  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3592
3593  /// \brief Determine what sort of exception specification a defaulted move
3594  /// assignment operator of a class will have.
3595  ImplicitExceptionSpecification
3596  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3597
3598  /// \brief Determine what sort of exception specification a defaulted
3599  /// destructor of a class will have.
3600  ImplicitExceptionSpecification
3601  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3602
3603  /// \brief Determine what sort of exception specification an inheriting
3604  /// constructor of a class will have.
3605  ImplicitExceptionSpecification
3606  ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD);
3607
3608  /// \brief Evaluate the implicit exception specification for a defaulted
3609  /// special member function.
3610  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3611
3612  /// \brief Check the given exception-specification and update the
3613  /// extended prototype information with the results.
3614  void checkExceptionSpecification(ExceptionSpecificationType EST,
3615                                   ArrayRef<ParsedType> DynamicExceptions,
3616                                   ArrayRef<SourceRange> DynamicExceptionRanges,
3617                                   Expr *NoexceptExpr,
3618                                   SmallVectorImpl<QualType> &Exceptions,
3619                                   FunctionProtoType::ExtProtoInfo &EPI);
3620
3621  /// \brief Determine if a special member function should have a deleted
3622  /// definition when it is defaulted.
3623  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3624                                 bool Diagnose = false);
3625
3626  /// \brief Declare the implicit default constructor for the given class.
3627  ///
3628  /// \param ClassDecl The class declaration into which the implicit
3629  /// default constructor will be added.
3630  ///
3631  /// \returns The implicitly-declared default constructor.
3632  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3633                                                     CXXRecordDecl *ClassDecl);
3634
3635  /// DefineImplicitDefaultConstructor - Checks for feasibility of
3636  /// defining this constructor as the default constructor.
3637  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3638                                        CXXConstructorDecl *Constructor);
3639
3640  /// \brief Declare the implicit destructor for the given class.
3641  ///
3642  /// \param ClassDecl The class declaration into which the implicit
3643  /// destructor will be added.
3644  ///
3645  /// \returns The implicitly-declared destructor.
3646  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3647
3648  /// DefineImplicitDestructor - Checks for feasibility of
3649  /// defining this destructor as the default destructor.
3650  void DefineImplicitDestructor(SourceLocation CurrentLocation,
3651                                CXXDestructorDecl *Destructor);
3652
3653  /// \brief Build an exception spec for destructors that don't have one.
3654  ///
3655  /// C++11 says that user-defined destructors with no exception spec get one
3656  /// that looks as if the destructor was implicitly declared.
3657  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3658                                     CXXDestructorDecl *Destructor);
3659
3660  /// \brief Declare all inheriting constructors for the given class.
3661  ///
3662  /// \param ClassDecl The class declaration into which the inheriting
3663  /// constructors will be added.
3664  void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
3665
3666  /// \brief Define the specified inheriting constructor.
3667  void DefineInheritingConstructor(SourceLocation UseLoc,
3668                                   CXXConstructorDecl *Constructor);
3669
3670  /// \brief Declare the implicit copy constructor for the given class.
3671  ///
3672  /// \param ClassDecl The class declaration into which the implicit
3673  /// copy constructor will be added.
3674  ///
3675  /// \returns The implicitly-declared copy constructor.
3676  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3677
3678  /// DefineImplicitCopyConstructor - Checks for feasibility of
3679  /// defining this constructor as the copy constructor.
3680  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3681                                     CXXConstructorDecl *Constructor);
3682
3683  /// \brief Declare the implicit move constructor for the given class.
3684  ///
3685  /// \param ClassDecl The Class declaration into which the implicit
3686  /// move constructor will be added.
3687  ///
3688  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3689  /// declared.
3690  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3691
3692  /// DefineImplicitMoveConstructor - Checks for feasibility of
3693  /// defining this constructor as the move constructor.
3694  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3695                                     CXXConstructorDecl *Constructor);
3696
3697  /// \brief Declare the implicit copy assignment operator for the given class.
3698  ///
3699  /// \param ClassDecl The class declaration into which the implicit
3700  /// copy assignment operator will be added.
3701  ///
3702  /// \returns The implicitly-declared copy assignment operator.
3703  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3704
3705  /// \brief Defines an implicitly-declared copy assignment operator.
3706  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3707                                    CXXMethodDecl *MethodDecl);
3708
3709  /// \brief Declare the implicit move assignment operator for the given class.
3710  ///
3711  /// \param ClassDecl The Class declaration into which the implicit
3712  /// move assignment operator will be added.
3713  ///
3714  /// \returns The implicitly-declared move assignment operator, or NULL if it
3715  /// wasn't declared.
3716  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3717
3718  /// \brief Defines an implicitly-declared move assignment operator.
3719  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3720                                    CXXMethodDecl *MethodDecl);
3721
3722  /// \brief Force the declaration of any implicitly-declared members of this
3723  /// class.
3724  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3725
3726  /// \brief Determine whether the given function is an implicitly-deleted
3727  /// special member function.
3728  bool isImplicitlyDeleted(FunctionDecl *FD);
3729
3730  /// \brief Check whether 'this' shows up in the type of a static member
3731  /// function after the (naturally empty) cv-qualifier-seq would be.
3732  ///
3733  /// \returns true if an error occurred.
3734  bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3735
3736  /// \brief Whether this' shows up in the exception specification of a static
3737  /// member function.
3738  bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3739
3740  /// \brief Check whether 'this' shows up in the attributes of the given
3741  /// static member function.
3742  ///
3743  /// \returns true if an error occurred.
3744  bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3745
3746  /// MaybeBindToTemporary - If the passed in expression has a record type with
3747  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3748  /// it simply returns the passed in expression.
3749  ExprResult MaybeBindToTemporary(Expr *E);
3750
3751  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3752                               MultiExprArg ArgsPtr,
3753                               SourceLocation Loc,
3754                               SmallVectorImpl<Expr*> &ConvertedArgs,
3755                               bool AllowExplicit = false,
3756                               bool IsListInitialization = false);
3757
3758  ParsedType getDestructorName(SourceLocation TildeLoc,
3759                               IdentifierInfo &II, SourceLocation NameLoc,
3760                               Scope *S, CXXScopeSpec &SS,
3761                               ParsedType ObjectType,
3762                               bool EnteringContext);
3763
3764  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3765
3766  // Checks that reinterpret casts don't have undefined behavior.
3767  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3768                                      bool IsDereference, SourceRange Range);
3769
3770  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3771  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3772                               tok::TokenKind Kind,
3773                               SourceLocation LAngleBracketLoc,
3774                               Declarator &D,
3775                               SourceLocation RAngleBracketLoc,
3776                               SourceLocation LParenLoc,
3777                               Expr *E,
3778                               SourceLocation RParenLoc);
3779
3780  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3781                               tok::TokenKind Kind,
3782                               TypeSourceInfo *Ty,
3783                               Expr *E,
3784                               SourceRange AngleBrackets,
3785                               SourceRange Parens);
3786
3787  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3788                            SourceLocation TypeidLoc,
3789                            TypeSourceInfo *Operand,
3790                            SourceLocation RParenLoc);
3791  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3792                            SourceLocation TypeidLoc,
3793                            Expr *Operand,
3794                            SourceLocation RParenLoc);
3795
3796  /// ActOnCXXTypeid - Parse typeid( something ).
3797  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3798                            SourceLocation LParenLoc, bool isType,
3799                            void *TyOrExpr,
3800                            SourceLocation RParenLoc);
3801
3802  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3803                            SourceLocation TypeidLoc,
3804                            TypeSourceInfo *Operand,
3805                            SourceLocation RParenLoc);
3806  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3807                            SourceLocation TypeidLoc,
3808                            Expr *Operand,
3809                            SourceLocation RParenLoc);
3810
3811  /// ActOnCXXUuidof - Parse __uuidof( something ).
3812  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3813                            SourceLocation LParenLoc, bool isType,
3814                            void *TyOrExpr,
3815                            SourceLocation RParenLoc);
3816
3817
3818  //// ActOnCXXThis -  Parse 'this' pointer.
3819  ExprResult ActOnCXXThis(SourceLocation loc);
3820
3821  /// \brief Try to retrieve the type of the 'this' pointer.
3822  ///
3823  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3824  QualType getCurrentThisType();
3825
3826  /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
3827  /// current context not being a non-static member function. In such cases,
3828  /// this provides the type used for 'this'.
3829  QualType CXXThisTypeOverride;
3830
3831  /// \brief RAII object used to temporarily allow the C++ 'this' expression
3832  /// to be used, with the given qualifiers on the current class type.
3833  class CXXThisScopeRAII {
3834    Sema &S;
3835    QualType OldCXXThisTypeOverride;
3836    bool Enabled;
3837
3838  public:
3839    /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
3840    /// using the given declaration (which is either a class template or a
3841    /// class) along with the given qualifiers.
3842    /// along with the qualifiers placed on '*this'.
3843    CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
3844                     bool Enabled = true);
3845
3846    ~CXXThisScopeRAII();
3847  };
3848
3849  /// \brief Make sure the value of 'this' is actually available in the current
3850  /// context, if it is a potentially evaluated context.
3851  ///
3852  /// \param Loc The location at which the capture of 'this' occurs.
3853  ///
3854  /// \param Explicit Whether 'this' is explicitly captured in a lambda
3855  /// capture list.
3856  void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
3857
3858  /// \brief Determine whether the given type is the type of *this that is used
3859  /// outside of the body of a member function for a type that is currently
3860  /// being defined.
3861  bool isThisOutsideMemberFunctionBody(QualType BaseType);
3862
3863  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3864  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3865
3866
3867  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
3868  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3869
3870  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
3871  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
3872
3873  //// ActOnCXXThrow -  Parse throw expressions.
3874  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
3875  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
3876                           bool IsThrownVarInScope);
3877  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
3878                                  bool IsThrownVarInScope);
3879
3880  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
3881  /// Can be interpreted either as function-style casting ("int(x)")
3882  /// or class type construction ("ClassType(x,y,z)")
3883  /// or creation of a value-initialized type ("int()").
3884  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
3885                                       SourceLocation LParenLoc,
3886                                       MultiExprArg Exprs,
3887                                       SourceLocation RParenLoc);
3888
3889  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
3890                                       SourceLocation LParenLoc,
3891                                       MultiExprArg Exprs,
3892                                       SourceLocation RParenLoc);
3893
3894  /// ActOnCXXNew - Parsed a C++ 'new' expression.
3895  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
3896                         SourceLocation PlacementLParen,
3897                         MultiExprArg PlacementArgs,
3898                         SourceLocation PlacementRParen,
3899                         SourceRange TypeIdParens, Declarator &D,
3900                         Expr *Initializer);
3901  ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
3902                         SourceLocation PlacementLParen,
3903                         MultiExprArg PlacementArgs,
3904                         SourceLocation PlacementRParen,
3905                         SourceRange TypeIdParens,
3906                         QualType AllocType,
3907                         TypeSourceInfo *AllocTypeInfo,
3908                         Expr *ArraySize,
3909                         SourceRange DirectInitRange,
3910                         Expr *Initializer,
3911                         bool TypeMayContainAuto = true);
3912
3913  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
3914                          SourceRange R);
3915  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
3916                               bool UseGlobal, QualType AllocType, bool IsArray,
3917                               Expr **PlaceArgs, unsigned NumPlaceArgs,
3918                               FunctionDecl *&OperatorNew,
3919                               FunctionDecl *&OperatorDelete);
3920  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
3921                              DeclarationName Name, Expr** Args,
3922                              unsigned NumArgs, DeclContext *Ctx,
3923                              bool AllowMissing, FunctionDecl *&Operator,
3924                              bool Diagnose = true);
3925  void DeclareGlobalNewDelete();
3926  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
3927                                       QualType Argument,
3928                                       bool addMallocAttr = false);
3929
3930  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3931                                DeclarationName Name, FunctionDecl* &Operator,
3932                                bool Diagnose = true);
3933
3934  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
3935  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
3936                            bool UseGlobal, bool ArrayForm,
3937                            Expr *Operand);
3938
3939  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
3940  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
3941                                    SourceLocation StmtLoc,
3942                                    bool ConvertToBoolean);
3943
3944  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
3945                               Expr *Operand, SourceLocation RParen);
3946  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3947                                  SourceLocation RParen);
3948
3949  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
3950  /// pseudo-functions.
3951  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
3952                                 SourceLocation KWLoc,
3953                                 ParsedType Ty,
3954                                 SourceLocation RParen);
3955
3956  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
3957                                 SourceLocation KWLoc,
3958                                 TypeSourceInfo *T,
3959                                 SourceLocation RParen);
3960
3961  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
3962  /// pseudo-functions.
3963  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
3964                                  SourceLocation KWLoc,
3965                                  ParsedType LhsTy,
3966                                  ParsedType RhsTy,
3967                                  SourceLocation RParen);
3968
3969  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3970                                  SourceLocation KWLoc,
3971                                  TypeSourceInfo *LhsT,
3972                                  TypeSourceInfo *RhsT,
3973                                  SourceLocation RParen);
3974
3975  /// \brief Parsed one of the type trait support pseudo-functions.
3976  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3977                            ArrayRef<ParsedType> Args,
3978                            SourceLocation RParenLoc);
3979  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3980                            ArrayRef<TypeSourceInfo *> Args,
3981                            SourceLocation RParenLoc);
3982
3983  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
3984  /// pseudo-functions.
3985  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3986                                 SourceLocation KWLoc,
3987                                 ParsedType LhsTy,
3988                                 Expr *DimExpr,
3989                                 SourceLocation RParen);
3990
3991  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
3992                                 SourceLocation KWLoc,
3993                                 TypeSourceInfo *TSInfo,
3994                                 Expr *DimExpr,
3995                                 SourceLocation RParen);
3996
3997  /// ActOnExpressionTrait - Parsed one of the unary type trait support
3998  /// pseudo-functions.
3999  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4000                                  SourceLocation KWLoc,
4001                                  Expr *Queried,
4002                                  SourceLocation RParen);
4003
4004  ExprResult BuildExpressionTrait(ExpressionTrait OET,
4005                                  SourceLocation KWLoc,
4006                                  Expr *Queried,
4007                                  SourceLocation RParen);
4008
4009  ExprResult ActOnStartCXXMemberReference(Scope *S,
4010                                          Expr *Base,
4011                                          SourceLocation OpLoc,
4012                                          tok::TokenKind OpKind,
4013                                          ParsedType &ObjectType,
4014                                          bool &MayBePseudoDestructor);
4015
4016  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4017
4018  ExprResult BuildPseudoDestructorExpr(Expr *Base,
4019                                       SourceLocation OpLoc,
4020                                       tok::TokenKind OpKind,
4021                                       const CXXScopeSpec &SS,
4022                                       TypeSourceInfo *ScopeType,
4023                                       SourceLocation CCLoc,
4024                                       SourceLocation TildeLoc,
4025                                     PseudoDestructorTypeStorage DestroyedType,
4026                                       bool HasTrailingLParen);
4027
4028  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4029                                       SourceLocation OpLoc,
4030                                       tok::TokenKind OpKind,
4031                                       CXXScopeSpec &SS,
4032                                       UnqualifiedId &FirstTypeName,
4033                                       SourceLocation CCLoc,
4034                                       SourceLocation TildeLoc,
4035                                       UnqualifiedId &SecondTypeName,
4036                                       bool HasTrailingLParen);
4037
4038  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4039                                       SourceLocation OpLoc,
4040                                       tok::TokenKind OpKind,
4041                                       SourceLocation TildeLoc,
4042                                       const DeclSpec& DS,
4043                                       bool HasTrailingLParen);
4044
4045  /// MaybeCreateExprWithCleanups - If the current full-expression
4046  /// requires any cleanups, surround it with a ExprWithCleanups node.
4047  /// Otherwise, just returns the passed-in expression.
4048  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4049  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4050  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4051
4052  ExprResult ActOnFinishFullExpr(Expr *Expr) {
4053    return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4054                                          : SourceLocation());
4055  }
4056  ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4057                                 bool DiscardedValue = false,
4058                                 bool IsConstexpr = false);
4059  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4060
4061  // Marks SS invalid if it represents an incomplete type.
4062  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4063
4064  DeclContext *computeDeclContext(QualType T);
4065  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4066                                  bool EnteringContext = false);
4067  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4068  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4069  bool isUnknownSpecialization(const CXXScopeSpec &SS);
4070
4071  /// \brief The parser has parsed a global nested-name-specifier '::'.
4072  ///
4073  /// \param S The scope in which this nested-name-specifier occurs.
4074  ///
4075  /// \param CCLoc The location of the '::'.
4076  ///
4077  /// \param SS The nested-name-specifier, which will be updated in-place
4078  /// to reflect the parsed nested-name-specifier.
4079  ///
4080  /// \returns true if an error occurred, false otherwise.
4081  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4082                                    CXXScopeSpec &SS);
4083
4084  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4085  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4086
4087  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4088                                    SourceLocation IdLoc,
4089                                    IdentifierInfo &II,
4090                                    ParsedType ObjectType);
4091
4092  bool BuildCXXNestedNameSpecifier(Scope *S,
4093                                   IdentifierInfo &Identifier,
4094                                   SourceLocation IdentifierLoc,
4095                                   SourceLocation CCLoc,
4096                                   QualType ObjectType,
4097                                   bool EnteringContext,
4098                                   CXXScopeSpec &SS,
4099                                   NamedDecl *ScopeLookupResult,
4100                                   bool ErrorRecoveryLookup);
4101
4102  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4103  ///
4104  /// \param S The scope in which this nested-name-specifier occurs.
4105  ///
4106  /// \param Identifier The identifier preceding the '::'.
4107  ///
4108  /// \param IdentifierLoc The location of the identifier.
4109  ///
4110  /// \param CCLoc The location of the '::'.
4111  ///
4112  /// \param ObjectType The type of the object, if we're parsing
4113  /// nested-name-specifier in a member access expression.
4114  ///
4115  /// \param EnteringContext Whether we're entering the context nominated by
4116  /// this nested-name-specifier.
4117  ///
4118  /// \param SS The nested-name-specifier, which is both an input
4119  /// parameter (the nested-name-specifier before this type) and an
4120  /// output parameter (containing the full nested-name-specifier,
4121  /// including this new type).
4122  ///
4123  /// \returns true if an error occurred, false otherwise.
4124  bool ActOnCXXNestedNameSpecifier(Scope *S,
4125                                   IdentifierInfo &Identifier,
4126                                   SourceLocation IdentifierLoc,
4127                                   SourceLocation CCLoc,
4128                                   ParsedType ObjectType,
4129                                   bool EnteringContext,
4130                                   CXXScopeSpec &SS);
4131
4132  ExprResult ActOnDecltypeExpression(Expr *E);
4133
4134  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4135                                           const DeclSpec &DS,
4136                                           SourceLocation ColonColonLoc);
4137
4138  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4139                                 IdentifierInfo &Identifier,
4140                                 SourceLocation IdentifierLoc,
4141                                 SourceLocation ColonLoc,
4142                                 ParsedType ObjectType,
4143                                 bool EnteringContext);
4144
4145  /// \brief The parser has parsed a nested-name-specifier
4146  /// 'template[opt] template-name < template-args >::'.
4147  ///
4148  /// \param S The scope in which this nested-name-specifier occurs.
4149  ///
4150  /// \param SS The nested-name-specifier, which is both an input
4151  /// parameter (the nested-name-specifier before this type) and an
4152  /// output parameter (containing the full nested-name-specifier,
4153  /// including this new type).
4154  ///
4155  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4156  /// \param TemplateName the template name.
4157  /// \param TemplateNameLoc The location of the template name.
4158  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4159  /// \param TemplateArgs The template arguments.
4160  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4161  /// \param CCLoc The location of the '::'.
4162  ///
4163  /// \param EnteringContext Whether we're entering the context of the
4164  /// nested-name-specifier.
4165  ///
4166  ///
4167  /// \returns true if an error occurred, false otherwise.
4168  bool ActOnCXXNestedNameSpecifier(Scope *S,
4169                                   CXXScopeSpec &SS,
4170                                   SourceLocation TemplateKWLoc,
4171                                   TemplateTy TemplateName,
4172                                   SourceLocation TemplateNameLoc,
4173                                   SourceLocation LAngleLoc,
4174                                   ASTTemplateArgsPtr TemplateArgs,
4175                                   SourceLocation RAngleLoc,
4176                                   SourceLocation CCLoc,
4177                                   bool EnteringContext);
4178
4179  /// \brief Given a C++ nested-name-specifier, produce an annotation value
4180  /// that the parser can use later to reconstruct the given
4181  /// nested-name-specifier.
4182  ///
4183  /// \param SS A nested-name-specifier.
4184  ///
4185  /// \returns A pointer containing all of the information in the
4186  /// nested-name-specifier \p SS.
4187  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4188
4189  /// \brief Given an annotation pointer for a nested-name-specifier, restore
4190  /// the nested-name-specifier structure.
4191  ///
4192  /// \param Annotation The annotation pointer, produced by
4193  /// \c SaveNestedNameSpecifierAnnotation().
4194  ///
4195  /// \param AnnotationRange The source range corresponding to the annotation.
4196  ///
4197  /// \param SS The nested-name-specifier that will be updated with the contents
4198  /// of the annotation pointer.
4199  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4200                                            SourceRange AnnotationRange,
4201                                            CXXScopeSpec &SS);
4202
4203  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4204
4205  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4206  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4207  /// After this method is called, according to [C++ 3.4.3p3], names should be
4208  /// looked up in the declarator-id's scope, until the declarator is parsed and
4209  /// ActOnCXXExitDeclaratorScope is called.
4210  /// The 'SS' should be a non-empty valid CXXScopeSpec.
4211  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4212
4213  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4214  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4215  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4216  /// Used to indicate that names should revert to being looked up in the
4217  /// defining scope.
4218  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4219
4220  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4221  /// initializer for the declaration 'Dcl'.
4222  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4223  /// static data member of class X, names should be looked up in the scope of
4224  /// class X.
4225  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4226
4227  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4228  /// initializer for the declaration 'Dcl'.
4229  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4230
4231  /// \brief Create a new lambda closure type.
4232  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4233                                         TypeSourceInfo *Info,
4234                                         bool KnownDependent);
4235
4236  /// \brief Start the definition of a lambda expression.
4237  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4238                                       SourceRange IntroducerRange,
4239                                       TypeSourceInfo *MethodType,
4240                                       SourceLocation EndLoc,
4241                                       ArrayRef<ParmVarDecl *> Params);
4242
4243  /// \brief Introduce the scope for a lambda expression.
4244  sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
4245                                          SourceRange IntroducerRange,
4246                                          LambdaCaptureDefault CaptureDefault,
4247                                          bool ExplicitParams,
4248                                          bool ExplicitResultType,
4249                                          bool Mutable);
4250
4251  /// \brief Note that we have finished the explicit captures for the
4252  /// given lambda.
4253  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4254
4255  /// \brief Introduce the lambda parameters into scope.
4256  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4257
4258  /// \brief Deduce a block or lambda's return type based on the return
4259  /// statements present in the body.
4260  void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4261
4262  /// ActOnStartOfLambdaDefinition - This is called just before we start
4263  /// parsing the body of a lambda; it analyzes the explicit captures and
4264  /// arguments, and sets up various data-structures for the body of the
4265  /// lambda.
4266  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4267                                    Declarator &ParamInfo, Scope *CurScope);
4268
4269  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4270  /// is invoked to pop the information about the lambda.
4271  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4272                        bool IsInstantiation = false);
4273
4274  /// ActOnLambdaExpr - This is called when the body of a lambda expression
4275  /// was successfully completed.
4276  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4277                             Scope *CurScope,
4278                             bool IsInstantiation = false);
4279
4280  /// \brief Define the "body" of the conversion from a lambda object to a
4281  /// function pointer.
4282  ///
4283  /// This routine doesn't actually define a sensible body; rather, it fills
4284  /// in the initialization expression needed to copy the lambda object into
4285  /// the block, and IR generation actually generates the real body of the
4286  /// block pointer conversion.
4287  void DefineImplicitLambdaToFunctionPointerConversion(
4288         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4289
4290  /// \brief Define the "body" of the conversion from a lambda object to a
4291  /// block pointer.
4292  ///
4293  /// This routine doesn't actually define a sensible body; rather, it fills
4294  /// in the initialization expression needed to copy the lambda object into
4295  /// the block, and IR generation actually generates the real body of the
4296  /// block pointer conversion.
4297  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4298                                                    CXXConversionDecl *Conv);
4299
4300  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4301                                           SourceLocation ConvLocation,
4302                                           CXXConversionDecl *Conv,
4303                                           Expr *Src);
4304
4305  // ParseObjCStringLiteral - Parse Objective-C string literals.
4306  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4307                                    Expr **Strings,
4308                                    unsigned NumStrings);
4309
4310  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4311
4312  /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4313  /// numeric literal expression. Type of the expression will be "NSNumber *"
4314  /// or "id" if NSNumber is unavailable.
4315  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4316  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4317                                  bool Value);
4318  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4319
4320  /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4321  /// '@' prefixed parenthesized expression. The type of the expression will
4322  /// either be "NSNumber *" or "NSString *" depending on the type of
4323  /// ValueType, which is allowed to be a built-in numeric type or
4324  /// "char *" or "const char *".
4325  ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4326
4327  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4328                                          Expr *IndexExpr,
4329                                          ObjCMethodDecl *getterMethod,
4330                                          ObjCMethodDecl *setterMethod);
4331
4332  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4333                                        ObjCDictionaryElement *Elements,
4334                                        unsigned NumElements);
4335
4336  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4337                                  TypeSourceInfo *EncodedTypeInfo,
4338                                  SourceLocation RParenLoc);
4339  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4340                                    CXXConversionDecl *Method,
4341                                    bool HadMultipleCandidates);
4342
4343  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4344                                       SourceLocation EncodeLoc,
4345                                       SourceLocation LParenLoc,
4346                                       ParsedType Ty,
4347                                       SourceLocation RParenLoc);
4348
4349  /// ParseObjCSelectorExpression - Build selector expression for \@selector
4350  ExprResult ParseObjCSelectorExpression(Selector Sel,
4351                                         SourceLocation AtLoc,
4352                                         SourceLocation SelLoc,
4353                                         SourceLocation LParenLoc,
4354                                         SourceLocation RParenLoc);
4355
4356  /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4357  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4358                                         SourceLocation AtLoc,
4359                                         SourceLocation ProtoLoc,
4360                                         SourceLocation LParenLoc,
4361                                         SourceLocation ProtoIdLoc,
4362                                         SourceLocation RParenLoc);
4363
4364  //===--------------------------------------------------------------------===//
4365  // C++ Declarations
4366  //
4367  Decl *ActOnStartLinkageSpecification(Scope *S,
4368                                       SourceLocation ExternLoc,
4369                                       SourceLocation LangLoc,
4370                                       StringRef Lang,
4371                                       SourceLocation LBraceLoc);
4372  Decl *ActOnFinishLinkageSpecification(Scope *S,
4373                                        Decl *LinkageSpec,
4374                                        SourceLocation RBraceLoc);
4375
4376
4377  //===--------------------------------------------------------------------===//
4378  // C++ Classes
4379  //
4380  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4381                          const CXXScopeSpec *SS = 0);
4382
4383  bool ActOnAccessSpecifier(AccessSpecifier Access,
4384                            SourceLocation ASLoc,
4385                            SourceLocation ColonLoc,
4386                            AttributeList *Attrs = 0);
4387
4388  NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4389                                 Declarator &D,
4390                                 MultiTemplateParamsArg TemplateParameterLists,
4391                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4392                                 InClassInitStyle InitStyle);
4393  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4394                                        Expr *Init);
4395
4396  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4397                                    Scope *S,
4398                                    CXXScopeSpec &SS,
4399                                    IdentifierInfo *MemberOrBase,
4400                                    ParsedType TemplateTypeTy,
4401                                    const DeclSpec &DS,
4402                                    SourceLocation IdLoc,
4403                                    SourceLocation LParenLoc,
4404                                    Expr **Args, unsigned NumArgs,
4405                                    SourceLocation RParenLoc,
4406                                    SourceLocation EllipsisLoc);
4407
4408  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4409                                    Scope *S,
4410                                    CXXScopeSpec &SS,
4411                                    IdentifierInfo *MemberOrBase,
4412                                    ParsedType TemplateTypeTy,
4413                                    const DeclSpec &DS,
4414                                    SourceLocation IdLoc,
4415                                    Expr *InitList,
4416                                    SourceLocation EllipsisLoc);
4417
4418  MemInitResult BuildMemInitializer(Decl *ConstructorD,
4419                                    Scope *S,
4420                                    CXXScopeSpec &SS,
4421                                    IdentifierInfo *MemberOrBase,
4422                                    ParsedType TemplateTypeTy,
4423                                    const DeclSpec &DS,
4424                                    SourceLocation IdLoc,
4425                                    Expr *Init,
4426                                    SourceLocation EllipsisLoc);
4427
4428  MemInitResult BuildMemberInitializer(ValueDecl *Member,
4429                                       Expr *Init,
4430                                       SourceLocation IdLoc);
4431
4432  MemInitResult BuildBaseInitializer(QualType BaseType,
4433                                     TypeSourceInfo *BaseTInfo,
4434                                     Expr *Init,
4435                                     CXXRecordDecl *ClassDecl,
4436                                     SourceLocation EllipsisLoc);
4437
4438  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4439                                           Expr *Init,
4440                                           CXXRecordDecl *ClassDecl);
4441
4442  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4443                                CXXCtorInitializer *Initializer);
4444
4445  bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4446                           ArrayRef<CXXCtorInitializer *> Initializers =
4447                               ArrayRef<CXXCtorInitializer *>());
4448
4449  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4450
4451
4452  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4453  /// mark all the non-trivial destructors of its members and bases as
4454  /// referenced.
4455  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4456                                              CXXRecordDecl *Record);
4457
4458  /// \brief The list of classes whose vtables have been used within
4459  /// this translation unit, and the source locations at which the
4460  /// first use occurred.
4461  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4462
4463  /// \brief The list of vtables that are required but have not yet been
4464  /// materialized.
4465  SmallVector<VTableUse, 16> VTableUses;
4466
4467  /// \brief The set of classes whose vtables have been used within
4468  /// this translation unit, and a bit that will be true if the vtable is
4469  /// required to be emitted (otherwise, it should be emitted only if needed
4470  /// by code generation).
4471  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4472
4473  /// \brief Load any externally-stored vtable uses.
4474  void LoadExternalVTableUses();
4475
4476  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4477                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4478    DynamicClassesType;
4479
4480  /// \brief A list of all of the dynamic classes in this translation
4481  /// unit.
4482  DynamicClassesType DynamicClasses;
4483
4484  /// \brief Note that the vtable for the given class was used at the
4485  /// given location.
4486  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4487                      bool DefinitionRequired = false);
4488
4489  /// \brief Mark the exception specifications of all virtual member functions
4490  /// in the given class as needed.
4491  void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4492                                             const CXXRecordDecl *RD);
4493
4494  /// MarkVirtualMembersReferenced - Will mark all members of the given
4495  /// CXXRecordDecl referenced.
4496  void MarkVirtualMembersReferenced(SourceLocation Loc,
4497                                    const CXXRecordDecl *RD);
4498
4499  /// \brief Define all of the vtables that have been used in this
4500  /// translation unit and reference any virtual members used by those
4501  /// vtables.
4502  ///
4503  /// \returns true if any work was done, false otherwise.
4504  bool DefineUsedVTables();
4505
4506  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4507
4508  void ActOnMemInitializers(Decl *ConstructorDecl,
4509                            SourceLocation ColonLoc,
4510                            ArrayRef<CXXCtorInitializer*> MemInits,
4511                            bool AnyErrors);
4512
4513  void CheckCompletedCXXClass(CXXRecordDecl *Record);
4514  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4515                                         Decl *TagDecl,
4516                                         SourceLocation LBrac,
4517                                         SourceLocation RBrac,
4518                                         AttributeList *AttrList);
4519  void ActOnFinishCXXMemberDecls();
4520
4521  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4522  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4523  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4524  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4525  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4526  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4527  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4528  void ActOnFinishDelayedMemberInitializers(Decl *Record);
4529  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
4530  bool IsInsideALocalClassWithinATemplateFunction();
4531
4532  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4533                                     Expr *AssertExpr,
4534                                     Expr *AssertMessageExpr,
4535                                     SourceLocation RParenLoc);
4536  Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4537                                     Expr *AssertExpr,
4538                                     StringLiteral *AssertMessageExpr,
4539                                     SourceLocation RParenLoc,
4540                                     bool Failed);
4541
4542  FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4543                                  SourceLocation FriendLoc,
4544                                  TypeSourceInfo *TSInfo);
4545  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4546                            MultiTemplateParamsArg TemplateParams);
4547  NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4548                                     MultiTemplateParamsArg TemplateParams);
4549
4550  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4551                                      StorageClass& SC);
4552  void CheckConstructor(CXXConstructorDecl *Constructor);
4553  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4554                                     StorageClass& SC);
4555  bool CheckDestructor(CXXDestructorDecl *Destructor);
4556  void CheckConversionDeclarator(Declarator &D, QualType &R,
4557                                 StorageClass& SC);
4558  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4559
4560  void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4561  void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4562                                                   const FunctionProtoType *T);
4563  void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
4564
4565  //===--------------------------------------------------------------------===//
4566  // C++ Derived Classes
4567  //
4568
4569  /// ActOnBaseSpecifier - Parsed a base specifier
4570  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4571                                       SourceRange SpecifierRange,
4572                                       bool Virtual, AccessSpecifier Access,
4573                                       TypeSourceInfo *TInfo,
4574                                       SourceLocation EllipsisLoc);
4575
4576  BaseResult ActOnBaseSpecifier(Decl *classdecl,
4577                                SourceRange SpecifierRange,
4578                                ParsedAttributes &Attrs,
4579                                bool Virtual, AccessSpecifier Access,
4580                                ParsedType basetype,
4581                                SourceLocation BaseLoc,
4582                                SourceLocation EllipsisLoc);
4583
4584  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4585                            unsigned NumBases);
4586  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4587                           unsigned NumBases);
4588
4589  bool IsDerivedFrom(QualType Derived, QualType Base);
4590  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4591
4592  // FIXME: I don't like this name.
4593  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4594
4595  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4596
4597  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4598                                    SourceLocation Loc, SourceRange Range,
4599                                    CXXCastPath *BasePath = 0,
4600                                    bool IgnoreAccess = false);
4601  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4602                                    unsigned InaccessibleBaseID,
4603                                    unsigned AmbigiousBaseConvID,
4604                                    SourceLocation Loc, SourceRange Range,
4605                                    DeclarationName Name,
4606                                    CXXCastPath *BasePath);
4607
4608  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4609
4610  bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4611                                         const CXXMethodDecl *Old);
4612
4613  /// CheckOverridingFunctionReturnType - Checks whether the return types are
4614  /// covariant, according to C++ [class.virtual]p5.
4615  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4616                                         const CXXMethodDecl *Old);
4617
4618  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4619  /// spec is a subset of base spec.
4620  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4621                                            const CXXMethodDecl *Old);
4622
4623  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4624
4625  /// CheckOverrideControl - Check C++11 override control semantics.
4626  void CheckOverrideControl(Decl *D);
4627
4628  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4629  /// overrides a virtual member function marked 'final', according to
4630  /// C++11 [class.virtual]p4.
4631  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4632                                              const CXXMethodDecl *Old);
4633
4634
4635  //===--------------------------------------------------------------------===//
4636  // C++ Access Control
4637  //
4638
4639  enum AccessResult {
4640    AR_accessible,
4641    AR_inaccessible,
4642    AR_dependent,
4643    AR_delayed
4644  };
4645
4646  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4647                                NamedDecl *PrevMemberDecl,
4648                                AccessSpecifier LexicalAS);
4649
4650  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4651                                           DeclAccessPair FoundDecl);
4652  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4653                                           DeclAccessPair FoundDecl);
4654  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4655                                     SourceRange PlacementRange,
4656                                     CXXRecordDecl *NamingClass,
4657                                     DeclAccessPair FoundDecl,
4658                                     bool Diagnose = true);
4659  AccessResult CheckConstructorAccess(SourceLocation Loc,
4660                                      CXXConstructorDecl *D,
4661                                      const InitializedEntity &Entity,
4662                                      AccessSpecifier Access,
4663                                      bool IsCopyBindingRefToTemp = false);
4664  AccessResult CheckConstructorAccess(SourceLocation Loc,
4665                                      CXXConstructorDecl *D,
4666                                      const InitializedEntity &Entity,
4667                                      AccessSpecifier Access,
4668                                      const PartialDiagnostic &PDiag);
4669  AccessResult CheckDestructorAccess(SourceLocation Loc,
4670                                     CXXDestructorDecl *Dtor,
4671                                     const PartialDiagnostic &PDiag,
4672                                     QualType objectType = QualType());
4673  AccessResult CheckFriendAccess(NamedDecl *D);
4674  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4675                                         Expr *ObjectExpr,
4676                                         Expr *ArgExpr,
4677                                         DeclAccessPair FoundDecl);
4678  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4679                                          DeclAccessPair FoundDecl);
4680  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4681                                    QualType Base, QualType Derived,
4682                                    const CXXBasePath &Path,
4683                                    unsigned DiagID,
4684                                    bool ForceCheck = false,
4685                                    bool ForceUnprivileged = false);
4686  void CheckLookupAccess(const LookupResult &R);
4687  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4688  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4689                                            AccessSpecifier access,
4690                                            QualType objectType);
4691
4692  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4693                         const MultiLevelTemplateArgumentList &TemplateArgs);
4694  void PerformDependentDiagnostics(const DeclContext *Pattern,
4695                        const MultiLevelTemplateArgumentList &TemplateArgs);
4696
4697  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4698
4699  /// \brief When true, access checking violations are treated as SFINAE
4700  /// failures rather than hard errors.
4701  bool AccessCheckingSFINAE;
4702
4703  enum AbstractDiagSelID {
4704    AbstractNone = -1,
4705    AbstractReturnType,
4706    AbstractParamType,
4707    AbstractVariableType,
4708    AbstractFieldType,
4709    AbstractIvarType,
4710    AbstractArrayType
4711  };
4712
4713  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4714                              TypeDiagnoser &Diagnoser);
4715  template<typename T1>
4716  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4717                              unsigned DiagID,
4718                              const T1 &Arg1) {
4719    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
4720    return RequireNonAbstractType(Loc, T, Diagnoser);
4721  }
4722
4723  template<typename T1, typename T2>
4724  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4725                              unsigned DiagID,
4726                              const T1 &Arg1, const T2 &Arg2) {
4727    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
4728    return RequireNonAbstractType(Loc, T, Diagnoser);
4729  }
4730
4731  template<typename T1, typename T2, typename T3>
4732  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4733                              unsigned DiagID,
4734                              const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
4735    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
4736    return RequireNonAbstractType(Loc, T, Diagnoser);
4737  }
4738
4739  void DiagnoseAbstractType(const CXXRecordDecl *RD);
4740
4741  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4742                              AbstractDiagSelID SelID = AbstractNone);
4743
4744  //===--------------------------------------------------------------------===//
4745  // C++ Overloaded Operators [C++ 13.5]
4746  //
4747
4748  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4749
4750  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4751
4752  //===--------------------------------------------------------------------===//
4753  // C++ Templates [C++ 14]
4754  //
4755  void FilterAcceptableTemplateNames(LookupResult &R,
4756                                     bool AllowFunctionTemplates = true);
4757  bool hasAnyAcceptableTemplateNames(LookupResult &R,
4758                                     bool AllowFunctionTemplates = true);
4759
4760  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4761                          QualType ObjectType, bool EnteringContext,
4762                          bool &MemberOfUnknownSpecialization);
4763
4764  TemplateNameKind isTemplateName(Scope *S,
4765                                  CXXScopeSpec &SS,
4766                                  bool hasTemplateKeyword,
4767                                  UnqualifiedId &Name,
4768                                  ParsedType ObjectType,
4769                                  bool EnteringContext,
4770                                  TemplateTy &Template,
4771                                  bool &MemberOfUnknownSpecialization);
4772
4773  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
4774                                   SourceLocation IILoc,
4775                                   Scope *S,
4776                                   const CXXScopeSpec *SS,
4777                                   TemplateTy &SuggestedTemplate,
4778                                   TemplateNameKind &SuggestedKind);
4779
4780  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
4781  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
4782
4783  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
4784                           SourceLocation EllipsisLoc,
4785                           SourceLocation KeyLoc,
4786                           IdentifierInfo *ParamName,
4787                           SourceLocation ParamNameLoc,
4788                           unsigned Depth, unsigned Position,
4789                           SourceLocation EqualLoc,
4790                           ParsedType DefaultArg);
4791
4792  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
4793  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
4794                                      unsigned Depth,
4795                                      unsigned Position,
4796                                      SourceLocation EqualLoc,
4797                                      Expr *DefaultArg);
4798  Decl *ActOnTemplateTemplateParameter(Scope *S,
4799                                       SourceLocation TmpLoc,
4800                                       TemplateParameterList *Params,
4801                                       SourceLocation EllipsisLoc,
4802                                       IdentifierInfo *ParamName,
4803                                       SourceLocation ParamNameLoc,
4804                                       unsigned Depth,
4805                                       unsigned Position,
4806                                       SourceLocation EqualLoc,
4807                                       ParsedTemplateArgument DefaultArg);
4808
4809  TemplateParameterList *
4810  ActOnTemplateParameterList(unsigned Depth,
4811                             SourceLocation ExportLoc,
4812                             SourceLocation TemplateLoc,
4813                             SourceLocation LAngleLoc,
4814                             Decl **Params, unsigned NumParams,
4815                             SourceLocation RAngleLoc);
4816
4817  /// \brief The context in which we are checking a template parameter
4818  /// list.
4819  enum TemplateParamListContext {
4820    TPC_ClassTemplate,
4821    TPC_FunctionTemplate,
4822    TPC_ClassTemplateMember,
4823    TPC_FriendFunctionTemplate,
4824    TPC_FriendFunctionTemplateDefinition,
4825    TPC_TypeAliasTemplate
4826  };
4827
4828  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
4829                                  TemplateParameterList *OldParams,
4830                                  TemplateParamListContext TPC);
4831  TemplateParameterList *
4832  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
4833                                          SourceLocation DeclLoc,
4834                                          const CXXScopeSpec &SS,
4835                                          TemplateParameterList **ParamLists,
4836                                          unsigned NumParamLists,
4837                                          bool IsFriend,
4838                                          bool &IsExplicitSpecialization,
4839                                          bool &Invalid);
4840
4841  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
4842                                SourceLocation KWLoc, CXXScopeSpec &SS,
4843                                IdentifierInfo *Name, SourceLocation NameLoc,
4844                                AttributeList *Attr,
4845                                TemplateParameterList *TemplateParams,
4846                                AccessSpecifier AS,
4847                                SourceLocation ModulePrivateLoc,
4848                                unsigned NumOuterTemplateParamLists,
4849                            TemplateParameterList **OuterTemplateParamLists);
4850
4851  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
4852                                  TemplateArgumentListInfo &Out);
4853
4854  void NoteAllFoundTemplates(TemplateName Name);
4855
4856  QualType CheckTemplateIdType(TemplateName Template,
4857                               SourceLocation TemplateLoc,
4858                              TemplateArgumentListInfo &TemplateArgs);
4859
4860  TypeResult
4861  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4862                      TemplateTy Template, SourceLocation TemplateLoc,
4863                      SourceLocation LAngleLoc,
4864                      ASTTemplateArgsPtr TemplateArgs,
4865                      SourceLocation RAngleLoc,
4866                      bool IsCtorOrDtorName = false);
4867
4868  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
4869  /// such as \c class T::template apply<U>.
4870  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
4871                                    TypeSpecifierType TagSpec,
4872                                    SourceLocation TagLoc,
4873                                    CXXScopeSpec &SS,
4874                                    SourceLocation TemplateKWLoc,
4875                                    TemplateTy TemplateD,
4876                                    SourceLocation TemplateLoc,
4877                                    SourceLocation LAngleLoc,
4878                                    ASTTemplateArgsPtr TemplateArgsIn,
4879                                    SourceLocation RAngleLoc);
4880
4881
4882  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
4883                                 SourceLocation TemplateKWLoc,
4884                                 LookupResult &R,
4885                                 bool RequiresADL,
4886                               const TemplateArgumentListInfo *TemplateArgs);
4887
4888  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4889                                          SourceLocation TemplateKWLoc,
4890                               const DeclarationNameInfo &NameInfo,
4891                               const TemplateArgumentListInfo *TemplateArgs);
4892
4893  TemplateNameKind ActOnDependentTemplateName(Scope *S,
4894                                              CXXScopeSpec &SS,
4895                                              SourceLocation TemplateKWLoc,
4896                                              UnqualifiedId &Name,
4897                                              ParsedType ObjectType,
4898                                              bool EnteringContext,
4899                                              TemplateTy &Template);
4900
4901  DeclResult
4902  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
4903                                   SourceLocation KWLoc,
4904                                   SourceLocation ModulePrivateLoc,
4905                                   CXXScopeSpec &SS,
4906                                   TemplateTy Template,
4907                                   SourceLocation TemplateNameLoc,
4908                                   SourceLocation LAngleLoc,
4909                                   ASTTemplateArgsPtr TemplateArgs,
4910                                   SourceLocation RAngleLoc,
4911                                   AttributeList *Attr,
4912                                 MultiTemplateParamsArg TemplateParameterLists);
4913
4914  Decl *ActOnTemplateDeclarator(Scope *S,
4915                                MultiTemplateParamsArg TemplateParameterLists,
4916                                Declarator &D);
4917
4918  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4919                                  MultiTemplateParamsArg TemplateParameterLists,
4920                                        Declarator &D);
4921
4922  bool
4923  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4924                                         TemplateSpecializationKind NewTSK,
4925                                         NamedDecl *PrevDecl,
4926                                         TemplateSpecializationKind PrevTSK,
4927                                         SourceLocation PrevPtOfInstantiation,
4928                                         bool &SuppressNew);
4929
4930  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4931                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
4932                                                    LookupResult &Previous);
4933
4934  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4935                         TemplateArgumentListInfo *ExplicitTemplateArgs,
4936                                           LookupResult &Previous);
4937  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
4938
4939  DeclResult
4940  ActOnExplicitInstantiation(Scope *S,
4941                             SourceLocation ExternLoc,
4942                             SourceLocation TemplateLoc,
4943                             unsigned TagSpec,
4944                             SourceLocation KWLoc,
4945                             const CXXScopeSpec &SS,
4946                             TemplateTy Template,
4947                             SourceLocation TemplateNameLoc,
4948                             SourceLocation LAngleLoc,
4949                             ASTTemplateArgsPtr TemplateArgs,
4950                             SourceLocation RAngleLoc,
4951                             AttributeList *Attr);
4952
4953  DeclResult
4954  ActOnExplicitInstantiation(Scope *S,
4955                             SourceLocation ExternLoc,
4956                             SourceLocation TemplateLoc,
4957                             unsigned TagSpec,
4958                             SourceLocation KWLoc,
4959                             CXXScopeSpec &SS,
4960                             IdentifierInfo *Name,
4961                             SourceLocation NameLoc,
4962                             AttributeList *Attr);
4963
4964  DeclResult ActOnExplicitInstantiation(Scope *S,
4965                                        SourceLocation ExternLoc,
4966                                        SourceLocation TemplateLoc,
4967                                        Declarator &D);
4968
4969  TemplateArgumentLoc
4970  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4971                                          SourceLocation TemplateLoc,
4972                                          SourceLocation RAngleLoc,
4973                                          Decl *Param,
4974                          SmallVectorImpl<TemplateArgument> &Converted);
4975
4976  /// \brief Specifies the context in which a particular template
4977  /// argument is being checked.
4978  enum CheckTemplateArgumentKind {
4979    /// \brief The template argument was specified in the code or was
4980    /// instantiated with some deduced template arguments.
4981    CTAK_Specified,
4982
4983    /// \brief The template argument was deduced via template argument
4984    /// deduction.
4985    CTAK_Deduced,
4986
4987    /// \brief The template argument was deduced from an array bound
4988    /// via template argument deduction.
4989    CTAK_DeducedFromArrayBound
4990  };
4991
4992  bool CheckTemplateArgument(NamedDecl *Param,
4993                             const TemplateArgumentLoc &Arg,
4994                             NamedDecl *Template,
4995                             SourceLocation TemplateLoc,
4996                             SourceLocation RAngleLoc,
4997                             unsigned ArgumentPackIndex,
4998                           SmallVectorImpl<TemplateArgument> &Converted,
4999                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
5000
5001  /// \brief Check that the given template arguments can be be provided to
5002  /// the given template, converting the arguments along the way.
5003  ///
5004  /// \param Template The template to which the template arguments are being
5005  /// provided.
5006  ///
5007  /// \param TemplateLoc The location of the template name in the source.
5008  ///
5009  /// \param TemplateArgs The list of template arguments. If the template is
5010  /// a template template parameter, this function may extend the set of
5011  /// template arguments to also include substituted, defaulted template
5012  /// arguments.
5013  ///
5014  /// \param PartialTemplateArgs True if the list of template arguments is
5015  /// intentionally partial, e.g., because we're checking just the initial
5016  /// set of template arguments.
5017  ///
5018  /// \param Converted Will receive the converted, canonicalized template
5019  /// arguments.
5020  ///
5021  ///
5022  /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
5023  /// when the template arguments contain a pack expansion that is being
5024  /// expanded into a fixed parameter list.
5025  ///
5026  /// \returns True if an error occurred, false otherwise.
5027  bool CheckTemplateArgumentList(TemplateDecl *Template,
5028                                 SourceLocation TemplateLoc,
5029                                 TemplateArgumentListInfo &TemplateArgs,
5030                                 bool PartialTemplateArgs,
5031                           SmallVectorImpl<TemplateArgument> &Converted,
5032                                 bool *ExpansionIntoFixedList = 0);
5033
5034  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5035                                 const TemplateArgumentLoc &Arg,
5036                           SmallVectorImpl<TemplateArgument> &Converted);
5037
5038  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5039                             TypeSourceInfo *Arg);
5040  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5041                                   QualType InstantiatedParamType, Expr *Arg,
5042                                   TemplateArgument &Converted,
5043                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
5044  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5045                             const TemplateArgumentLoc &Arg,
5046                             unsigned ArgumentPackIndex);
5047
5048  ExprResult
5049  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5050                                          QualType ParamType,
5051                                          SourceLocation Loc);
5052  ExprResult
5053  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5054                                              SourceLocation Loc);
5055
5056  /// \brief Enumeration describing how template parameter lists are compared
5057  /// for equality.
5058  enum TemplateParameterListEqualKind {
5059    /// \brief We are matching the template parameter lists of two templates
5060    /// that might be redeclarations.
5061    ///
5062    /// \code
5063    /// template<typename T> struct X;
5064    /// template<typename T> struct X;
5065    /// \endcode
5066    TPL_TemplateMatch,
5067
5068    /// \brief We are matching the template parameter lists of two template
5069    /// template parameters as part of matching the template parameter lists
5070    /// of two templates that might be redeclarations.
5071    ///
5072    /// \code
5073    /// template<template<int I> class TT> struct X;
5074    /// template<template<int Value> class Other> struct X;
5075    /// \endcode
5076    TPL_TemplateTemplateParmMatch,
5077
5078    /// \brief We are matching the template parameter lists of a template
5079    /// template argument against the template parameter lists of a template
5080    /// template parameter.
5081    ///
5082    /// \code
5083    /// template<template<int Value> class Metafun> struct X;
5084    /// template<int Value> struct integer_c;
5085    /// X<integer_c> xic;
5086    /// \endcode
5087    TPL_TemplateTemplateArgumentMatch
5088  };
5089
5090  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5091                                      TemplateParameterList *Old,
5092                                      bool Complain,
5093                                      TemplateParameterListEqualKind Kind,
5094                                      SourceLocation TemplateArgLoc
5095                                        = SourceLocation());
5096
5097  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5098
5099  /// \brief Called when the parser has parsed a C++ typename
5100  /// specifier, e.g., "typename T::type".
5101  ///
5102  /// \param S The scope in which this typename type occurs.
5103  /// \param TypenameLoc the location of the 'typename' keyword
5104  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5105  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5106  /// \param IdLoc the location of the identifier.
5107  TypeResult
5108  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5109                    const CXXScopeSpec &SS, const IdentifierInfo &II,
5110                    SourceLocation IdLoc);
5111
5112  /// \brief Called when the parser has parsed a C++ typename
5113  /// specifier that ends in a template-id, e.g.,
5114  /// "typename MetaFun::template apply<T1, T2>".
5115  ///
5116  /// \param S The scope in which this typename type occurs.
5117  /// \param TypenameLoc the location of the 'typename' keyword
5118  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5119  /// \param TemplateLoc the location of the 'template' keyword, if any.
5120  /// \param TemplateName The template name.
5121  /// \param TemplateNameLoc The location of the template name.
5122  /// \param LAngleLoc The location of the opening angle bracket  ('<').
5123  /// \param TemplateArgs The template arguments.
5124  /// \param RAngleLoc The location of the closing angle bracket  ('>').
5125  TypeResult
5126  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5127                    const CXXScopeSpec &SS,
5128                    SourceLocation TemplateLoc,
5129                    TemplateTy TemplateName,
5130                    SourceLocation TemplateNameLoc,
5131                    SourceLocation LAngleLoc,
5132                    ASTTemplateArgsPtr TemplateArgs,
5133                    SourceLocation RAngleLoc);
5134
5135  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5136                             SourceLocation KeywordLoc,
5137                             NestedNameSpecifierLoc QualifierLoc,
5138                             const IdentifierInfo &II,
5139                             SourceLocation IILoc);
5140
5141  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5142                                                    SourceLocation Loc,
5143                                                    DeclarationName Name);
5144  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5145
5146  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5147  bool RebuildTemplateParamsInCurrentInstantiation(
5148                                                TemplateParameterList *Params);
5149
5150  std::string
5151  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5152                                  const TemplateArgumentList &Args);
5153
5154  std::string
5155  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5156                                  const TemplateArgument *Args,
5157                                  unsigned NumArgs);
5158
5159  //===--------------------------------------------------------------------===//
5160  // C++ Variadic Templates (C++0x [temp.variadic])
5161  //===--------------------------------------------------------------------===//
5162
5163  /// \brief The context in which an unexpanded parameter pack is
5164  /// being diagnosed.
5165  ///
5166  /// Note that the values of this enumeration line up with the first
5167  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5168  enum UnexpandedParameterPackContext {
5169    /// \brief An arbitrary expression.
5170    UPPC_Expression = 0,
5171
5172    /// \brief The base type of a class type.
5173    UPPC_BaseType,
5174
5175    /// \brief The type of an arbitrary declaration.
5176    UPPC_DeclarationType,
5177
5178    /// \brief The type of a data member.
5179    UPPC_DataMemberType,
5180
5181    /// \brief The size of a bit-field.
5182    UPPC_BitFieldWidth,
5183
5184    /// \brief The expression in a static assertion.
5185    UPPC_StaticAssertExpression,
5186
5187    /// \brief The fixed underlying type of an enumeration.
5188    UPPC_FixedUnderlyingType,
5189
5190    /// \brief The enumerator value.
5191    UPPC_EnumeratorValue,
5192
5193    /// \brief A using declaration.
5194    UPPC_UsingDeclaration,
5195
5196    /// \brief A friend declaration.
5197    UPPC_FriendDeclaration,
5198
5199    /// \brief A declaration qualifier.
5200    UPPC_DeclarationQualifier,
5201
5202    /// \brief An initializer.
5203    UPPC_Initializer,
5204
5205    /// \brief A default argument.
5206    UPPC_DefaultArgument,
5207
5208    /// \brief The type of a non-type template parameter.
5209    UPPC_NonTypeTemplateParameterType,
5210
5211    /// \brief The type of an exception.
5212    UPPC_ExceptionType,
5213
5214    /// \brief Partial specialization.
5215    UPPC_PartialSpecialization,
5216
5217    /// \brief Microsoft __if_exists.
5218    UPPC_IfExists,
5219
5220    /// \brief Microsoft __if_not_exists.
5221    UPPC_IfNotExists,
5222
5223    /// \brief Lambda expression.
5224    UPPC_Lambda,
5225
5226    /// \brief Block expression,
5227    UPPC_Block
5228};
5229
5230  /// \brief Diagnose unexpanded parameter packs.
5231  ///
5232  /// \param Loc The location at which we should emit the diagnostic.
5233  ///
5234  /// \param UPPC The context in which we are diagnosing unexpanded
5235  /// parameter packs.
5236  ///
5237  /// \param Unexpanded the set of unexpanded parameter packs.
5238  ///
5239  /// \returns true if an error occurred, false otherwise.
5240  bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5241                                        UnexpandedParameterPackContext UPPC,
5242                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
5243
5244  /// \brief If the given type contains an unexpanded parameter pack,
5245  /// diagnose the error.
5246  ///
5247  /// \param Loc The source location where a diagnostc should be emitted.
5248  ///
5249  /// \param T The type that is being checked for unexpanded parameter
5250  /// packs.
5251  ///
5252  /// \returns true if an error occurred, false otherwise.
5253  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5254                                       UnexpandedParameterPackContext UPPC);
5255
5256  /// \brief If the given expression contains an unexpanded parameter
5257  /// pack, diagnose the error.
5258  ///
5259  /// \param E The expression that is being checked for unexpanded
5260  /// parameter packs.
5261  ///
5262  /// \returns true if an error occurred, false otherwise.
5263  bool DiagnoseUnexpandedParameterPack(Expr *E,
5264                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
5265
5266  /// \brief If the given nested-name-specifier contains an unexpanded
5267  /// parameter pack, diagnose the error.
5268  ///
5269  /// \param SS The nested-name-specifier that is being checked for
5270  /// unexpanded parameter packs.
5271  ///
5272  /// \returns true if an error occurred, false otherwise.
5273  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5274                                       UnexpandedParameterPackContext UPPC);
5275
5276  /// \brief If the given name contains an unexpanded parameter pack,
5277  /// diagnose the error.
5278  ///
5279  /// \param NameInfo The name (with source location information) that
5280  /// is being checked for unexpanded parameter packs.
5281  ///
5282  /// \returns true if an error occurred, false otherwise.
5283  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5284                                       UnexpandedParameterPackContext UPPC);
5285
5286  /// \brief If the given template name contains an unexpanded parameter pack,
5287  /// diagnose the error.
5288  ///
5289  /// \param Loc The location of the template name.
5290  ///
5291  /// \param Template The template name that is being checked for unexpanded
5292  /// parameter packs.
5293  ///
5294  /// \returns true if an error occurred, false otherwise.
5295  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5296                                       TemplateName Template,
5297                                       UnexpandedParameterPackContext UPPC);
5298
5299  /// \brief If the given template argument contains an unexpanded parameter
5300  /// pack, diagnose the error.
5301  ///
5302  /// \param Arg The template argument that is being checked for unexpanded
5303  /// parameter packs.
5304  ///
5305  /// \returns true if an error occurred, false otherwise.
5306  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5307                                       UnexpandedParameterPackContext UPPC);
5308
5309  /// \brief Collect the set of unexpanded parameter packs within the given
5310  /// template argument.
5311  ///
5312  /// \param Arg The template argument that will be traversed to find
5313  /// unexpanded parameter packs.
5314  void collectUnexpandedParameterPacks(TemplateArgument Arg,
5315                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5316
5317  /// \brief Collect the set of unexpanded parameter packs within the given
5318  /// template argument.
5319  ///
5320  /// \param Arg The template argument that will be traversed to find
5321  /// unexpanded parameter packs.
5322  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5323                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5324
5325  /// \brief Collect the set of unexpanded parameter packs within the given
5326  /// type.
5327  ///
5328  /// \param T The type that will be traversed to find
5329  /// unexpanded parameter packs.
5330  void collectUnexpandedParameterPacks(QualType T,
5331                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5332
5333  /// \brief Collect the set of unexpanded parameter packs within the given
5334  /// type.
5335  ///
5336  /// \param TL The type that will be traversed to find
5337  /// unexpanded parameter packs.
5338  void collectUnexpandedParameterPacks(TypeLoc TL,
5339                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5340
5341  /// \brief Collect the set of unexpanded parameter packs within the given
5342  /// nested-name-specifier.
5343  ///
5344  /// \param SS The nested-name-specifier that will be traversed to find
5345  /// unexpanded parameter packs.
5346  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5347                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5348
5349  /// \brief Collect the set of unexpanded parameter packs within the given
5350  /// name.
5351  ///
5352  /// \param NameInfo The name that will be traversed to find
5353  /// unexpanded parameter packs.
5354  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5355                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5356
5357  /// \brief Invoked when parsing a template argument followed by an
5358  /// ellipsis, which creates a pack expansion.
5359  ///
5360  /// \param Arg The template argument preceding the ellipsis, which
5361  /// may already be invalid.
5362  ///
5363  /// \param EllipsisLoc The location of the ellipsis.
5364  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5365                                            SourceLocation EllipsisLoc);
5366
5367  /// \brief Invoked when parsing a type followed by an ellipsis, which
5368  /// creates a pack expansion.
5369  ///
5370  /// \param Type The type preceding the ellipsis, which will become
5371  /// the pattern of the pack expansion.
5372  ///
5373  /// \param EllipsisLoc The location of the ellipsis.
5374  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5375
5376  /// \brief Construct a pack expansion type from the pattern of the pack
5377  /// expansion.
5378  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5379                                     SourceLocation EllipsisLoc,
5380                                     Optional<unsigned> NumExpansions);
5381
5382  /// \brief Construct a pack expansion type from the pattern of the pack
5383  /// expansion.
5384  QualType CheckPackExpansion(QualType Pattern,
5385                              SourceRange PatternRange,
5386                              SourceLocation EllipsisLoc,
5387                              Optional<unsigned> NumExpansions);
5388
5389  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5390  /// creates a pack expansion.
5391  ///
5392  /// \param Pattern The expression preceding the ellipsis, which will become
5393  /// the pattern of the pack expansion.
5394  ///
5395  /// \param EllipsisLoc The location of the ellipsis.
5396  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5397
5398  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5399  /// creates a pack expansion.
5400  ///
5401  /// \param Pattern The expression preceding the ellipsis, which will become
5402  /// the pattern of the pack expansion.
5403  ///
5404  /// \param EllipsisLoc The location of the ellipsis.
5405  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5406                                Optional<unsigned> NumExpansions);
5407
5408  /// \brief Determine whether we could expand a pack expansion with the
5409  /// given set of parameter packs into separate arguments by repeatedly
5410  /// transforming the pattern.
5411  ///
5412  /// \param EllipsisLoc The location of the ellipsis that identifies the
5413  /// pack expansion.
5414  ///
5415  /// \param PatternRange The source range that covers the entire pattern of
5416  /// the pack expansion.
5417  ///
5418  /// \param Unexpanded The set of unexpanded parameter packs within the
5419  /// pattern.
5420  ///
5421  /// \param ShouldExpand Will be set to \c true if the transformer should
5422  /// expand the corresponding pack expansions into separate arguments. When
5423  /// set, \c NumExpansions must also be set.
5424  ///
5425  /// \param RetainExpansion Whether the caller should add an unexpanded
5426  /// pack expansion after all of the expanded arguments. This is used
5427  /// when extending explicitly-specified template argument packs per
5428  /// C++0x [temp.arg.explicit]p9.
5429  ///
5430  /// \param NumExpansions The number of separate arguments that will be in
5431  /// the expanded form of the corresponding pack expansion. This is both an
5432  /// input and an output parameter, which can be set by the caller if the
5433  /// number of expansions is known a priori (e.g., due to a prior substitution)
5434  /// and will be set by the callee when the number of expansions is known.
5435  /// The callee must set this value when \c ShouldExpand is \c true; it may
5436  /// set this value in other cases.
5437  ///
5438  /// \returns true if an error occurred (e.g., because the parameter packs
5439  /// are to be instantiated with arguments of different lengths), false
5440  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5441  /// must be set.
5442  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5443                                       SourceRange PatternRange,
5444                             ArrayRef<UnexpandedParameterPack> Unexpanded,
5445                             const MultiLevelTemplateArgumentList &TemplateArgs,
5446                                       bool &ShouldExpand,
5447                                       bool &RetainExpansion,
5448                                       Optional<unsigned> &NumExpansions);
5449
5450  /// \brief Determine the number of arguments in the given pack expansion
5451  /// type.
5452  ///
5453  /// This routine assumes that the number of arguments in the expansion is
5454  /// consistent across all of the unexpanded parameter packs in its pattern.
5455  ///
5456  /// Returns an empty Optional if the type can't be expanded.
5457  Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5458      const MultiLevelTemplateArgumentList &TemplateArgs);
5459
5460  /// \brief Determine whether the given declarator contains any unexpanded
5461  /// parameter packs.
5462  ///
5463  /// This routine is used by the parser to disambiguate function declarators
5464  /// with an ellipsis prior to the ')', e.g.,
5465  ///
5466  /// \code
5467  ///   void f(T...);
5468  /// \endcode
5469  ///
5470  /// To determine whether we have an (unnamed) function parameter pack or
5471  /// a variadic function.
5472  ///
5473  /// \returns true if the declarator contains any unexpanded parameter packs,
5474  /// false otherwise.
5475  bool containsUnexpandedParameterPacks(Declarator &D);
5476
5477  //===--------------------------------------------------------------------===//
5478  // C++ Template Argument Deduction (C++ [temp.deduct])
5479  //===--------------------------------------------------------------------===//
5480
5481  /// \brief Describes the result of template argument deduction.
5482  ///
5483  /// The TemplateDeductionResult enumeration describes the result of
5484  /// template argument deduction, as returned from
5485  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5486  /// structure provides additional information about the results of
5487  /// template argument deduction, e.g., the deduced template argument
5488  /// list (if successful) or the specific template parameters or
5489  /// deduced arguments that were involved in the failure.
5490  enum TemplateDeductionResult {
5491    /// \brief Template argument deduction was successful.
5492    TDK_Success = 0,
5493    /// \brief The declaration was invalid; do nothing.
5494    TDK_Invalid,
5495    /// \brief Template argument deduction exceeded the maximum template
5496    /// instantiation depth (which has already been diagnosed).
5497    TDK_InstantiationDepth,
5498    /// \brief Template argument deduction did not deduce a value
5499    /// for every template parameter.
5500    TDK_Incomplete,
5501    /// \brief Template argument deduction produced inconsistent
5502    /// deduced values for the given template parameter.
5503    TDK_Inconsistent,
5504    /// \brief Template argument deduction failed due to inconsistent
5505    /// cv-qualifiers on a template parameter type that would
5506    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5507    /// but were given a non-const "X".
5508    TDK_Underqualified,
5509    /// \brief Substitution of the deduced template argument values
5510    /// resulted in an error.
5511    TDK_SubstitutionFailure,
5512    /// \brief A non-depnedent component of the parameter did not match the
5513    /// corresponding component of the argument.
5514    TDK_NonDeducedMismatch,
5515    /// \brief When performing template argument deduction for a function
5516    /// template, there were too many call arguments.
5517    TDK_TooManyArguments,
5518    /// \brief When performing template argument deduction for a function
5519    /// template, there were too few call arguments.
5520    TDK_TooFewArguments,
5521    /// \brief The explicitly-specified template arguments were not valid
5522    /// template arguments for the given template.
5523    TDK_InvalidExplicitArguments,
5524    /// \brief The arguments included an overloaded function name that could
5525    /// not be resolved to a suitable function.
5526    TDK_FailedOverloadResolution,
5527    /// \brief Deduction failed; that's all we know.
5528    TDK_MiscellaneousDeductionFailure
5529  };
5530
5531  TemplateDeductionResult
5532  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5533                          const TemplateArgumentList &TemplateArgs,
5534                          sema::TemplateDeductionInfo &Info);
5535
5536  TemplateDeductionResult
5537  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5538                              TemplateArgumentListInfo &ExplicitTemplateArgs,
5539                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5540                                 SmallVectorImpl<QualType> &ParamTypes,
5541                                      QualType *FunctionType,
5542                                      sema::TemplateDeductionInfo &Info);
5543
5544  /// brief A function argument from which we performed template argument
5545  // deduction for a call.
5546  struct OriginalCallArg {
5547    OriginalCallArg(QualType OriginalParamType,
5548                    unsigned ArgIdx,
5549                    QualType OriginalArgType)
5550      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5551        OriginalArgType(OriginalArgType) { }
5552
5553    QualType OriginalParamType;
5554    unsigned ArgIdx;
5555    QualType OriginalArgType;
5556  };
5557
5558  TemplateDeductionResult
5559  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5560                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5561                                  unsigned NumExplicitlySpecified,
5562                                  FunctionDecl *&Specialization,
5563                                  sema::TemplateDeductionInfo &Info,
5564           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5565
5566  TemplateDeductionResult
5567  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5568                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5569                          ArrayRef<Expr *> Args,
5570                          FunctionDecl *&Specialization,
5571                          sema::TemplateDeductionInfo &Info);
5572
5573  TemplateDeductionResult
5574  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5575                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5576                          QualType ArgFunctionType,
5577                          FunctionDecl *&Specialization,
5578                          sema::TemplateDeductionInfo &Info);
5579
5580  TemplateDeductionResult
5581  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5582                          QualType ToType,
5583                          CXXConversionDecl *&Specialization,
5584                          sema::TemplateDeductionInfo &Info);
5585
5586  TemplateDeductionResult
5587  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5588                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5589                          FunctionDecl *&Specialization,
5590                          sema::TemplateDeductionInfo &Info);
5591
5592  /// \brief Result type of DeduceAutoType.
5593  enum DeduceAutoResult {
5594    DAR_Succeeded,
5595    DAR_Failed,
5596    DAR_FailedAlreadyDiagnosed
5597  };
5598
5599  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5600                                  TypeSourceInfo *&Result);
5601  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5602
5603  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5604                                                   FunctionTemplateDecl *FT2,
5605                                                   SourceLocation Loc,
5606                                           TemplatePartialOrderingContext TPOC,
5607                                                   unsigned NumCallArguments);
5608  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
5609                                           UnresolvedSetIterator SEnd,
5610                                           TemplatePartialOrderingContext TPOC,
5611                                           unsigned NumCallArguments,
5612                                           SourceLocation Loc,
5613                                           const PartialDiagnostic &NoneDiag,
5614                                           const PartialDiagnostic &AmbigDiag,
5615                                        const PartialDiagnostic &CandidateDiag,
5616                                        bool Complain = true,
5617                                        QualType TargetType = QualType());
5618
5619  ClassTemplatePartialSpecializationDecl *
5620  getMoreSpecializedPartialSpecialization(
5621                                  ClassTemplatePartialSpecializationDecl *PS1,
5622                                  ClassTemplatePartialSpecializationDecl *PS2,
5623                                  SourceLocation Loc);
5624
5625  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5626                                  bool OnlyDeduced,
5627                                  unsigned Depth,
5628                                  llvm::SmallBitVector &Used);
5629  void MarkDeducedTemplateParameters(
5630                                  const FunctionTemplateDecl *FunctionTemplate,
5631                                  llvm::SmallBitVector &Deduced) {
5632    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5633  }
5634  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5635                                  const FunctionTemplateDecl *FunctionTemplate,
5636                                  llvm::SmallBitVector &Deduced);
5637
5638  //===--------------------------------------------------------------------===//
5639  // C++ Template Instantiation
5640  //
5641
5642  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5643                                     const TemplateArgumentList *Innermost = 0,
5644                                                bool RelativeToPrimary = false,
5645                                               const FunctionDecl *Pattern = 0);
5646
5647  /// \brief A template instantiation that is currently in progress.
5648  struct ActiveTemplateInstantiation {
5649    /// \brief The kind of template instantiation we are performing
5650    enum InstantiationKind {
5651      /// We are instantiating a template declaration. The entity is
5652      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5653      TemplateInstantiation,
5654
5655      /// We are instantiating a default argument for a template
5656      /// parameter. The Entity is the template, and
5657      /// TemplateArgs/NumTemplateArguments provides the template
5658      /// arguments as specified.
5659      /// FIXME: Use a TemplateArgumentList
5660      DefaultTemplateArgumentInstantiation,
5661
5662      /// We are instantiating a default argument for a function.
5663      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5664      /// provides the template arguments as specified.
5665      DefaultFunctionArgumentInstantiation,
5666
5667      /// We are substituting explicit template arguments provided for
5668      /// a function template. The entity is a FunctionTemplateDecl.
5669      ExplicitTemplateArgumentSubstitution,
5670
5671      /// We are substituting template argument determined as part of
5672      /// template argument deduction for either a class template
5673      /// partial specialization or a function template. The
5674      /// Entity is either a ClassTemplatePartialSpecializationDecl or
5675      /// a FunctionTemplateDecl.
5676      DeducedTemplateArgumentSubstitution,
5677
5678      /// We are substituting prior template arguments into a new
5679      /// template parameter. The template parameter itself is either a
5680      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5681      PriorTemplateArgumentSubstitution,
5682
5683      /// We are checking the validity of a default template argument that
5684      /// has been used when naming a template-id.
5685      DefaultTemplateArgumentChecking,
5686
5687      /// We are instantiating the exception specification for a function
5688      /// template which was deferred until it was needed.
5689      ExceptionSpecInstantiation
5690    } Kind;
5691
5692    /// \brief The point of instantiation within the source code.
5693    SourceLocation PointOfInstantiation;
5694
5695    /// \brief The template (or partial specialization) in which we are
5696    /// performing the instantiation, for substitutions of prior template
5697    /// arguments.
5698    NamedDecl *Template;
5699
5700    /// \brief The entity that is being instantiated.
5701    Decl *Entity;
5702
5703    /// \brief The list of template arguments we are substituting, if they
5704    /// are not part of the entity.
5705    const TemplateArgument *TemplateArgs;
5706
5707    /// \brief The number of template arguments in TemplateArgs.
5708    unsigned NumTemplateArgs;
5709
5710    /// \brief The template deduction info object associated with the
5711    /// substitution or checking of explicit or deduced template arguments.
5712    sema::TemplateDeductionInfo *DeductionInfo;
5713
5714    /// \brief The source range that covers the construct that cause
5715    /// the instantiation, e.g., the template-id that causes a class
5716    /// template instantiation.
5717    SourceRange InstantiationRange;
5718
5719    ActiveTemplateInstantiation()
5720      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
5721        NumTemplateArgs(0), DeductionInfo(0) {}
5722
5723    /// \brief Determines whether this template is an actual instantiation
5724    /// that should be counted toward the maximum instantiation depth.
5725    bool isInstantiationRecord() const;
5726
5727    friend bool operator==(const ActiveTemplateInstantiation &X,
5728                           const ActiveTemplateInstantiation &Y) {
5729      if (X.Kind != Y.Kind)
5730        return false;
5731
5732      if (X.Entity != Y.Entity)
5733        return false;
5734
5735      switch (X.Kind) {
5736      case TemplateInstantiation:
5737      case ExceptionSpecInstantiation:
5738        return true;
5739
5740      case PriorTemplateArgumentSubstitution:
5741      case DefaultTemplateArgumentChecking:
5742        if (X.Template != Y.Template)
5743          return false;
5744
5745        // Fall through
5746
5747      case DefaultTemplateArgumentInstantiation:
5748      case ExplicitTemplateArgumentSubstitution:
5749      case DeducedTemplateArgumentSubstitution:
5750      case DefaultFunctionArgumentInstantiation:
5751        return X.TemplateArgs == Y.TemplateArgs;
5752
5753      }
5754
5755      llvm_unreachable("Invalid InstantiationKind!");
5756    }
5757
5758    friend bool operator!=(const ActiveTemplateInstantiation &X,
5759                           const ActiveTemplateInstantiation &Y) {
5760      return !(X == Y);
5761    }
5762  };
5763
5764  /// \brief List of active template instantiations.
5765  ///
5766  /// This vector is treated as a stack. As one template instantiation
5767  /// requires another template instantiation, additional
5768  /// instantiations are pushed onto the stack up to a
5769  /// user-configurable limit LangOptions::InstantiationDepth.
5770  SmallVector<ActiveTemplateInstantiation, 16>
5771    ActiveTemplateInstantiations;
5772
5773  /// \brief Whether we are in a SFINAE context that is not associated with
5774  /// template instantiation.
5775  ///
5776  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
5777  /// of a template instantiation or template argument deduction.
5778  bool InNonInstantiationSFINAEContext;
5779
5780  /// \brief The number of ActiveTemplateInstantiation entries in
5781  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
5782  /// therefore, should not be counted as part of the instantiation depth.
5783  unsigned NonInstantiationEntries;
5784
5785  /// \brief The last template from which a template instantiation
5786  /// error or warning was produced.
5787  ///
5788  /// This value is used to suppress printing of redundant template
5789  /// instantiation backtraces when there are multiple errors in the
5790  /// same instantiation. FIXME: Does this belong in Sema? It's tough
5791  /// to implement it anywhere else.
5792  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
5793
5794  /// \brief The current index into pack expansion arguments that will be
5795  /// used for substitution of parameter packs.
5796  ///
5797  /// The pack expansion index will be -1 to indicate that parameter packs
5798  /// should be instantiated as themselves. Otherwise, the index specifies
5799  /// which argument within the parameter pack will be used for substitution.
5800  int ArgumentPackSubstitutionIndex;
5801
5802  /// \brief RAII object used to change the argument pack substitution index
5803  /// within a \c Sema object.
5804  ///
5805  /// See \c ArgumentPackSubstitutionIndex for more information.
5806  class ArgumentPackSubstitutionIndexRAII {
5807    Sema &Self;
5808    int OldSubstitutionIndex;
5809
5810  public:
5811    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
5812      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
5813      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
5814    }
5815
5816    ~ArgumentPackSubstitutionIndexRAII() {
5817      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
5818    }
5819  };
5820
5821  friend class ArgumentPackSubstitutionRAII;
5822
5823  /// \brief The stack of calls expression undergoing template instantiation.
5824  ///
5825  /// The top of this stack is used by a fixit instantiating unresolved
5826  /// function calls to fix the AST to match the textual change it prints.
5827  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
5828
5829  /// \brief For each declaration that involved template argument deduction, the
5830  /// set of diagnostics that were suppressed during that template argument
5831  /// deduction.
5832  ///
5833  /// FIXME: Serialize this structure to the AST file.
5834  llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
5835    SuppressedDiagnostics;
5836
5837  /// \brief A stack object to be created when performing template
5838  /// instantiation.
5839  ///
5840  /// Construction of an object of type \c InstantiatingTemplate
5841  /// pushes the current instantiation onto the stack of active
5842  /// instantiations. If the size of this stack exceeds the maximum
5843  /// number of recursive template instantiations, construction
5844  /// produces an error and evaluates true.
5845  ///
5846  /// Destruction of this object will pop the named instantiation off
5847  /// the stack.
5848  struct InstantiatingTemplate {
5849    /// \brief Note that we are instantiating a class template,
5850    /// function template, or a member thereof.
5851    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5852                          Decl *Entity,
5853                          SourceRange InstantiationRange = SourceRange());
5854
5855    struct ExceptionSpecification {};
5856    /// \brief Note that we are instantiating an exception specification
5857    /// of a function template.
5858    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5859                          FunctionDecl *Entity, ExceptionSpecification,
5860                          SourceRange InstantiationRange = SourceRange());
5861
5862    /// \brief Note that we are instantiating a default argument in a
5863    /// template-id.
5864    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5865                          TemplateDecl *Template,
5866                          ArrayRef<TemplateArgument> TemplateArgs,
5867                          SourceRange InstantiationRange = SourceRange());
5868
5869    /// \brief Note that we are instantiating a default argument in a
5870    /// template-id.
5871    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5872                          FunctionTemplateDecl *FunctionTemplate,
5873                          ArrayRef<TemplateArgument> TemplateArgs,
5874                          ActiveTemplateInstantiation::InstantiationKind Kind,
5875                          sema::TemplateDeductionInfo &DeductionInfo,
5876                          SourceRange InstantiationRange = SourceRange());
5877
5878    /// \brief Note that we are instantiating as part of template
5879    /// argument deduction for a class template partial
5880    /// specialization.
5881    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5882                          ClassTemplatePartialSpecializationDecl *PartialSpec,
5883                          ArrayRef<TemplateArgument> TemplateArgs,
5884                          sema::TemplateDeductionInfo &DeductionInfo,
5885                          SourceRange InstantiationRange = SourceRange());
5886
5887    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5888                          ParmVarDecl *Param,
5889                          ArrayRef<TemplateArgument> TemplateArgs,
5890                          SourceRange InstantiationRange = SourceRange());
5891
5892    /// \brief Note that we are substituting prior template arguments into a
5893    /// non-type or template template parameter.
5894    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5895                          NamedDecl *Template,
5896                          NonTypeTemplateParmDecl *Param,
5897                          ArrayRef<TemplateArgument> TemplateArgs,
5898                          SourceRange InstantiationRange);
5899
5900    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5901                          NamedDecl *Template,
5902                          TemplateTemplateParmDecl *Param,
5903                          ArrayRef<TemplateArgument> TemplateArgs,
5904                          SourceRange InstantiationRange);
5905
5906    /// \brief Note that we are checking the default template argument
5907    /// against the template parameter for a given template-id.
5908    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5909                          TemplateDecl *Template,
5910                          NamedDecl *Param,
5911                          ArrayRef<TemplateArgument> TemplateArgs,
5912                          SourceRange InstantiationRange);
5913
5914
5915    /// \brief Note that we have finished instantiating this template.
5916    void Clear();
5917
5918    ~InstantiatingTemplate() { Clear(); }
5919
5920    /// \brief Determines whether we have exceeded the maximum
5921    /// recursive template instantiations.
5922    operator bool() const { return Invalid; }
5923
5924  private:
5925    Sema &SemaRef;
5926    bool Invalid;
5927    bool SavedInNonInstantiationSFINAEContext;
5928    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
5929                                 SourceRange InstantiationRange);
5930
5931    InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
5932
5933    InstantiatingTemplate&
5934    operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
5935  };
5936
5937  void PrintInstantiationStack();
5938
5939  /// \brief Determines whether we are currently in a context where
5940  /// template argument substitution failures are not considered
5941  /// errors.
5942  ///
5943  /// \returns An empty \c Optional if we're not in a SFINAE context.
5944  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
5945  /// template-deduction context object, which can be used to capture
5946  /// diagnostics that will be suppressed.
5947  Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
5948
5949  /// \brief Determines whether we are currently in a context that
5950  /// is not evaluated as per C++ [expr] p5.
5951  bool isUnevaluatedContext() const {
5952    assert(!ExprEvalContexts.empty() &&
5953           "Must be in an expression evaluation context");
5954    return ExprEvalContexts.back().Context == Sema::Unevaluated;
5955  }
5956
5957  /// \brief RAII class used to determine whether SFINAE has
5958  /// trapped any errors that occur during template argument
5959  /// deduction.`
5960  class SFINAETrap {
5961    Sema &SemaRef;
5962    unsigned PrevSFINAEErrors;
5963    bool PrevInNonInstantiationSFINAEContext;
5964    bool PrevAccessCheckingSFINAE;
5965
5966  public:
5967    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
5968      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
5969        PrevInNonInstantiationSFINAEContext(
5970                                      SemaRef.InNonInstantiationSFINAEContext),
5971        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
5972    {
5973      if (!SemaRef.isSFINAEContext())
5974        SemaRef.InNonInstantiationSFINAEContext = true;
5975      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
5976    }
5977
5978    ~SFINAETrap() {
5979      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
5980      SemaRef.InNonInstantiationSFINAEContext
5981        = PrevInNonInstantiationSFINAEContext;
5982      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
5983    }
5984
5985    /// \brief Determine whether any SFINAE errors have been trapped.
5986    bool hasErrorOccurred() const {
5987      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
5988    }
5989  };
5990
5991  /// \brief The current instantiation scope used to store local
5992  /// variables.
5993  LocalInstantiationScope *CurrentInstantiationScope;
5994
5995  /// \brief The number of typos corrected by CorrectTypo.
5996  unsigned TyposCorrected;
5997
5998  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
5999    UnqualifiedTyposCorrectedMap;
6000
6001  /// \brief A cache containing the results of typo correction for unqualified
6002  /// name lookup.
6003  ///
6004  /// The string is the string that we corrected to (which may be empty, if
6005  /// there was no correction), while the boolean will be true when the
6006  /// string represents a keyword.
6007  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6008
6009  /// \brief Worker object for performing CFG-based warnings.
6010  sema::AnalysisBasedWarnings AnalysisWarnings;
6011
6012  /// \brief An entity for which implicit template instantiation is required.
6013  ///
6014  /// The source location associated with the declaration is the first place in
6015  /// the source code where the declaration was "used". It is not necessarily
6016  /// the point of instantiation (which will be either before or after the
6017  /// namespace-scope declaration that triggered this implicit instantiation),
6018  /// However, it is the location that diagnostics should generally refer to,
6019  /// because users will need to know what code triggered the instantiation.
6020  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6021
6022  /// \brief The queue of implicit template instantiations that are required
6023  /// but have not yet been performed.
6024  std::deque<PendingImplicitInstantiation> PendingInstantiations;
6025
6026  /// \brief The queue of implicit template instantiations that are required
6027  /// and must be performed within the current local scope.
6028  ///
6029  /// This queue is only used for member functions of local classes in
6030  /// templates, which must be instantiated in the same scope as their
6031  /// enclosing function, so that they can reference function-local
6032  /// types, static variables, enumerators, etc.
6033  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6034
6035  void PerformPendingInstantiations(bool LocalOnly = false);
6036
6037  TypeSourceInfo *SubstType(TypeSourceInfo *T,
6038                            const MultiLevelTemplateArgumentList &TemplateArgs,
6039                            SourceLocation Loc, DeclarationName Entity);
6040
6041  QualType SubstType(QualType T,
6042                     const MultiLevelTemplateArgumentList &TemplateArgs,
6043                     SourceLocation Loc, DeclarationName Entity);
6044
6045  TypeSourceInfo *SubstType(TypeLoc TL,
6046                            const MultiLevelTemplateArgumentList &TemplateArgs,
6047                            SourceLocation Loc, DeclarationName Entity);
6048
6049  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6050                            const MultiLevelTemplateArgumentList &TemplateArgs,
6051                                        SourceLocation Loc,
6052                                        DeclarationName Entity,
6053                                        CXXRecordDecl *ThisContext,
6054                                        unsigned ThisTypeQuals);
6055  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6056                            const MultiLevelTemplateArgumentList &TemplateArgs,
6057                                int indexAdjustment,
6058                                Optional<unsigned> NumExpansions,
6059                                bool ExpectParameterPack);
6060  bool SubstParmTypes(SourceLocation Loc,
6061                      ParmVarDecl **Params, unsigned NumParams,
6062                      const MultiLevelTemplateArgumentList &TemplateArgs,
6063                      SmallVectorImpl<QualType> &ParamTypes,
6064                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
6065  ExprResult SubstExpr(Expr *E,
6066                       const MultiLevelTemplateArgumentList &TemplateArgs);
6067
6068  /// \brief Substitute the given template arguments into a list of
6069  /// expressions, expanding pack expansions if required.
6070  ///
6071  /// \param Exprs The list of expressions to substitute into.
6072  ///
6073  /// \param NumExprs The number of expressions in \p Exprs.
6074  ///
6075  /// \param IsCall Whether this is some form of call, in which case
6076  /// default arguments will be dropped.
6077  ///
6078  /// \param TemplateArgs The set of template arguments to substitute.
6079  ///
6080  /// \param Outputs Will receive all of the substituted arguments.
6081  ///
6082  /// \returns true if an error occurred, false otherwise.
6083  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6084                  const MultiLevelTemplateArgumentList &TemplateArgs,
6085                  SmallVectorImpl<Expr *> &Outputs);
6086
6087  StmtResult SubstStmt(Stmt *S,
6088                       const MultiLevelTemplateArgumentList &TemplateArgs);
6089
6090  Decl *SubstDecl(Decl *D, DeclContext *Owner,
6091                  const MultiLevelTemplateArgumentList &TemplateArgs);
6092
6093  ExprResult SubstInitializer(Expr *E,
6094                       const MultiLevelTemplateArgumentList &TemplateArgs,
6095                       bool CXXDirectInit);
6096
6097  bool
6098  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6099                      CXXRecordDecl *Pattern,
6100                      const MultiLevelTemplateArgumentList &TemplateArgs);
6101
6102  bool
6103  InstantiateClass(SourceLocation PointOfInstantiation,
6104                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6105                   const MultiLevelTemplateArgumentList &TemplateArgs,
6106                   TemplateSpecializationKind TSK,
6107                   bool Complain = true);
6108
6109  bool InstantiateEnum(SourceLocation PointOfInstantiation,
6110                       EnumDecl *Instantiation, EnumDecl *Pattern,
6111                       const MultiLevelTemplateArgumentList &TemplateArgs,
6112                       TemplateSpecializationKind TSK);
6113
6114  struct LateInstantiatedAttribute {
6115    const Attr *TmplAttr;
6116    LocalInstantiationScope *Scope;
6117    Decl *NewDecl;
6118
6119    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6120                              Decl *D)
6121      : TmplAttr(A), Scope(S), NewDecl(D)
6122    { }
6123  };
6124  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6125
6126  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6127                        const Decl *Pattern, Decl *Inst,
6128                        LateInstantiatedAttrVec *LateAttrs = 0,
6129                        LocalInstantiationScope *OuterMostScope = 0);
6130
6131  bool
6132  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6133                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6134                           TemplateSpecializationKind TSK,
6135                           bool Complain = true);
6136
6137  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6138                               CXXRecordDecl *Instantiation,
6139                            const MultiLevelTemplateArgumentList &TemplateArgs,
6140                               TemplateSpecializationKind TSK);
6141
6142  void InstantiateClassTemplateSpecializationMembers(
6143                                          SourceLocation PointOfInstantiation,
6144                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6145                                                TemplateSpecializationKind TSK);
6146
6147  NestedNameSpecifierLoc
6148  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6149                           const MultiLevelTemplateArgumentList &TemplateArgs);
6150
6151  DeclarationNameInfo
6152  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6153                           const MultiLevelTemplateArgumentList &TemplateArgs);
6154  TemplateName
6155  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6156                    SourceLocation Loc,
6157                    const MultiLevelTemplateArgumentList &TemplateArgs);
6158  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6159             TemplateArgumentListInfo &Result,
6160             const MultiLevelTemplateArgumentList &TemplateArgs);
6161
6162  void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6163                                FunctionDecl *Function);
6164  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6165                                     FunctionDecl *Function,
6166                                     bool Recursive = false,
6167                                     bool DefinitionRequired = false);
6168  void InstantiateStaticDataMemberDefinition(
6169                                     SourceLocation PointOfInstantiation,
6170                                     VarDecl *Var,
6171                                     bool Recursive = false,
6172                                     bool DefinitionRequired = false);
6173
6174  void InstantiateMemInitializers(CXXConstructorDecl *New,
6175                                  const CXXConstructorDecl *Tmpl,
6176                            const MultiLevelTemplateArgumentList &TemplateArgs);
6177
6178  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6179                          const MultiLevelTemplateArgumentList &TemplateArgs);
6180  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6181                          const MultiLevelTemplateArgumentList &TemplateArgs);
6182
6183  // Objective-C declarations.
6184  enum ObjCContainerKind {
6185    OCK_None = -1,
6186    OCK_Interface = 0,
6187    OCK_Protocol,
6188    OCK_Category,
6189    OCK_ClassExtension,
6190    OCK_Implementation,
6191    OCK_CategoryImplementation
6192  };
6193  ObjCContainerKind getObjCContainerKind() const;
6194
6195  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6196                                 IdentifierInfo *ClassName,
6197                                 SourceLocation ClassLoc,
6198                                 IdentifierInfo *SuperName,
6199                                 SourceLocation SuperLoc,
6200                                 Decl * const *ProtoRefs,
6201                                 unsigned NumProtoRefs,
6202                                 const SourceLocation *ProtoLocs,
6203                                 SourceLocation EndProtoLoc,
6204                                 AttributeList *AttrList);
6205
6206  Decl *ActOnCompatibilityAlias(
6207                    SourceLocation AtCompatibilityAliasLoc,
6208                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
6209                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
6210
6211  bool CheckForwardProtocolDeclarationForCircularDependency(
6212    IdentifierInfo *PName,
6213    SourceLocation &PLoc, SourceLocation PrevLoc,
6214    const ObjCList<ObjCProtocolDecl> &PList);
6215
6216  Decl *ActOnStartProtocolInterface(
6217                    SourceLocation AtProtoInterfaceLoc,
6218                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6219                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6220                    const SourceLocation *ProtoLocs,
6221                    SourceLocation EndProtoLoc,
6222                    AttributeList *AttrList);
6223
6224  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6225                                    IdentifierInfo *ClassName,
6226                                    SourceLocation ClassLoc,
6227                                    IdentifierInfo *CategoryName,
6228                                    SourceLocation CategoryLoc,
6229                                    Decl * const *ProtoRefs,
6230                                    unsigned NumProtoRefs,
6231                                    const SourceLocation *ProtoLocs,
6232                                    SourceLocation EndProtoLoc);
6233
6234  Decl *ActOnStartClassImplementation(
6235                    SourceLocation AtClassImplLoc,
6236                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
6237                    IdentifierInfo *SuperClassname,
6238                    SourceLocation SuperClassLoc);
6239
6240  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6241                                         IdentifierInfo *ClassName,
6242                                         SourceLocation ClassLoc,
6243                                         IdentifierInfo *CatName,
6244                                         SourceLocation CatLoc);
6245
6246  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6247                                               ArrayRef<Decl *> Decls);
6248
6249  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6250                                     IdentifierInfo **IdentList,
6251                                     SourceLocation *IdentLocs,
6252                                     unsigned NumElts);
6253
6254  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6255                                        const IdentifierLocPair *IdentList,
6256                                        unsigned NumElts,
6257                                        AttributeList *attrList);
6258
6259  void FindProtocolDeclaration(bool WarnOnDeclarations,
6260                               const IdentifierLocPair *ProtocolId,
6261                               unsigned NumProtocols,
6262                               SmallVectorImpl<Decl *> &Protocols);
6263
6264  /// Ensure attributes are consistent with type.
6265  /// \param [in, out] Attributes The attributes to check; they will
6266  /// be modified to be consistent with \p PropertyTy.
6267  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6268                                   SourceLocation Loc,
6269                                   unsigned &Attributes,
6270                                   bool propertyInPrimaryClass);
6271
6272  /// Process the specified property declaration and create decls for the
6273  /// setters and getters as needed.
6274  /// \param property The property declaration being processed
6275  /// \param CD The semantic container for the property
6276  /// \param redeclaredProperty Declaration for property if redeclared
6277  ///        in class extension.
6278  /// \param lexicalDC Container for redeclaredProperty.
6279  void ProcessPropertyDecl(ObjCPropertyDecl *property,
6280                           ObjCContainerDecl *CD,
6281                           ObjCPropertyDecl *redeclaredProperty = 0,
6282                           ObjCContainerDecl *lexicalDC = 0);
6283
6284
6285  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6286                                ObjCPropertyDecl *SuperProperty,
6287                                const IdentifierInfo *Name);
6288
6289  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6290                                        ObjCInterfaceDecl *ID);
6291
6292  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
6293                                         ObjCProtocolDecl *PDecl);
6294
6295  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6296                   Decl **allMethods = 0, unsigned allNum = 0,
6297                   Decl **allProperties = 0, unsigned pNum = 0,
6298                   DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
6299
6300  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6301                      SourceLocation LParenLoc,
6302                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
6303                      Selector GetterSel, Selector SetterSel,
6304                      bool *OverridingProperty,
6305                      tok::ObjCKeywordKind MethodImplKind,
6306                      DeclContext *lexicalDC = 0);
6307
6308  Decl *ActOnPropertyImplDecl(Scope *S,
6309                              SourceLocation AtLoc,
6310                              SourceLocation PropertyLoc,
6311                              bool ImplKind,
6312                              IdentifierInfo *PropertyId,
6313                              IdentifierInfo *PropertyIvar,
6314                              SourceLocation PropertyIvarLoc);
6315
6316  enum ObjCSpecialMethodKind {
6317    OSMK_None,
6318    OSMK_Alloc,
6319    OSMK_New,
6320    OSMK_Copy,
6321    OSMK_RetainingInit,
6322    OSMK_NonRetainingInit
6323  };
6324
6325  struct ObjCArgInfo {
6326    IdentifierInfo *Name;
6327    SourceLocation NameLoc;
6328    // The Type is null if no type was specified, and the DeclSpec is invalid
6329    // in this case.
6330    ParsedType Type;
6331    ObjCDeclSpec DeclSpec;
6332
6333    /// ArgAttrs - Attribute list for this argument.
6334    AttributeList *ArgAttrs;
6335  };
6336
6337  Decl *ActOnMethodDeclaration(
6338    Scope *S,
6339    SourceLocation BeginLoc, // location of the + or -.
6340    SourceLocation EndLoc,   // location of the ; or {.
6341    tok::TokenKind MethodType,
6342    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6343    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6344    // optional arguments. The number of types/arguments is obtained
6345    // from the Sel.getNumArgs().
6346    ObjCArgInfo *ArgInfo,
6347    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6348    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6349    bool isVariadic, bool MethodDefinition);
6350
6351  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6352                                              const ObjCObjectPointerType *OPT,
6353                                              bool IsInstance);
6354  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6355                                           bool IsInstance);
6356
6357  bool inferObjCARCLifetime(ValueDecl *decl);
6358
6359  ExprResult
6360  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6361                            Expr *BaseExpr,
6362                            SourceLocation OpLoc,
6363                            DeclarationName MemberName,
6364                            SourceLocation MemberLoc,
6365                            SourceLocation SuperLoc, QualType SuperType,
6366                            bool Super);
6367
6368  ExprResult
6369  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6370                            IdentifierInfo &propertyName,
6371                            SourceLocation receiverNameLoc,
6372                            SourceLocation propertyNameLoc);
6373
6374  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6375
6376  /// \brief Describes the kind of message expression indicated by a message
6377  /// send that starts with an identifier.
6378  enum ObjCMessageKind {
6379    /// \brief The message is sent to 'super'.
6380    ObjCSuperMessage,
6381    /// \brief The message is an instance message.
6382    ObjCInstanceMessage,
6383    /// \brief The message is a class message, and the identifier is a type
6384    /// name.
6385    ObjCClassMessage
6386  };
6387
6388  ObjCMessageKind getObjCMessageKind(Scope *S,
6389                                     IdentifierInfo *Name,
6390                                     SourceLocation NameLoc,
6391                                     bool IsSuper,
6392                                     bool HasTrailingDot,
6393                                     ParsedType &ReceiverType);
6394
6395  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6396                               Selector Sel,
6397                               SourceLocation LBracLoc,
6398                               ArrayRef<SourceLocation> SelectorLocs,
6399                               SourceLocation RBracLoc,
6400                               MultiExprArg Args);
6401
6402  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6403                               QualType ReceiverType,
6404                               SourceLocation SuperLoc,
6405                               Selector Sel,
6406                               ObjCMethodDecl *Method,
6407                               SourceLocation LBracLoc,
6408                               ArrayRef<SourceLocation> SelectorLocs,
6409                               SourceLocation RBracLoc,
6410                               MultiExprArg Args,
6411                               bool isImplicit = false);
6412
6413  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6414                                       bool isSuperReceiver,
6415                                       SourceLocation Loc,
6416                                       Selector Sel,
6417                                       ObjCMethodDecl *Method,
6418                                       MultiExprArg Args);
6419
6420  ExprResult ActOnClassMessage(Scope *S,
6421                               ParsedType Receiver,
6422                               Selector Sel,
6423                               SourceLocation LBracLoc,
6424                               ArrayRef<SourceLocation> SelectorLocs,
6425                               SourceLocation RBracLoc,
6426                               MultiExprArg Args);
6427
6428  ExprResult BuildInstanceMessage(Expr *Receiver,
6429                                  QualType ReceiverType,
6430                                  SourceLocation SuperLoc,
6431                                  Selector Sel,
6432                                  ObjCMethodDecl *Method,
6433                                  SourceLocation LBracLoc,
6434                                  ArrayRef<SourceLocation> SelectorLocs,
6435                                  SourceLocation RBracLoc,
6436                                  MultiExprArg Args,
6437                                  bool isImplicit = false);
6438
6439  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6440                                          QualType ReceiverType,
6441                                          SourceLocation Loc,
6442                                          Selector Sel,
6443                                          ObjCMethodDecl *Method,
6444                                          MultiExprArg Args);
6445
6446  ExprResult ActOnInstanceMessage(Scope *S,
6447                                  Expr *Receiver,
6448                                  Selector Sel,
6449                                  SourceLocation LBracLoc,
6450                                  ArrayRef<SourceLocation> SelectorLocs,
6451                                  SourceLocation RBracLoc,
6452                                  MultiExprArg Args);
6453
6454  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6455                                  ObjCBridgeCastKind Kind,
6456                                  SourceLocation BridgeKeywordLoc,
6457                                  TypeSourceInfo *TSInfo,
6458                                  Expr *SubExpr);
6459
6460  ExprResult ActOnObjCBridgedCast(Scope *S,
6461                                  SourceLocation LParenLoc,
6462                                  ObjCBridgeCastKind Kind,
6463                                  SourceLocation BridgeKeywordLoc,
6464                                  ParsedType Type,
6465                                  SourceLocation RParenLoc,
6466                                  Expr *SubExpr);
6467
6468  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6469
6470  /// \brief Check whether the given new method is a valid override of the
6471  /// given overridden method, and set any properties that should be inherited.
6472  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6473                               const ObjCMethodDecl *Overridden);
6474
6475  /// \brief Describes the compatibility of a result type with its method.
6476  enum ResultTypeCompatibilityKind {
6477    RTC_Compatible,
6478    RTC_Incompatible,
6479    RTC_Unknown
6480  };
6481
6482  void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6483                                ObjCInterfaceDecl *CurrentClass,
6484                                ResultTypeCompatibilityKind RTC);
6485
6486  enum PragmaOptionsAlignKind {
6487    POAK_Native,  // #pragma options align=native
6488    POAK_Natural, // #pragma options align=natural
6489    POAK_Packed,  // #pragma options align=packed
6490    POAK_Power,   // #pragma options align=power
6491    POAK_Mac68k,  // #pragma options align=mac68k
6492    POAK_Reset    // #pragma options align=reset
6493  };
6494
6495  /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6496  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6497                               SourceLocation PragmaLoc);
6498
6499  enum PragmaPackKind {
6500    PPK_Default, // #pragma pack([n])
6501    PPK_Show,    // #pragma pack(show), only supported by MSVC.
6502    PPK_Push,    // #pragma pack(push, [identifier], [n])
6503    PPK_Pop      // #pragma pack(pop, [identifier], [n])
6504  };
6505
6506  enum PragmaMSStructKind {
6507    PMSST_OFF,  // #pragms ms_struct off
6508    PMSST_ON    // #pragms ms_struct on
6509  };
6510
6511  /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6512  void ActOnPragmaPack(PragmaPackKind Kind,
6513                       IdentifierInfo *Name,
6514                       Expr *Alignment,
6515                       SourceLocation PragmaLoc,
6516                       SourceLocation LParenLoc,
6517                       SourceLocation RParenLoc);
6518
6519  /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6520  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6521
6522  /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6523  void ActOnPragmaUnused(const Token &Identifier,
6524                         Scope *curScope,
6525                         SourceLocation PragmaLoc);
6526
6527  /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6528  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6529                             SourceLocation PragmaLoc);
6530
6531  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6532                                 SourceLocation Loc);
6533  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6534
6535  /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6536  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6537                         SourceLocation PragmaLoc,
6538                         SourceLocation WeakNameLoc);
6539
6540  /// ActOnPragmaRedefineExtname - Called on well formed
6541  /// \#pragma redefine_extname oldname newname.
6542  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6543                                  IdentifierInfo* AliasName,
6544                                  SourceLocation PragmaLoc,
6545                                  SourceLocation WeakNameLoc,
6546                                  SourceLocation AliasNameLoc);
6547
6548  /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
6549  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
6550                            IdentifierInfo* AliasName,
6551                            SourceLocation PragmaLoc,
6552                            SourceLocation WeakNameLoc,
6553                            SourceLocation AliasNameLoc);
6554
6555  /// ActOnPragmaFPContract - Called on well formed
6556  /// \#pragma {STDC,OPENCL} FP_CONTRACT
6557  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
6558
6559  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
6560  /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
6561  void AddAlignmentAttributesForRecord(RecordDecl *RD);
6562
6563  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
6564  void AddMsStructLayoutForRecord(RecordDecl *RD);
6565
6566  /// FreePackedContext - Deallocate and null out PackContext.
6567  void FreePackedContext();
6568
6569  /// PushNamespaceVisibilityAttr - Note that we've entered a
6570  /// namespace with a visibility attribute.
6571  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
6572                                   SourceLocation Loc);
6573
6574  /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
6575  /// add an appropriate visibility attribute.
6576  void AddPushedVisibilityAttribute(Decl *RD);
6577
6578  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6579  /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
6580  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6581
6582  /// FreeVisContext - Deallocate and null out VisContext.
6583  void FreeVisContext();
6584
6585  /// AddCFAuditedAttribute - Check whether we're currently within
6586  /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
6587  /// the appropriate attribute.
6588  void AddCFAuditedAttribute(Decl *D);
6589
6590  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6591  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
6592                      unsigned SpellingListIndex, bool IsPackExpansion);
6593  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
6594                      unsigned SpellingListIndex, bool IsPackExpansion);
6595
6596  // OpenMP directives and clauses.
6597
6598  /// \brief Called on well-formed '#pragma omp threadprivate'.
6599  DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
6600                        SourceLocation Loc,
6601                        Scope *CurScope,
6602                        ArrayRef<DeclarationNameInfo> IdList);
6603  /// \brief Build a new OpenMPThreadPrivateDecl and check its correctness.
6604  OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
6605                        SourceLocation Loc,
6606                        ArrayRef<DeclRefExpr *> VarList);
6607
6608  /// \brief The kind of conversion being performed.
6609  enum CheckedConversionKind {
6610    /// \brief An implicit conversion.
6611    CCK_ImplicitConversion,
6612    /// \brief A C-style cast.
6613    CCK_CStyleCast,
6614    /// \brief A functional-style cast.
6615    CCK_FunctionalCast,
6616    /// \brief A cast other than a C-style cast.
6617    CCK_OtherCast
6618  };
6619
6620  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
6621  /// cast.  If there is already an implicit cast, merge into the existing one.
6622  /// If isLvalue, the result of the cast is an lvalue.
6623  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
6624                               ExprValueKind VK = VK_RValue,
6625                               const CXXCastPath *BasePath = 0,
6626                               CheckedConversionKind CCK
6627                                  = CCK_ImplicitConversion);
6628
6629  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6630  /// to the conversion from scalar type ScalarTy to the Boolean type.
6631  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
6632
6633  /// IgnoredValueConversions - Given that an expression's result is
6634  /// syntactically ignored, perform any conversions that are
6635  /// required.
6636  ExprResult IgnoredValueConversions(Expr *E);
6637
6638  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
6639  // functions and arrays to their respective pointers (C99 6.3.2.1).
6640  ExprResult UsualUnaryConversions(Expr *E);
6641
6642  // DefaultFunctionArrayConversion - converts functions and arrays
6643  // to their respective pointers (C99 6.3.2.1).
6644  ExprResult DefaultFunctionArrayConversion(Expr *E);
6645
6646  // DefaultFunctionArrayLvalueConversion - converts functions and
6647  // arrays to their respective pointers and performs the
6648  // lvalue-to-rvalue conversion.
6649  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
6650
6651  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
6652  // the operand.  This is DefaultFunctionArrayLvalueConversion,
6653  // except that it assumes the operand isn't of function or array
6654  // type.
6655  ExprResult DefaultLvalueConversion(Expr *E);
6656
6657  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
6658  // do not have a prototype. Integer promotions are performed on each
6659  // argument, and arguments that have type float are promoted to double.
6660  ExprResult DefaultArgumentPromotion(Expr *E);
6661
6662  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
6663  enum VariadicCallType {
6664    VariadicFunction,
6665    VariadicBlock,
6666    VariadicMethod,
6667    VariadicConstructor,
6668    VariadicDoesNotApply
6669  };
6670
6671  VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
6672                                       const FunctionProtoType *Proto,
6673                                       Expr *Fn);
6674
6675  // Used for determining in which context a type is allowed to be passed to a
6676  // vararg function.
6677  enum VarArgKind {
6678    VAK_Valid,
6679    VAK_ValidInCXX11,
6680    VAK_Invalid
6681  };
6682
6683  // Determines which VarArgKind fits an expression.
6684  VarArgKind isValidVarArgType(const QualType &Ty);
6685
6686  /// GatherArgumentsForCall - Collector argument expressions for various
6687  /// form of call prototypes.
6688  bool GatherArgumentsForCall(SourceLocation CallLoc,
6689                              FunctionDecl *FDecl,
6690                              const FunctionProtoType *Proto,
6691                              unsigned FirstProtoArg,
6692                              Expr **Args, unsigned NumArgs,
6693                              SmallVector<Expr *, 8> &AllArgs,
6694                              VariadicCallType CallType = VariadicDoesNotApply,
6695                              bool AllowExplicit = false,
6696                              bool IsListInitialization = false);
6697
6698  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
6699  // will create a runtime trap if the resulting type is not a POD type.
6700  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
6701                                              FunctionDecl *FDecl);
6702
6703  /// Checks to see if the given expression is a valid argument to a variadic
6704  /// function, issuing a diagnostic and returning NULL if not.
6705  bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT);
6706
6707  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
6708  // operands and then handles various conversions that are common to binary
6709  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
6710  // routine returns the first non-arithmetic type found. The client is
6711  // responsible for emitting appropriate error diagnostics.
6712  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
6713                                      bool IsCompAssign = false);
6714
6715  /// AssignConvertType - All of the 'assignment' semantic checks return this
6716  /// enum to indicate whether the assignment was allowed.  These checks are
6717  /// done for simple assignments, as well as initialization, return from
6718  /// function, argument passing, etc.  The query is phrased in terms of a
6719  /// source and destination type.
6720  enum AssignConvertType {
6721    /// Compatible - the types are compatible according to the standard.
6722    Compatible,
6723
6724    /// PointerToInt - The assignment converts a pointer to an int, which we
6725    /// accept as an extension.
6726    PointerToInt,
6727
6728    /// IntToPointer - The assignment converts an int to a pointer, which we
6729    /// accept as an extension.
6730    IntToPointer,
6731
6732    /// FunctionVoidPointer - The assignment is between a function pointer and
6733    /// void*, which the standard doesn't allow, but we accept as an extension.
6734    FunctionVoidPointer,
6735
6736    /// IncompatiblePointer - The assignment is between two pointers types that
6737    /// are not compatible, but we accept them as an extension.
6738    IncompatiblePointer,
6739
6740    /// IncompatiblePointer - The assignment is between two pointers types which
6741    /// point to integers which have a different sign, but are otherwise
6742    /// identical. This is a subset of the above, but broken out because it's by
6743    /// far the most common case of incompatible pointers.
6744    IncompatiblePointerSign,
6745
6746    /// CompatiblePointerDiscardsQualifiers - The assignment discards
6747    /// c/v/r qualifiers, which we accept as an extension.
6748    CompatiblePointerDiscardsQualifiers,
6749
6750    /// IncompatiblePointerDiscardsQualifiers - The assignment
6751    /// discards qualifiers that we don't permit to be discarded,
6752    /// like address spaces.
6753    IncompatiblePointerDiscardsQualifiers,
6754
6755    /// IncompatibleNestedPointerQualifiers - The assignment is between two
6756    /// nested pointer types, and the qualifiers other than the first two
6757    /// levels differ e.g. char ** -> const char **, but we accept them as an
6758    /// extension.
6759    IncompatibleNestedPointerQualifiers,
6760
6761    /// IncompatibleVectors - The assignment is between two vector types that
6762    /// have the same size, which we accept as an extension.
6763    IncompatibleVectors,
6764
6765    /// IntToBlockPointer - The assignment converts an int to a block
6766    /// pointer. We disallow this.
6767    IntToBlockPointer,
6768
6769    /// IncompatibleBlockPointer - The assignment is between two block
6770    /// pointers types that are not compatible.
6771    IncompatibleBlockPointer,
6772
6773    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
6774    /// id type and something else (that is incompatible with it). For example,
6775    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
6776    IncompatibleObjCQualifiedId,
6777
6778    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
6779    /// object with __weak qualifier.
6780    IncompatibleObjCWeakRef,
6781
6782    /// Incompatible - We reject this conversion outright, it is invalid to
6783    /// represent it in the AST.
6784    Incompatible
6785  };
6786
6787  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
6788  /// assignment conversion type specified by ConvTy.  This returns true if the
6789  /// conversion was invalid or false if the conversion was accepted.
6790  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
6791                                SourceLocation Loc,
6792                                QualType DstType, QualType SrcType,
6793                                Expr *SrcExpr, AssignmentAction Action,
6794                                bool *Complained = 0);
6795
6796  /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
6797  /// integer not in the range of enum values.
6798  void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
6799                              Expr *SrcExpr);
6800
6801  /// CheckAssignmentConstraints - Perform type checking for assignment,
6802  /// argument passing, variable initialization, and function return values.
6803  /// C99 6.5.16.
6804  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
6805                                               QualType LHSType,
6806                                               QualType RHSType);
6807
6808  /// Check assignment constraints and prepare for a conversion of the
6809  /// RHS to the LHS type.
6810  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
6811                                               ExprResult &RHS,
6812                                               CastKind &Kind);
6813
6814  // CheckSingleAssignmentConstraints - Currently used by
6815  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
6816  // this routine performs the default function/array converions.
6817  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
6818                                                     ExprResult &RHS,
6819                                                     bool Diagnose = true);
6820
6821  // \brief If the lhs type is a transparent union, check whether we
6822  // can initialize the transparent union with the given expression.
6823  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
6824                                                             ExprResult &RHS);
6825
6826  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
6827
6828  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6829
6830  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6831                                       AssignmentAction Action,
6832                                       bool AllowExplicit = false);
6833  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6834                                       AssignmentAction Action,
6835                                       bool AllowExplicit,
6836                                       ImplicitConversionSequence& ICS);
6837  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6838                                       const ImplicitConversionSequence& ICS,
6839                                       AssignmentAction Action,
6840                                       CheckedConversionKind CCK
6841                                          = CCK_ImplicitConversion);
6842  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6843                                       const StandardConversionSequence& SCS,
6844                                       AssignmentAction Action,
6845                                       CheckedConversionKind CCK);
6846
6847  /// the following "Check" methods will return a valid/converted QualType
6848  /// or a null QualType (indicating an error diagnostic was issued).
6849
6850  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
6851  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6852                           ExprResult &RHS);
6853  QualType CheckPointerToMemberOperands( // C++ 5.5
6854    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
6855    SourceLocation OpLoc, bool isIndirect);
6856  QualType CheckMultiplyDivideOperands( // C99 6.5.5
6857    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
6858    bool IsDivide);
6859  QualType CheckRemainderOperands( // C99 6.5.5
6860    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6861    bool IsCompAssign = false);
6862  QualType CheckAdditionOperands( // C99 6.5.6
6863    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6864    QualType* CompLHSTy = 0);
6865  QualType CheckSubtractionOperands( // C99 6.5.6
6866    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6867    QualType* CompLHSTy = 0);
6868  QualType CheckShiftOperands( // C99 6.5.7
6869    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6870    bool IsCompAssign = false);
6871  QualType CheckCompareOperands( // C99 6.5.8/9
6872    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
6873                                bool isRelational);
6874  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
6875    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6876    bool IsCompAssign = false);
6877  QualType CheckLogicalOperands( // C99 6.5.[13,14]
6878    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
6879  // CheckAssignmentOperands is used for both simple and compound assignment.
6880  // For simple assignment, pass both expressions and a null converted type.
6881  // For compound assignment, pass both expressions and the converted type.
6882  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
6883    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
6884
6885  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
6886                                     UnaryOperatorKind Opcode, Expr *Op);
6887  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
6888                                         BinaryOperatorKind Opcode,
6889                                         Expr *LHS, Expr *RHS);
6890  ExprResult checkPseudoObjectRValue(Expr *E);
6891  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
6892
6893  QualType CheckConditionalOperands( // C99 6.5.15
6894    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
6895    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
6896  QualType CXXCheckConditionalOperands( // C++ 5.16
6897    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
6898    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
6899  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
6900                                    bool *NonStandardCompositeType = 0);
6901  QualType FindCompositePointerType(SourceLocation Loc,
6902                                    ExprResult &E1, ExprResult &E2,
6903                                    bool *NonStandardCompositeType = 0) {
6904    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
6905    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
6906                                                  NonStandardCompositeType);
6907    E1 = Owned(E1Tmp);
6908    E2 = Owned(E2Tmp);
6909    return Composite;
6910  }
6911
6912  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6913                                        SourceLocation QuestionLoc);
6914
6915  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6916                                  SourceLocation QuestionLoc);
6917
6918  /// type checking for vector binary operators.
6919  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6920                               SourceLocation Loc, bool IsCompAssign);
6921  QualType GetSignedVectorType(QualType V);
6922  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6923                                      SourceLocation Loc, bool isRelational);
6924  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
6925                                      SourceLocation Loc);
6926
6927  /// type checking declaration initializers (C99 6.7.8)
6928  bool CheckForConstantInitializer(Expr *e, QualType t);
6929
6930  // type checking C++ declaration initializers (C++ [dcl.init]).
6931
6932  /// ReferenceCompareResult - Expresses the result of comparing two
6933  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
6934  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
6935  enum ReferenceCompareResult {
6936    /// Ref_Incompatible - The two types are incompatible, so direct
6937    /// reference binding is not possible.
6938    Ref_Incompatible = 0,
6939    /// Ref_Related - The two types are reference-related, which means
6940    /// that their unqualified forms (T1 and T2) are either the same
6941    /// or T1 is a base class of T2.
6942    Ref_Related,
6943    /// Ref_Compatible_With_Added_Qualification - The two types are
6944    /// reference-compatible with added qualification, meaning that
6945    /// they are reference-compatible and the qualifiers on T1 (cv1)
6946    /// are greater than the qualifiers on T2 (cv2).
6947    Ref_Compatible_With_Added_Qualification,
6948    /// Ref_Compatible - The two types are reference-compatible and
6949    /// have equivalent qualifiers (cv1 == cv2).
6950    Ref_Compatible
6951  };
6952
6953  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
6954                                                      QualType T1, QualType T2,
6955                                                      bool &DerivedToBase,
6956                                                      bool &ObjCConversion,
6957                                                bool &ObjCLifetimeConversion);
6958
6959  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
6960                                 Expr *CastExpr, CastKind &CastKind,
6961                                 ExprValueKind &VK, CXXCastPath &Path);
6962
6963  /// \brief Force an expression with unknown-type to an expression of the
6964  /// given type.
6965  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
6966
6967  /// \brief Type-check an expression that's being passed to an
6968  /// __unknown_anytype parameter.
6969  ExprResult checkUnknownAnyArg(SourceLocation callLoc,
6970                                Expr *result, QualType &paramType);
6971
6972  // CheckVectorCast - check type constraints for vectors.
6973  // Since vectors are an extension, there are no C standard reference for this.
6974  // We allow casting between vectors and integer datatypes of the same size.
6975  // returns true if the cast is invalid
6976  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6977                       CastKind &Kind);
6978
6979  // CheckExtVectorCast - check type constraints for extended vectors.
6980  // Since vectors are an extension, there are no C standard reference for this.
6981  // We allow casting between vectors and integer datatypes of the same size,
6982  // or vectors and the element type of that vector.
6983  // returns the cast expr
6984  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
6985                                CastKind &Kind);
6986
6987  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
6988                                        SourceLocation LParenLoc,
6989                                        Expr *CastExpr,
6990                                        SourceLocation RParenLoc);
6991
6992  enum ARCConversionResult { ACR_okay, ACR_unbridged };
6993
6994  /// \brief Checks for invalid conversions and casts between
6995  /// retainable pointers and other pointer kinds.
6996  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
6997                                             QualType castType, Expr *&op,
6998                                             CheckedConversionKind CCK);
6999
7000  Expr *stripARCUnbridgedCast(Expr *e);
7001  void diagnoseARCUnbridgedCast(Expr *e);
7002
7003  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7004                                             QualType ExprType);
7005
7006  /// checkRetainCycles - Check whether an Objective-C message send
7007  /// might create an obvious retain cycle.
7008  void checkRetainCycles(ObjCMessageExpr *msg);
7009  void checkRetainCycles(Expr *receiver, Expr *argument);
7010  void checkRetainCycles(VarDecl *Var, Expr *Init);
7011
7012  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7013  /// to weak/__unsafe_unretained type.
7014  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7015
7016  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7017  /// to weak/__unsafe_unretained expression.
7018  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7019
7020  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7021  /// \param Method - May be null.
7022  /// \param [out] ReturnType - The return type of the send.
7023  /// \return true iff there were any incompatible types.
7024  bool CheckMessageArgumentTypes(QualType ReceiverType,
7025                                 Expr **Args, unsigned NumArgs, Selector Sel,
7026                                 ArrayRef<SourceLocation> SelectorLocs,
7027                                 ObjCMethodDecl *Method, bool isClassMessage,
7028                                 bool isSuperMessage,
7029                                 SourceLocation lbrac, SourceLocation rbrac,
7030                                 QualType &ReturnType, ExprValueKind &VK);
7031
7032  /// \brief Determine the result of a message send expression based on
7033  /// the type of the receiver, the method expected to receive the message,
7034  /// and the form of the message send.
7035  QualType getMessageSendResultType(QualType ReceiverType,
7036                                    ObjCMethodDecl *Method,
7037                                    bool isClassMessage, bool isSuperMessage);
7038
7039  /// \brief If the given expression involves a message send to a method
7040  /// with a related result type, emit a note describing what happened.
7041  void EmitRelatedResultTypeNote(const Expr *E);
7042
7043  /// \brief Given that we had incompatible pointer types in a return
7044  /// statement, check whether we're in a method with a related result
7045  /// type, and if so, emit a note describing what happened.
7046  void EmitRelatedResultTypeNoteForReturn(QualType destType);
7047
7048  /// CheckBooleanCondition - Diagnose problems involving the use of
7049  /// the given expression as a boolean condition (e.g. in an if
7050  /// statement).  Also performs the standard function and array
7051  /// decays, possibly changing the input variable.
7052  ///
7053  /// \param Loc - A location associated with the condition, e.g. the
7054  /// 'if' keyword.
7055  /// \return true iff there were any errors
7056  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7057
7058  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7059                                   Expr *SubExpr);
7060
7061  /// DiagnoseAssignmentAsCondition - Given that an expression is
7062  /// being used as a boolean condition, warn if it's an assignment.
7063  void DiagnoseAssignmentAsCondition(Expr *E);
7064
7065  /// \brief Redundant parentheses over an equality comparison can indicate
7066  /// that the user intended an assignment used as condition.
7067  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7068
7069  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7070  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7071
7072  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7073  /// the specified width and sign.  If an overflow occurs, detect it and emit
7074  /// the specified diagnostic.
7075  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7076                                          unsigned NewWidth, bool NewSign,
7077                                          SourceLocation Loc, unsigned DiagID);
7078
7079  /// Checks that the Objective-C declaration is declared in the global scope.
7080  /// Emits an error and marks the declaration as invalid if it's not declared
7081  /// in the global scope.
7082  bool CheckObjCDeclScope(Decl *D);
7083
7084  /// \brief Abstract base class used for diagnosing integer constant
7085  /// expression violations.
7086  class VerifyICEDiagnoser {
7087  public:
7088    bool Suppress;
7089
7090    VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7091
7092    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7093    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
7094    virtual ~VerifyICEDiagnoser() { }
7095  };
7096
7097  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7098  /// and reports the appropriate diagnostics. Returns false on success.
7099  /// Can optionally return the value of the expression.
7100  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7101                                             VerifyICEDiagnoser &Diagnoser,
7102                                             bool AllowFold = true);
7103  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7104                                             unsigned DiagID,
7105                                             bool AllowFold = true);
7106  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
7107
7108  /// VerifyBitField - verifies that a bit field expression is an ICE and has
7109  /// the correct width, and that the field type is valid.
7110  /// Returns false on success.
7111  /// Can optionally return whether the bit-field is of width 0
7112  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
7113                            QualType FieldTy, Expr *BitWidth,
7114                            bool *ZeroWidth = 0);
7115
7116  enum CUDAFunctionTarget {
7117    CFT_Device,
7118    CFT_Global,
7119    CFT_Host,
7120    CFT_HostDevice
7121  };
7122
7123  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
7124
7125  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
7126                       CUDAFunctionTarget CalleeTarget);
7127
7128  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
7129    return CheckCUDATarget(IdentifyCUDATarget(Caller),
7130                           IdentifyCUDATarget(Callee));
7131  }
7132
7133  /// \name Code completion
7134  //@{
7135  /// \brief Describes the context in which code completion occurs.
7136  enum ParserCompletionContext {
7137    /// \brief Code completion occurs at top-level or namespace context.
7138    PCC_Namespace,
7139    /// \brief Code completion occurs within a class, struct, or union.
7140    PCC_Class,
7141    /// \brief Code completion occurs within an Objective-C interface, protocol,
7142    /// or category.
7143    PCC_ObjCInterface,
7144    /// \brief Code completion occurs within an Objective-C implementation or
7145    /// category implementation
7146    PCC_ObjCImplementation,
7147    /// \brief Code completion occurs within the list of instance variables
7148    /// in an Objective-C interface, protocol, category, or implementation.
7149    PCC_ObjCInstanceVariableList,
7150    /// \brief Code completion occurs following one or more template
7151    /// headers.
7152    PCC_Template,
7153    /// \brief Code completion occurs following one or more template
7154    /// headers within a class.
7155    PCC_MemberTemplate,
7156    /// \brief Code completion occurs within an expression.
7157    PCC_Expression,
7158    /// \brief Code completion occurs within a statement, which may
7159    /// also be an expression or a declaration.
7160    PCC_Statement,
7161    /// \brief Code completion occurs at the beginning of the
7162    /// initialization statement (or expression) in a for loop.
7163    PCC_ForInit,
7164    /// \brief Code completion occurs within the condition of an if,
7165    /// while, switch, or for statement.
7166    PCC_Condition,
7167    /// \brief Code completion occurs within the body of a function on a
7168    /// recovery path, where we do not have a specific handle on our position
7169    /// in the grammar.
7170    PCC_RecoveryInFunction,
7171    /// \brief Code completion occurs where only a type is permitted.
7172    PCC_Type,
7173    /// \brief Code completion occurs in a parenthesized expression, which
7174    /// might also be a type cast.
7175    PCC_ParenthesizedExpression,
7176    /// \brief Code completion occurs within a sequence of declaration
7177    /// specifiers within a function, method, or block.
7178    PCC_LocalDeclarationSpecifiers
7179  };
7180
7181  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
7182  void CodeCompleteOrdinaryName(Scope *S,
7183                                ParserCompletionContext CompletionContext);
7184  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
7185                            bool AllowNonIdentifiers,
7186                            bool AllowNestedNameSpecifiers);
7187
7188  struct CodeCompleteExpressionData;
7189  void CodeCompleteExpression(Scope *S,
7190                              const CodeCompleteExpressionData &Data);
7191  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
7192                                       SourceLocation OpLoc,
7193                                       bool IsArrow);
7194  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
7195  void CodeCompleteTag(Scope *S, unsigned TagSpec);
7196  void CodeCompleteTypeQualifiers(DeclSpec &DS);
7197  void CodeCompleteCase(Scope *S);
7198  void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
7199  void CodeCompleteInitializer(Scope *S, Decl *D);
7200  void CodeCompleteReturn(Scope *S);
7201  void CodeCompleteAfterIf(Scope *S);
7202  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
7203
7204  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
7205                               bool EnteringContext);
7206  void CodeCompleteUsing(Scope *S);
7207  void CodeCompleteUsingDirective(Scope *S);
7208  void CodeCompleteNamespaceDecl(Scope *S);
7209  void CodeCompleteNamespaceAliasDecl(Scope *S);
7210  void CodeCompleteOperatorName(Scope *S);
7211  void CodeCompleteConstructorInitializer(Decl *Constructor,
7212                                          CXXCtorInitializer** Initializers,
7213                                          unsigned NumInitializers);
7214  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7215                                    bool AfterAmpersand);
7216
7217  void CodeCompleteObjCAtDirective(Scope *S);
7218  void CodeCompleteObjCAtVisibility(Scope *S);
7219  void CodeCompleteObjCAtStatement(Scope *S);
7220  void CodeCompleteObjCAtExpression(Scope *S);
7221  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
7222  void CodeCompleteObjCPropertyGetter(Scope *S);
7223  void CodeCompleteObjCPropertySetter(Scope *S);
7224  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7225                                   bool IsParameter);
7226  void CodeCompleteObjCMessageReceiver(Scope *S);
7227  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7228                                    IdentifierInfo **SelIdents,
7229                                    unsigned NumSelIdents,
7230                                    bool AtArgumentExpression);
7231  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7232                                    IdentifierInfo **SelIdents,
7233                                    unsigned NumSelIdents,
7234                                    bool AtArgumentExpression,
7235                                    bool IsSuper = false);
7236  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7237                                       IdentifierInfo **SelIdents,
7238                                       unsigned NumSelIdents,
7239                                       bool AtArgumentExpression,
7240                                       ObjCInterfaceDecl *Super = 0);
7241  void CodeCompleteObjCForCollection(Scope *S,
7242                                     DeclGroupPtrTy IterationVar);
7243  void CodeCompleteObjCSelector(Scope *S,
7244                                IdentifierInfo **SelIdents,
7245                                unsigned NumSelIdents);
7246  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7247                                          unsigned NumProtocols);
7248  void CodeCompleteObjCProtocolDecl(Scope *S);
7249  void CodeCompleteObjCInterfaceDecl(Scope *S);
7250  void CodeCompleteObjCSuperclass(Scope *S,
7251                                  IdentifierInfo *ClassName,
7252                                  SourceLocation ClassNameLoc);
7253  void CodeCompleteObjCImplementationDecl(Scope *S);
7254  void CodeCompleteObjCInterfaceCategory(Scope *S,
7255                                         IdentifierInfo *ClassName,
7256                                         SourceLocation ClassNameLoc);
7257  void CodeCompleteObjCImplementationCategory(Scope *S,
7258                                              IdentifierInfo *ClassName,
7259                                              SourceLocation ClassNameLoc);
7260  void CodeCompleteObjCPropertyDefinition(Scope *S);
7261  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7262                                              IdentifierInfo *PropertyName);
7263  void CodeCompleteObjCMethodDecl(Scope *S,
7264                                  bool IsInstanceMethod,
7265                                  ParsedType ReturnType);
7266  void CodeCompleteObjCMethodDeclSelector(Scope *S,
7267                                          bool IsInstanceMethod,
7268                                          bool AtParameterName,
7269                                          ParsedType ReturnType,
7270                                          IdentifierInfo **SelIdents,
7271                                          unsigned NumSelIdents);
7272  void CodeCompletePreprocessorDirective(bool InConditional);
7273  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7274  void CodeCompletePreprocessorMacroName(bool IsDefinition);
7275  void CodeCompletePreprocessorExpression();
7276  void CodeCompletePreprocessorMacroArgument(Scope *S,
7277                                             IdentifierInfo *Macro,
7278                                             MacroInfo *MacroInfo,
7279                                             unsigned Argument);
7280  void CodeCompleteNaturalLanguage();
7281  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7282                                   CodeCompletionTUInfo &CCTUInfo,
7283                  SmallVectorImpl<CodeCompletionResult> &Results);
7284  //@}
7285
7286  //===--------------------------------------------------------------------===//
7287  // Extra semantic analysis beyond the C type system
7288
7289public:
7290  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7291                                                unsigned ByteNo) const;
7292
7293private:
7294  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7295                        const ArraySubscriptExpr *ASE=0,
7296                        bool AllowOnePastEnd=true, bool IndexNegated=false);
7297  void CheckArrayAccess(const Expr *E);
7298  // Used to grab the relevant information from a FormatAttr and a
7299  // FunctionDeclaration.
7300  struct FormatStringInfo {
7301    unsigned FormatIdx;
7302    unsigned FirstDataArg;
7303    bool HasVAListArg;
7304  };
7305
7306  bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7307                           FormatStringInfo *FSI);
7308  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7309                         const FunctionProtoType *Proto);
7310  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7311                           Expr **Args, unsigned NumArgs);
7312  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
7313                      const FunctionProtoType *Proto);
7314  void CheckConstructorCall(FunctionDecl *FDecl,
7315                            ArrayRef<const Expr *> Args,
7316                            const FunctionProtoType *Proto,
7317                            SourceLocation Loc);
7318
7319  void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
7320                 unsigned NumProtoArgs, bool IsMemberFunction,
7321                 SourceLocation Loc, SourceRange Range,
7322                 VariadicCallType CallType);
7323
7324
7325  bool CheckObjCString(Expr *Arg);
7326
7327  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7328  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7329  bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7330
7331  bool SemaBuiltinVAStart(CallExpr *TheCall);
7332  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7333  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7334
7335public:
7336  // Used by C++ template instantiation.
7337  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7338
7339private:
7340  bool SemaBuiltinPrefetch(CallExpr *TheCall);
7341  bool SemaBuiltinObjectSize(CallExpr *TheCall);
7342  bool SemaBuiltinLongjmp(CallExpr *TheCall);
7343  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7344  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7345                                     AtomicExpr::AtomicOp Op);
7346  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7347                              llvm::APSInt &Result);
7348
7349  enum FormatStringType {
7350    FST_Scanf,
7351    FST_Printf,
7352    FST_NSString,
7353    FST_Strftime,
7354    FST_Strfmon,
7355    FST_Kprintf,
7356    FST_Unknown
7357  };
7358  static FormatStringType GetFormatStringType(const FormatAttr *Format);
7359
7360  enum StringLiteralCheckType {
7361    SLCT_NotALiteral,
7362    SLCT_UncheckedLiteral,
7363    SLCT_CheckedLiteral
7364  };
7365
7366  StringLiteralCheckType checkFormatStringExpr(const Expr *E,
7367                                               ArrayRef<const Expr *> Args,
7368                                               bool HasVAListArg,
7369                                               unsigned format_idx,
7370                                               unsigned firstDataArg,
7371                                               FormatStringType Type,
7372                                               VariadicCallType CallType,
7373                                               bool inFunctionCall = true);
7374
7375  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7376                         ArrayRef<const Expr *> Args, bool HasVAListArg,
7377                         unsigned format_idx, unsigned firstDataArg,
7378                         FormatStringType Type, bool inFunctionCall,
7379                         VariadicCallType CallType);
7380
7381  bool CheckFormatArguments(const FormatAttr *Format,
7382                            ArrayRef<const Expr *> Args,
7383                            bool IsCXXMember,
7384                            VariadicCallType CallType,
7385                            SourceLocation Loc, SourceRange Range);
7386  bool CheckFormatArguments(ArrayRef<const Expr *> Args,
7387                            bool HasVAListArg, unsigned format_idx,
7388                            unsigned firstDataArg, FormatStringType Type,
7389                            VariadicCallType CallType,
7390                            SourceLocation Loc, SourceRange range);
7391
7392  void CheckNonNullArguments(const NonNullAttr *NonNull,
7393                             const Expr * const *ExprArgs,
7394                             SourceLocation CallSiteLoc);
7395
7396  void CheckMemaccessArguments(const CallExpr *Call,
7397                               unsigned BId,
7398                               IdentifierInfo *FnName);
7399
7400  void CheckStrlcpycatArguments(const CallExpr *Call,
7401                                IdentifierInfo *FnName);
7402
7403  void CheckStrncatArguments(const CallExpr *Call,
7404                             IdentifierInfo *FnName);
7405
7406  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7407                            SourceLocation ReturnLoc);
7408  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7409  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7410  void CheckForIntOverflow(Expr *E);
7411  void CheckUnsequencedOperations(Expr *E);
7412
7413  /// \brief Perform semantic checks on a completed expression. This will either
7414  /// be a full-expression or a default argument expression.
7415  void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
7416                          bool IsConstexpr = false);
7417
7418  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7419                                   Expr *Init);
7420
7421public:
7422  /// \brief Register a magic integral constant to be used as a type tag.
7423  void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7424                                  uint64_t MagicValue, QualType Type,
7425                                  bool LayoutCompatible, bool MustBeNull);
7426
7427  struct TypeTagData {
7428    TypeTagData() {}
7429
7430    TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7431        Type(Type), LayoutCompatible(LayoutCompatible),
7432        MustBeNull(MustBeNull)
7433    {}
7434
7435    QualType Type;
7436
7437    /// If true, \c Type should be compared with other expression's types for
7438    /// layout-compatibility.
7439    unsigned LayoutCompatible : 1;
7440    unsigned MustBeNull : 1;
7441  };
7442
7443  /// A pair of ArgumentKind identifier and magic value.  This uniquely
7444  /// identifies the magic value.
7445  typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7446
7447private:
7448  /// \brief A map from magic value to type information.
7449  OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7450      TypeTagForDatatypeMagicValues;
7451
7452  /// \brief Peform checks on a call of a function with argument_with_type_tag
7453  /// or pointer_with_type_tag attributes.
7454  void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7455                                const Expr * const *ExprArgs);
7456
7457  /// \brief The parser's current scope.
7458  ///
7459  /// The parser maintains this state here.
7460  Scope *CurScope;
7461
7462  mutable IdentifierInfo *Ident_super;
7463
7464protected:
7465  friend class Parser;
7466  friend class InitializationSequence;
7467  friend class ASTReader;
7468  friend class ASTWriter;
7469
7470public:
7471  /// \brief Retrieve the parser's current scope.
7472  ///
7473  /// This routine must only be used when it is certain that semantic analysis
7474  /// and the parser are in precisely the same context, which is not the case
7475  /// when, e.g., we are performing any kind of template instantiation.
7476  /// Therefore, the only safe places to use this scope are in the parser
7477  /// itself and in routines directly invoked from the parser and *never* from
7478  /// template substitution or instantiation.
7479  Scope *getCurScope() const { return CurScope; }
7480
7481  IdentifierInfo *getSuperIdentifier() const;
7482
7483  Decl *getObjCDeclContext() const;
7484
7485  DeclContext *getCurLexicalContext() const {
7486    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
7487  }
7488
7489  AvailabilityResult getCurContextAvailability() const;
7490
7491  const DeclContext *getCurObjCLexicalContext() const {
7492    const DeclContext *DC = getCurLexicalContext();
7493    // A category implicitly has the attribute of the interface.
7494    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
7495      DC = CatD->getClassInterface();
7496    return DC;
7497  }
7498};
7499
7500/// \brief RAII object that enters a new expression evaluation context.
7501class EnterExpressionEvaluationContext {
7502  Sema &Actions;
7503
7504public:
7505  EnterExpressionEvaluationContext(Sema &Actions,
7506                                   Sema::ExpressionEvaluationContext NewContext,
7507                                   Decl *LambdaContextDecl = 0,
7508                                   bool IsDecltype = false)
7509    : Actions(Actions) {
7510    Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
7511                                            IsDecltype);
7512  }
7513  EnterExpressionEvaluationContext(Sema &Actions,
7514                                   Sema::ExpressionEvaluationContext NewContext,
7515                                   Sema::ReuseLambdaContextDecl_t,
7516                                   bool IsDecltype = false)
7517    : Actions(Actions) {
7518    Actions.PushExpressionEvaluationContext(NewContext,
7519                                            Sema::ReuseLambdaContextDecl,
7520                                            IsDecltype);
7521  }
7522
7523  ~EnterExpressionEvaluationContext() {
7524    Actions.PopExpressionEvaluationContext();
7525  }
7526};
7527
7528}  // end namespace clang
7529
7530#endif
7531