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