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