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