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