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