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