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