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