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