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