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