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