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