Sema.h revision b328e29173d15baf3f44ccdc9c310ee741caaaf7
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    /// \brief The lookup found an overload set of literal operator templates,
2405    /// which expect the character type and characters of the spelling of the
2406    /// string literal token to be passed as template arguments.
2407    LOLR_StringTemplate
2408  };
2409
2410  SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2411                                                   CXXSpecialMember SM,
2412                                                   bool ConstArg,
2413                                                   bool VolatileArg,
2414                                                   bool RValueThis,
2415                                                   bool ConstThis,
2416                                                   bool VolatileThis);
2417
2418private:
2419  bool CppLookupName(LookupResult &R, Scope *S);
2420
2421  // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2422  //
2423  // The boolean value will be true to indicate that the namespace was loaded
2424  // from an AST/PCH file, or false otherwise.
2425  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2426
2427  /// \brief Whether we have already loaded known namespaces from an extenal
2428  /// source.
2429  bool LoadedExternalKnownNamespaces;
2430
2431public:
2432  /// \brief Look up a name, looking for a single declaration.  Return
2433  /// null if the results were absent, ambiguous, or overloaded.
2434  ///
2435  /// It is preferable to use the elaborated form and explicitly handle
2436  /// ambiguity and overloaded.
2437  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2438                              SourceLocation Loc,
2439                              LookupNameKind NameKind,
2440                              RedeclarationKind Redecl
2441                                = NotForRedeclaration);
2442  bool LookupName(LookupResult &R, Scope *S,
2443                  bool AllowBuiltinCreation = false);
2444  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2445                           bool InUnqualifiedLookup = false);
2446  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2447                        bool AllowBuiltinCreation = false,
2448                        bool EnteringContext = false);
2449  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2450                                   RedeclarationKind Redecl
2451                                     = NotForRedeclaration);
2452
2453  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2454                                    QualType T1, QualType T2,
2455                                    UnresolvedSetImpl &Functions);
2456
2457  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2458                                 SourceLocation GnuLabelLoc = SourceLocation());
2459
2460  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2461  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2462  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2463                                               unsigned Quals);
2464  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2465                                         bool RValueThis, unsigned ThisQuals);
2466  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2467                                              unsigned Quals);
2468  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2469                                        bool RValueThis, unsigned ThisQuals);
2470  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2471
2472  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2473                                                    ArrayRef<QualType> ArgTys,
2474                                                    bool AllowRaw,
2475                                                    bool AllowTemplate,
2476                                                    bool AllowStringTemplate);
2477  bool isKnownName(StringRef name);
2478
2479  void ArgumentDependentLookup(DeclarationName Name, bool Operator,
2480                               SourceLocation Loc,
2481                               ArrayRef<Expr *> Args,
2482                               ADLResult &Functions);
2483
2484  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2485                          VisibleDeclConsumer &Consumer,
2486                          bool IncludeGlobalScope = true);
2487  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2488                          VisibleDeclConsumer &Consumer,
2489                          bool IncludeGlobalScope = true);
2490
2491  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2492                             Sema::LookupNameKind LookupKind,
2493                             Scope *S, CXXScopeSpec *SS,
2494                             CorrectionCandidateCallback &CCC,
2495                             DeclContext *MemberContext = 0,
2496                             bool EnteringContext = false,
2497                             const ObjCObjectPointerType *OPT = 0,
2498                             bool RecordFailure = true);
2499
2500  void diagnoseTypo(const TypoCorrection &Correction,
2501                    const PartialDiagnostic &TypoDiag,
2502                    bool ErrorRecovery = true);
2503
2504  void diagnoseTypo(const TypoCorrection &Correction,
2505                    const PartialDiagnostic &TypoDiag,
2506                    const PartialDiagnostic &PrevNote,
2507                    bool ErrorRecovery = true);
2508
2509  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2510                                          ArrayRef<Expr *> Args,
2511                                   AssociatedNamespaceSet &AssociatedNamespaces,
2512                                   AssociatedClassSet &AssociatedClasses);
2513
2514  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2515                            bool ConsiderLinkage,
2516                            bool ExplicitInstantiationOrSpecialization);
2517
2518  void DiagnoseAmbiguousLookup(LookupResult &Result);
2519  //@}
2520
2521  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2522                                          SourceLocation IdLoc,
2523                                          bool TypoCorrection = false);
2524  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2525                                 Scope *S, bool ForRedeclaration,
2526                                 SourceLocation Loc);
2527  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2528                                      Scope *S);
2529  void AddKnownFunctionAttributes(FunctionDecl *FD);
2530
2531  // More parsing and symbol table subroutines.
2532
2533  void ProcessPragmaWeak(Scope *S, Decl *D);
2534  // Decl attributes - this routine is the top level dispatcher.
2535  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2536  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2537                                bool IncludeCXX11Attributes = true);
2538  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2539                                      const AttributeList *AttrList);
2540
2541  void checkUnusedDeclAttributes(Declarator &D);
2542
2543  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2544  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2545                            const FunctionDecl *FD = 0);
2546  bool CheckNoReturnAttr(const AttributeList &attr);
2547  bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2548                                      unsigned ArgNum, StringRef &Str,
2549                                      SourceLocation *ArgLocation = 0);
2550
2551  void CheckAlignasUnderalignment(Decl *D);
2552
2553  /// Adjust the calling convention of a method to be the ABI default if it
2554  /// wasn't specified explicitly.  This handles method types formed from
2555  /// function type typedefs and typename template arguments.
2556  void adjustMemberFunctionCC(QualType &T);
2557
2558  /// Get the outermost AttributedType node that sets a calling convention.
2559  /// Valid types should not have multiple attributes with different CCs.
2560  const AttributedType *getCallingConvAttributedType(QualType T) const;
2561
2562  /// \brief Stmt attributes - this routine is the top level dispatcher.
2563  StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2564                                   SourceRange Range);
2565
2566  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
2567                           bool &IncompleteImpl, unsigned DiagID);
2568  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2569                                   ObjCMethodDecl *MethodDecl,
2570                                   bool IsProtocolMethodDecl);
2571
2572  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2573                                   ObjCMethodDecl *Overridden,
2574                                   bool IsProtocolMethodDecl);
2575
2576  /// WarnExactTypedMethods - This routine issues a warning if method
2577  /// implementation declaration matches exactly that of its declaration.
2578  void WarnExactTypedMethods(ObjCMethodDecl *Method,
2579                             ObjCMethodDecl *MethodDecl,
2580                             bool IsProtocolMethodDecl);
2581
2582  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2583  typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2584
2585  /// CheckProtocolMethodDefs - This routine checks unimplemented
2586  /// methods declared in protocol, and those referenced by it.
2587  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
2588                               ObjCProtocolDecl *PDecl,
2589                               bool& IncompleteImpl,
2590                               const SelectorSet &InsMap,
2591                               const SelectorSet &ClsMap,
2592                               ObjCContainerDecl *CDecl);
2593
2594  /// CheckImplementationIvars - This routine checks if the instance variables
2595  /// listed in the implelementation match those listed in the interface.
2596  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2597                                ObjCIvarDecl **Fields, unsigned nIvars,
2598                                SourceLocation Loc);
2599
2600  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2601  /// remains unimplemented in the class or category \@implementation.
2602  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2603                                 ObjCContainerDecl* IDecl,
2604                                 bool IncompleteImpl = false);
2605
2606  /// DiagnoseUnimplementedProperties - This routine warns on those properties
2607  /// which must be implemented by this implementation.
2608  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2609                                       ObjCContainerDecl *CDecl);
2610
2611  /// DefaultSynthesizeProperties - This routine default synthesizes all
2612  /// properties which must be synthesized in the class's \@implementation.
2613  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2614                                    ObjCInterfaceDecl *IDecl);
2615  void DefaultSynthesizeProperties(Scope *S, Decl *D);
2616
2617  /// CollectImmediateProperties - This routine collects all properties in
2618  /// the class and its conforming protocols; but not those it its super class.
2619  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
2620            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
2621            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
2622
2623  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2624  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2625  /// declared in class 'IFace'.
2626  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2627                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2628
2629  /// Called by ActOnProperty to handle \@property declarations in
2630  /// class extensions.
2631  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2632                      SourceLocation AtLoc,
2633                      SourceLocation LParenLoc,
2634                      FieldDeclarator &FD,
2635                      Selector GetterSel,
2636                      Selector SetterSel,
2637                      const bool isAssign,
2638                      const bool isReadWrite,
2639                      const unsigned Attributes,
2640                      const unsigned AttributesAsWritten,
2641                      bool *isOverridingProperty,
2642                      TypeSourceInfo *T,
2643                      tok::ObjCKeywordKind MethodImplKind);
2644
2645  /// Called by ActOnProperty and HandlePropertyInClassExtension to
2646  /// handle creating the ObjcPropertyDecl for a category or \@interface.
2647  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2648                                       ObjCContainerDecl *CDecl,
2649                                       SourceLocation AtLoc,
2650                                       SourceLocation LParenLoc,
2651                                       FieldDeclarator &FD,
2652                                       Selector GetterSel,
2653                                       Selector SetterSel,
2654                                       const bool isAssign,
2655                                       const bool isReadWrite,
2656                                       const unsigned Attributes,
2657                                       const unsigned AttributesAsWritten,
2658                                       TypeSourceInfo *T,
2659                                       tok::ObjCKeywordKind MethodImplKind,
2660                                       DeclContext *lexicalDC = 0);
2661
2662  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2663  /// warning) when atomic property has one but not the other user-declared
2664  /// setter or getter.
2665  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2666                                       ObjCContainerDecl* IDecl);
2667
2668  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2669
2670  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2671
2672  enum MethodMatchStrategy {
2673    MMS_loose,
2674    MMS_strict
2675  };
2676
2677  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2678  /// true, or false, accordingly.
2679  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2680                                  const ObjCMethodDecl *PrevMethod,
2681                                  MethodMatchStrategy strategy = MMS_strict);
2682
2683  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2684  /// or protocol against those declared in their implementations.
2685  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2686                                  const SelectorSet &ClsMap,
2687                                  SelectorSet &InsMapSeen,
2688                                  SelectorSet &ClsMapSeen,
2689                                  ObjCImplDecl* IMPDecl,
2690                                  ObjCContainerDecl* IDecl,
2691                                  bool &IncompleteImpl,
2692                                  bool ImmediateClass,
2693                                  bool WarnCategoryMethodImpl=false);
2694
2695  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2696  /// category matches with those implemented in its primary class and
2697  /// warns each time an exact match is found.
2698  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2699
2700  /// \brief Add the given method to the list of globally-known methods.
2701  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2702
2703private:
2704  /// AddMethodToGlobalPool - Add an instance or factory method to the global
2705  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2706  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2707
2708  /// LookupMethodInGlobalPool - Returns the instance or factory method and
2709  /// optionally warns if there are multiple signatures.
2710  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2711                                           bool receiverIdOrClass,
2712                                           bool warn, bool instance);
2713
2714  /// \brief Record the typo correction failure and return an empty correction.
2715  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
2716                                  bool RecordFailure = true,
2717                                  bool IsUnqualifiedLookup = false) {
2718    if (IsUnqualifiedLookup)
2719      (void)UnqualifiedTyposCorrected[Typo];
2720    if (RecordFailure)
2721      TypoCorrectionFailures[Typo].insert(TypoLoc);
2722    return TypoCorrection();
2723  }
2724
2725public:
2726  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2727  /// unit are added to a global pool. This allows us to efficiently associate
2728  /// a selector with a method declaraation for purposes of typechecking
2729  /// messages sent to "id" (where the class of the object is unknown).
2730  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2731    AddMethodToGlobalPool(Method, impl, /*instance*/true);
2732  }
2733
2734  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2735  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2736    AddMethodToGlobalPool(Method, impl, /*instance*/false);
2737  }
2738
2739  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2740  /// pool.
2741  void AddAnyMethodToGlobalPool(Decl *D);
2742
2743  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2744  /// there are multiple signatures.
2745  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2746                                                   bool receiverIdOrClass=false,
2747                                                   bool warn=true) {
2748    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2749                                    warn, /*instance*/true);
2750  }
2751
2752  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2753  /// there are multiple signatures.
2754  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2755                                                  bool receiverIdOrClass=false,
2756                                                  bool warn=true) {
2757    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2758                                    warn, /*instance*/false);
2759  }
2760
2761  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
2762                              QualType ObjectType=QualType());
2763
2764  /// DiagnoseMismatchedMethodsInGlobalPool - This routine goes through list of
2765  /// methods in global pool and issues diagnostic on identical selectors which
2766  /// have mismathched types.
2767  void DiagnoseMismatchedMethodsInGlobalPool();
2768
2769  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2770  /// implementation.
2771  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2772
2773  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2774  /// initialization.
2775  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2776                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2777
2778  //===--------------------------------------------------------------------===//
2779  // Statement Parsing Callbacks: SemaStmt.cpp.
2780public:
2781  class FullExprArg {
2782  public:
2783    FullExprArg(Sema &actions) : E(0) { }
2784
2785    // FIXME: The const_cast here is ugly. RValue references would make this
2786    // much nicer (or we could duplicate a bunch of the move semantics
2787    // emulation code from Ownership.h).
2788    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2789
2790    ExprResult release() {
2791      return E;
2792    }
2793
2794    Expr *get() const { return E; }
2795
2796    Expr *operator->() {
2797      return E;
2798    }
2799
2800  private:
2801    // FIXME: No need to make the entire Sema class a friend when it's just
2802    // Sema::MakeFullExpr that needs access to the constructor below.
2803    friend class Sema;
2804
2805    explicit FullExprArg(Expr *expr) : E(expr) {}
2806
2807    Expr *E;
2808  };
2809
2810  FullExprArg MakeFullExpr(Expr *Arg) {
2811    return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2812  }
2813  FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2814    return FullExprArg(ActOnFinishFullExpr(Arg, CC).release());
2815  }
2816  FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
2817    ExprResult FE =
2818      ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
2819                          /*DiscardedValue*/ true);
2820    return FullExprArg(FE.release());
2821  }
2822
2823  StmtResult ActOnExprStmt(ExprResult Arg);
2824  StmtResult ActOnExprStmtError();
2825
2826  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2827                           bool HasLeadingEmptyMacro = false);
2828
2829  void ActOnStartOfCompoundStmt();
2830  void ActOnFinishOfCompoundStmt();
2831  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2832                               ArrayRef<Stmt *> Elts, bool isStmtExpr);
2833
2834  /// \brief A RAII object to enter scope of a compound statement.
2835  class CompoundScopeRAII {
2836  public:
2837    CompoundScopeRAII(Sema &S): S(S) {
2838      S.ActOnStartOfCompoundStmt();
2839    }
2840
2841    ~CompoundScopeRAII() {
2842      S.ActOnFinishOfCompoundStmt();
2843    }
2844
2845  private:
2846    Sema &S;
2847  };
2848
2849  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2850                                   SourceLocation StartLoc,
2851                                   SourceLocation EndLoc);
2852  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2853  StmtResult ActOnForEachLValueExpr(Expr *E);
2854  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2855                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
2856                                   SourceLocation ColonLoc);
2857  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2858
2859  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2860                                      SourceLocation ColonLoc,
2861                                      Stmt *SubStmt, Scope *CurScope);
2862  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2863                            SourceLocation ColonLoc, Stmt *SubStmt);
2864
2865  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
2866                                 ArrayRef<const Attr*> Attrs,
2867                                 Stmt *SubStmt);
2868
2869  StmtResult ActOnIfStmt(SourceLocation IfLoc,
2870                         FullExprArg CondVal, Decl *CondVar,
2871                         Stmt *ThenVal,
2872                         SourceLocation ElseLoc, Stmt *ElseVal);
2873  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2874                                            Expr *Cond,
2875                                            Decl *CondVar);
2876  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2877                                           Stmt *Switch, Stmt *Body);
2878  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2879                            FullExprArg Cond,
2880                            Decl *CondVar, Stmt *Body);
2881  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2882                                 SourceLocation WhileLoc,
2883                                 SourceLocation CondLParen, Expr *Cond,
2884                                 SourceLocation CondRParen);
2885
2886  StmtResult ActOnForStmt(SourceLocation ForLoc,
2887                          SourceLocation LParenLoc,
2888                          Stmt *First, FullExprArg Second,
2889                          Decl *SecondVar,
2890                          FullExprArg Third,
2891                          SourceLocation RParenLoc,
2892                          Stmt *Body);
2893  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
2894                                           Expr *collection);
2895  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2896                                        Stmt *First, Expr *collection,
2897                                        SourceLocation RParenLoc);
2898  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
2899
2900  enum BuildForRangeKind {
2901    /// Initial building of a for-range statement.
2902    BFRK_Build,
2903    /// Instantiation or recovery rebuild of a for-range statement. Don't
2904    /// attempt any typo-correction.
2905    BFRK_Rebuild,
2906    /// Determining whether a for-range statement could be built. Avoid any
2907    /// unnecessary or irreversible actions.
2908    BFRK_Check
2909  };
2910
2911  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
2912                                  SourceLocation ColonLoc, Expr *Collection,
2913                                  SourceLocation RParenLoc,
2914                                  BuildForRangeKind Kind);
2915  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2916                                  SourceLocation ColonLoc,
2917                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
2918                                  Expr *Cond, Expr *Inc,
2919                                  Stmt *LoopVarDecl,
2920                                  SourceLocation RParenLoc,
2921                                  BuildForRangeKind Kind);
2922  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2923
2924  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2925                           SourceLocation LabelLoc,
2926                           LabelDecl *TheDecl);
2927  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2928                                   SourceLocation StarLoc,
2929                                   Expr *DestExp);
2930  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2931  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
2932
2933  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
2934                                CapturedRegionKind Kind, unsigned NumParams);
2935  StmtResult ActOnCapturedRegionEnd(Stmt *S);
2936  void ActOnCapturedRegionError();
2937  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
2938                                           SourceLocation Loc,
2939                                           unsigned NumParams);
2940  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2941                                         bool AllowFunctionParameters);
2942
2943  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2944  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2945
2946  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2947                             bool IsVolatile, unsigned NumOutputs,
2948                             unsigned NumInputs, IdentifierInfo **Names,
2949                             MultiExprArg Constraints, MultiExprArg Exprs,
2950                             Expr *AsmString, MultiExprArg Clobbers,
2951                             SourceLocation RParenLoc);
2952
2953  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
2954                                       SourceLocation TemplateKWLoc,
2955                                       UnqualifiedId &Id,
2956                                       InlineAsmIdentifierInfo &Info,
2957                                       bool IsUnevaluatedContext);
2958  bool LookupInlineAsmField(StringRef Base, StringRef Member,
2959                            unsigned &Offset, SourceLocation AsmLoc);
2960  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
2961                            ArrayRef<Token> AsmToks,
2962                            StringRef AsmString,
2963                            unsigned NumOutputs, unsigned NumInputs,
2964                            ArrayRef<StringRef> Constraints,
2965                            ArrayRef<StringRef> Clobbers,
2966                            ArrayRef<Expr*> Exprs,
2967                            SourceLocation EndLoc);
2968
2969  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2970                                  SourceLocation StartLoc,
2971                                  SourceLocation IdLoc, IdentifierInfo *Id,
2972                                  bool Invalid = false);
2973
2974  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2975
2976  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2977                                  Decl *Parm, Stmt *Body);
2978
2979  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2980
2981  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2982                                MultiStmtArg Catch, Stmt *Finally);
2983
2984  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2985  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2986                                  Scope *CurScope);
2987  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
2988                                            Expr *operand);
2989  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2990                                         Expr *SynchExpr,
2991                                         Stmt *SynchBody);
2992
2993  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2994
2995  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2996                                     SourceLocation StartLoc,
2997                                     SourceLocation IdLoc,
2998                                     IdentifierInfo *Id);
2999
3000  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3001
3002  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3003                                Decl *ExDecl, Stmt *HandlerBlock);
3004  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3005                              ArrayRef<Stmt *> Handlers);
3006
3007  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3008                              SourceLocation TryLoc, Stmt *TryBlock,
3009                              Stmt *Handler);
3010
3011  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3012                                 Expr *FilterExpr,
3013                                 Stmt *Block);
3014
3015  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
3016                                  Stmt *Block);
3017
3018  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3019
3020  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3021
3022  /// \brief If it's a file scoped decl that must warn if not used, keep track
3023  /// of it.
3024  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3025
3026  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3027  /// whose result is unused, warn.
3028  void DiagnoseUnusedExprResult(const Stmt *S);
3029  void DiagnoseUnusedDecl(const NamedDecl *ND);
3030
3031  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3032  /// statement as a \p Body, and it is located on the same line.
3033  ///
3034  /// This helps prevent bugs due to typos, such as:
3035  ///     if (condition);
3036  ///       do_stuff();
3037  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3038                             const Stmt *Body,
3039                             unsigned DiagID);
3040
3041  /// Warn if a for/while loop statement \p S, which is followed by
3042  /// \p PossibleBody, has a suspicious null statement as a body.
3043  void DiagnoseEmptyLoopBody(const Stmt *S,
3044                             const Stmt *PossibleBody);
3045
3046  ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3047    return DelayedDiagnostics.push(pool);
3048  }
3049  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3050
3051  typedef ProcessingContextState ParsingClassState;
3052  ParsingClassState PushParsingClass() {
3053    return DelayedDiagnostics.pushUndelayed();
3054  }
3055  void PopParsingClass(ParsingClassState state) {
3056    DelayedDiagnostics.popUndelayed(state);
3057  }
3058
3059  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3060
3061  void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
3062                              SourceLocation Loc,
3063                              const ObjCInterfaceDecl *UnknownObjCClass,
3064                              const ObjCPropertyDecl  *ObjCProperty);
3065
3066  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3067
3068  bool makeUnavailableInSystemHeader(SourceLocation loc,
3069                                     StringRef message);
3070
3071  //===--------------------------------------------------------------------===//
3072  // Expression Parsing Callbacks: SemaExpr.cpp.
3073
3074  bool CanUseDecl(NamedDecl *D);
3075  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3076                         const ObjCInterfaceDecl *UnknownObjCClass=0);
3077  void NoteDeletedFunction(FunctionDecl *FD);
3078  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3079  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3080                                        ObjCMethodDecl *Getter,
3081                                        SourceLocation Loc);
3082  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3083                             ArrayRef<Expr *> Args);
3084
3085  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3086                                       Decl *LambdaContextDecl = 0,
3087                                       bool IsDecltype = false);
3088  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3089  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3090                                       ReuseLambdaContextDecl_t,
3091                                       bool IsDecltype = false);
3092  void PopExpressionEvaluationContext();
3093
3094  void DiscardCleanupsInEvaluationContext();
3095
3096  ExprResult TransformToPotentiallyEvaluated(Expr *E);
3097  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3098
3099  ExprResult ActOnConstantExpression(ExprResult Res);
3100
3101  // Functions for marking a declaration referenced.  These functions also
3102  // contain the relevant logic for marking if a reference to a function or
3103  // variable is an odr-use (in the C++11 sense).  There are separate variants
3104  // for expressions referring to a decl; these exist because odr-use marking
3105  // needs to be delayed for some constant variables when we build one of the
3106  // named expressions.
3107  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3108  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
3109  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3110  void MarkDeclRefReferenced(DeclRefExpr *E);
3111  void MarkMemberReferenced(MemberExpr *E);
3112
3113  void UpdateMarkingForLValueToRValue(Expr *E);
3114  void CleanupVarDeclMarking();
3115
3116  enum TryCaptureKind {
3117    TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3118  };
3119
3120  /// \brief Try to capture the given variable.
3121  ///
3122  /// \param Var The variable to capture.
3123  ///
3124  /// \param Loc The location at which the capture occurs.
3125  ///
3126  /// \param Kind The kind of capture, which may be implicit (for either a
3127  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3128  ///
3129  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3130  /// an explicit lambda capture.
3131  ///
3132  /// \param BuildAndDiagnose Whether we are actually supposed to add the
3133  /// captures or diagnose errors. If false, this routine merely check whether
3134  /// the capture can occur without performing the capture itself or complaining
3135  /// if the variable cannot be captured.
3136  ///
3137  /// \param CaptureType Will be set to the type of the field used to capture
3138  /// this variable in the innermost block or lambda. Only valid when the
3139  /// variable can be captured.
3140  ///
3141  /// \param DeclRefType Will be set to the type of a reference to the capture
3142  /// from within the current scope. Only valid when the variable can be
3143  /// captured.
3144  ///
3145  /// \returns true if an error occurred (i.e., the variable cannot be
3146  /// captured) and false if the capture succeeded.
3147  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3148                          SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3149                          QualType &CaptureType,
3150                          QualType &DeclRefType);
3151
3152  /// \brief Try to capture the given variable.
3153  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3154                          TryCaptureKind Kind = TryCapture_Implicit,
3155                          SourceLocation EllipsisLoc = SourceLocation());
3156
3157  /// \brief Given a variable, determine the type that a reference to that
3158  /// variable will have in the given scope.
3159  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3160
3161  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3162  void MarkDeclarationsReferencedInExpr(Expr *E,
3163                                        bool SkipLocalVariables = false);
3164
3165  /// \brief Try to recover by turning the given expression into a
3166  /// call.  Returns true if recovery was attempted or an error was
3167  /// emitted; this may also leave the ExprResult invalid.
3168  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3169                            bool ForceComplain = false,
3170                            bool (*IsPlausibleResult)(QualType) = 0);
3171
3172  /// \brief Figure out if an expression could be turned into a call.
3173  bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3174                     UnresolvedSetImpl &NonTemplateOverloads);
3175
3176  /// \brief Conditionally issue a diagnostic based on the current
3177  /// evaluation context.
3178  ///
3179  /// \param Statement If Statement is non-null, delay reporting the
3180  /// diagnostic until the function body is parsed, and then do a basic
3181  /// reachability analysis to determine if the statement is reachable.
3182  /// If it is unreachable, the diagnostic will not be emitted.
3183  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3184                           const PartialDiagnostic &PD);
3185
3186  // Primary Expressions.
3187  SourceRange getExprRange(Expr *E) const;
3188
3189  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
3190                               SourceLocation TemplateKWLoc,
3191                               UnqualifiedId &Id,
3192                               bool HasTrailingLParen, bool IsAddressOfOperand,
3193                               CorrectionCandidateCallback *CCC = 0,
3194                               bool IsInlineAsmIdentifier = false);
3195
3196  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3197                              TemplateArgumentListInfo &Buffer,
3198                              DeclarationNameInfo &NameInfo,
3199                              const TemplateArgumentListInfo *&TemplateArgs);
3200
3201  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3202                           CorrectionCandidateCallback &CCC,
3203                           TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
3204                           ArrayRef<Expr *> Args = None);
3205
3206  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3207                                IdentifierInfo *II,
3208                                bool AllowBuiltinCreation=false);
3209
3210  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3211                                        SourceLocation TemplateKWLoc,
3212                                        const DeclarationNameInfo &NameInfo,
3213                                        bool isAddressOfOperand,
3214                                const TemplateArgumentListInfo *TemplateArgs);
3215
3216  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3217                              ExprValueKind VK,
3218                              SourceLocation Loc,
3219                              const CXXScopeSpec *SS = 0);
3220  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3221                              const DeclarationNameInfo &NameInfo,
3222                              const CXXScopeSpec *SS = 0, NamedDecl *FoundD = 0,
3223                              const TemplateArgumentListInfo *TemplateArgs = 0);
3224  ExprResult
3225  BuildAnonymousStructUnionMemberReference(
3226      const CXXScopeSpec &SS,
3227      SourceLocation nameLoc,
3228      IndirectFieldDecl *indirectField,
3229      DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_none),
3230      Expr *baseObjectExpr = 0,
3231      SourceLocation opLoc = SourceLocation());
3232
3233  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3234                                             SourceLocation TemplateKWLoc,
3235                                             LookupResult &R,
3236                                const TemplateArgumentListInfo *TemplateArgs);
3237  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3238                                     SourceLocation TemplateKWLoc,
3239                                     LookupResult &R,
3240                                const TemplateArgumentListInfo *TemplateArgs,
3241                                     bool IsDefiniteInstance);
3242  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3243                                  const LookupResult &R,
3244                                  bool HasTrailingLParen);
3245
3246  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3247                                         const DeclarationNameInfo &NameInfo,
3248                                               bool IsAddressOfOperand);
3249  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3250                                       SourceLocation TemplateKWLoc,
3251                                const DeclarationNameInfo &NameInfo,
3252                                const TemplateArgumentListInfo *TemplateArgs);
3253
3254  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3255                                      LookupResult &R,
3256                                      bool NeedsADL);
3257  ExprResult BuildDeclarationNameExpr(
3258      const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3259      NamedDecl *FoundD = 0, const TemplateArgumentListInfo *TemplateArgs = 0);
3260
3261  ExprResult BuildLiteralOperatorCall(LookupResult &R,
3262                                      DeclarationNameInfo &SuffixInfo,
3263                                      ArrayRef<Expr*> Args,
3264                                      SourceLocation LitEndLoc,
3265                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
3266
3267  ExprResult BuildPredefinedExpr(SourceLocation Loc,
3268                                 PredefinedExpr::IdentType IT);
3269  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3270  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3271  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
3272  ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
3273  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3274  ExprResult ActOnParenListExpr(SourceLocation L,
3275                                SourceLocation R,
3276                                MultiExprArg Val);
3277
3278  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3279  /// fragments (e.g. "foo" "bar" L"baz").
3280  ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
3281                                Scope *UDLScope = 0);
3282
3283  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3284                                       SourceLocation DefaultLoc,
3285                                       SourceLocation RParenLoc,
3286                                       Expr *ControllingExpr,
3287                                       ArrayRef<ParsedType> ArgTypes,
3288                                       ArrayRef<Expr *> ArgExprs);
3289  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3290                                        SourceLocation DefaultLoc,
3291                                        SourceLocation RParenLoc,
3292                                        Expr *ControllingExpr,
3293                                        ArrayRef<TypeSourceInfo *> Types,
3294                                        ArrayRef<Expr *> Exprs);
3295
3296  // Binary/Unary Operators.  'Tok' is the token for the operator.
3297  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3298                                  Expr *InputExpr);
3299  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3300                          UnaryOperatorKind Opc, Expr *Input);
3301  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3302                          tok::TokenKind Op, Expr *Input);
3303
3304  QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3305
3306  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3307                                            SourceLocation OpLoc,
3308                                            UnaryExprOrTypeTrait ExprKind,
3309                                            SourceRange R);
3310  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3311                                            UnaryExprOrTypeTrait ExprKind);
3312  ExprResult
3313    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3314                                  UnaryExprOrTypeTrait ExprKind,
3315                                  bool IsType, void *TyOrEx,
3316                                  const SourceRange &ArgRange);
3317
3318  ExprResult CheckPlaceholderExpr(Expr *E);
3319  bool CheckVecStepExpr(Expr *E);
3320
3321  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3322  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3323                                        SourceRange ExprRange,
3324                                        UnaryExprOrTypeTrait ExprKind);
3325  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3326                                          SourceLocation OpLoc,
3327                                          IdentifierInfo &Name,
3328                                          SourceLocation NameLoc,
3329                                          SourceLocation RParenLoc);
3330  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3331                                 tok::TokenKind Kind, Expr *Input);
3332
3333  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3334                                     Expr *Idx, SourceLocation RLoc);
3335  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3336                                             Expr *Idx, SourceLocation RLoc);
3337
3338  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3339                                      SourceLocation OpLoc, bool IsArrow,
3340                                      CXXScopeSpec &SS,
3341                                      SourceLocation TemplateKWLoc,
3342                                      NamedDecl *FirstQualifierInScope,
3343                                const DeclarationNameInfo &NameInfo,
3344                                const TemplateArgumentListInfo *TemplateArgs);
3345
3346  // This struct is for use by ActOnMemberAccess to allow
3347  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3348  // changing the access operator from a '.' to a '->' (to see if that is the
3349  // change needed to fix an error about an unknown member, e.g. when the class
3350  // defines a custom operator->).
3351  struct ActOnMemberAccessExtraArgs {
3352    Scope *S;
3353    UnqualifiedId &Id;
3354    Decl *ObjCImpDecl;
3355    bool HasTrailingLParen;
3356  };
3357
3358  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3359                                      SourceLocation OpLoc, bool IsArrow,
3360                                      const CXXScopeSpec &SS,
3361                                      SourceLocation TemplateKWLoc,
3362                                      NamedDecl *FirstQualifierInScope,
3363                                      LookupResult &R,
3364                                 const TemplateArgumentListInfo *TemplateArgs,
3365                                      bool SuppressQualifierCheck = false,
3366                                     ActOnMemberAccessExtraArgs *ExtraArgs = 0);
3367
3368  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3369  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
3370                              bool &IsArrow, SourceLocation OpLoc,
3371                              CXXScopeSpec &SS,
3372                              Decl *ObjCImpDecl,
3373                              bool HasTemplateArgs);
3374
3375  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3376                                     const CXXScopeSpec &SS,
3377                                     const LookupResult &R);
3378
3379  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3380                                      bool IsArrow, SourceLocation OpLoc,
3381                                      const CXXScopeSpec &SS,
3382                                      SourceLocation TemplateKWLoc,
3383                                      NamedDecl *FirstQualifierInScope,
3384                               const DeclarationNameInfo &NameInfo,
3385                               const TemplateArgumentListInfo *TemplateArgs);
3386
3387  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3388                                   SourceLocation OpLoc,
3389                                   tok::TokenKind OpKind,
3390                                   CXXScopeSpec &SS,
3391                                   SourceLocation TemplateKWLoc,
3392                                   UnqualifiedId &Member,
3393                                   Decl *ObjCImpDecl,
3394                                   bool HasTrailingLParen);
3395
3396  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3397  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3398                               FunctionDecl *FDecl,
3399                               const FunctionProtoType *Proto,
3400                               ArrayRef<Expr *> Args,
3401                               SourceLocation RParenLoc,
3402                               bool ExecConfig = false);
3403  void CheckStaticArrayArgument(SourceLocation CallLoc,
3404                                ParmVarDecl *Param,
3405                                const Expr *ArgExpr);
3406
3407  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3408  /// This provides the location of the left/right parens and a list of comma
3409  /// locations.
3410  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3411                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
3412                           Expr *ExecConfig = 0, bool IsExecConfig = false);
3413  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3414                                   SourceLocation LParenLoc,
3415                                   ArrayRef<Expr *> Arg,
3416                                   SourceLocation RParenLoc,
3417                                   Expr *Config = 0,
3418                                   bool IsExecConfig = false);
3419
3420  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3421                                     MultiExprArg ExecConfig,
3422                                     SourceLocation GGGLoc);
3423
3424  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3425                           Declarator &D, ParsedType &Ty,
3426                           SourceLocation RParenLoc, Expr *CastExpr);
3427  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3428                                 TypeSourceInfo *Ty,
3429                                 SourceLocation RParenLoc,
3430                                 Expr *Op);
3431  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3432
3433  /// \brief Build an altivec or OpenCL literal.
3434  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3435                                SourceLocation RParenLoc, Expr *E,
3436                                TypeSourceInfo *TInfo);
3437
3438  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3439
3440  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3441                                  ParsedType Ty,
3442                                  SourceLocation RParenLoc,
3443                                  Expr *InitExpr);
3444
3445  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3446                                      TypeSourceInfo *TInfo,
3447                                      SourceLocation RParenLoc,
3448                                      Expr *LiteralExpr);
3449
3450  ExprResult ActOnInitList(SourceLocation LBraceLoc,
3451                           MultiExprArg InitArgList,
3452                           SourceLocation RBraceLoc);
3453
3454  ExprResult ActOnDesignatedInitializer(Designation &Desig,
3455                                        SourceLocation Loc,
3456                                        bool GNUSyntax,
3457                                        ExprResult Init);
3458
3459  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3460                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3461  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3462                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3463  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3464                                Expr *LHSExpr, Expr *RHSExpr);
3465
3466  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3467  /// in the case of a the GNU conditional expr extension.
3468  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3469                                SourceLocation ColonLoc,
3470                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3471
3472  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3473  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3474                            LabelDecl *TheDecl);
3475
3476  void ActOnStartStmtExpr();
3477  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3478                           SourceLocation RPLoc); // "({..})"
3479  void ActOnStmtExprError();
3480
3481  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3482  struct OffsetOfComponent {
3483    SourceLocation LocStart, LocEnd;
3484    bool isBrackets;  // true if [expr], false if .ident
3485    union {
3486      IdentifierInfo *IdentInfo;
3487      Expr *E;
3488    } U;
3489  };
3490
3491  /// __builtin_offsetof(type, a.b[123][456].c)
3492  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3493                                  TypeSourceInfo *TInfo,
3494                                  OffsetOfComponent *CompPtr,
3495                                  unsigned NumComponents,
3496                                  SourceLocation RParenLoc);
3497  ExprResult ActOnBuiltinOffsetOf(Scope *S,
3498                                  SourceLocation BuiltinLoc,
3499                                  SourceLocation TypeLoc,
3500                                  ParsedType ParsedArgTy,
3501                                  OffsetOfComponent *CompPtr,
3502                                  unsigned NumComponents,
3503                                  SourceLocation RParenLoc);
3504
3505  // __builtin_choose_expr(constExpr, expr1, expr2)
3506  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3507                             Expr *CondExpr, Expr *LHSExpr,
3508                             Expr *RHSExpr, SourceLocation RPLoc);
3509
3510  // __builtin_va_arg(expr, type)
3511  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3512                        SourceLocation RPLoc);
3513  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3514                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
3515
3516  // __null
3517  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3518
3519  bool CheckCaseExpression(Expr *E);
3520
3521  /// \brief Describes the result of an "if-exists" condition check.
3522  enum IfExistsResult {
3523    /// \brief The symbol exists.
3524    IER_Exists,
3525
3526    /// \brief The symbol does not exist.
3527    IER_DoesNotExist,
3528
3529    /// \brief The name is a dependent name, so the results will differ
3530    /// from one instantiation to the next.
3531    IER_Dependent,
3532
3533    /// \brief An error occurred.
3534    IER_Error
3535  };
3536
3537  IfExistsResult
3538  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3539                               const DeclarationNameInfo &TargetNameInfo);
3540
3541  IfExistsResult
3542  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3543                               bool IsIfExists, CXXScopeSpec &SS,
3544                               UnqualifiedId &Name);
3545
3546  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3547                                        bool IsIfExists,
3548                                        NestedNameSpecifierLoc QualifierLoc,
3549                                        DeclarationNameInfo NameInfo,
3550                                        Stmt *Nested);
3551  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3552                                        bool IsIfExists,
3553                                        CXXScopeSpec &SS, UnqualifiedId &Name,
3554                                        Stmt *Nested);
3555
3556  //===------------------------- "Block" Extension ------------------------===//
3557
3558  /// ActOnBlockStart - This callback is invoked when a block literal is
3559  /// started.
3560  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3561
3562  /// ActOnBlockArguments - This callback allows processing of block arguments.
3563  /// If there are no arguments, this is still invoked.
3564  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3565                           Scope *CurScope);
3566
3567  /// ActOnBlockError - If there is an error parsing a block, this callback
3568  /// is invoked to pop the information about the block from the action impl.
3569  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3570
3571  /// ActOnBlockStmtExpr - This is called when the body of a block statement
3572  /// literal was successfully completed.  ^(int x){...}
3573  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3574                                Scope *CurScope);
3575
3576  //===---------------------------- Clang Extensions ----------------------===//
3577
3578  /// __builtin_convertvector(...)
3579  ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
3580                                    SourceLocation BuiltinLoc,
3581                                    SourceLocation RParenLoc);
3582
3583  //===---------------------------- OpenCL Features -----------------------===//
3584
3585  /// __builtin_astype(...)
3586  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3587                             SourceLocation BuiltinLoc,
3588                             SourceLocation RParenLoc);
3589
3590  //===---------------------------- C++ Features --------------------------===//
3591
3592  // Act on C++ namespaces
3593  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3594                               SourceLocation NamespaceLoc,
3595                               SourceLocation IdentLoc,
3596                               IdentifierInfo *Ident,
3597                               SourceLocation LBrace,
3598                               AttributeList *AttrList);
3599  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3600
3601  NamespaceDecl *getStdNamespace() const;
3602  NamespaceDecl *getOrCreateStdNamespace();
3603
3604  CXXRecordDecl *getStdBadAlloc() const;
3605
3606  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3607  /// it is and Element is not NULL, assigns the element type to Element.
3608  bool isStdInitializerList(QualType Ty, QualType *Element);
3609
3610  /// \brief Looks for the std::initializer_list template and instantiates it
3611  /// with Element, or emits an error if it's not found.
3612  ///
3613  /// \returns The instantiated template, or null on error.
3614  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3615
3616  /// \brief Determine whether Ctor is an initializer-list constructor, as
3617  /// defined in [dcl.init.list]p2.
3618  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3619
3620  Decl *ActOnUsingDirective(Scope *CurScope,
3621                            SourceLocation UsingLoc,
3622                            SourceLocation NamespcLoc,
3623                            CXXScopeSpec &SS,
3624                            SourceLocation IdentLoc,
3625                            IdentifierInfo *NamespcName,
3626                            AttributeList *AttrList);
3627
3628  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3629
3630  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3631                               SourceLocation NamespaceLoc,
3632                               SourceLocation AliasLoc,
3633                               IdentifierInfo *Alias,
3634                               CXXScopeSpec &SS,
3635                               SourceLocation IdentLoc,
3636                               IdentifierInfo *Ident);
3637
3638  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3639  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3640                            const LookupResult &PreviousDecls);
3641  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3642                                        NamedDecl *Target);
3643
3644  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3645                                   bool HasTypenameKeyword,
3646                                   const CXXScopeSpec &SS,
3647                                   SourceLocation NameLoc,
3648                                   const LookupResult &Previous);
3649  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3650                               const CXXScopeSpec &SS,
3651                               SourceLocation NameLoc);
3652
3653  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3654                                   SourceLocation UsingLoc,
3655                                   CXXScopeSpec &SS,
3656                                   const DeclarationNameInfo &NameInfo,
3657                                   AttributeList *AttrList,
3658                                   bool IsInstantiation,
3659                                   bool HasTypenameKeyword,
3660                                   SourceLocation TypenameLoc);
3661
3662  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3663
3664  Decl *ActOnUsingDeclaration(Scope *CurScope,
3665                              AccessSpecifier AS,
3666                              bool HasUsingKeyword,
3667                              SourceLocation UsingLoc,
3668                              CXXScopeSpec &SS,
3669                              UnqualifiedId &Name,
3670                              AttributeList *AttrList,
3671                              bool HasTypenameKeyword,
3672                              SourceLocation TypenameLoc);
3673  Decl *ActOnAliasDeclaration(Scope *CurScope,
3674                              AccessSpecifier AS,
3675                              MultiTemplateParamsArg TemplateParams,
3676                              SourceLocation UsingLoc,
3677                              UnqualifiedId &Name,
3678                              AttributeList *AttrList,
3679                              TypeResult Type);
3680
3681  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3682  /// including handling of its default argument expressions.
3683  ///
3684  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3685  ExprResult
3686  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3687                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3688                        bool HadMultipleCandidates, bool IsListInitialization,
3689                        bool RequiresZeroInit, unsigned ConstructKind,
3690                        SourceRange ParenRange);
3691
3692  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3693  // the constructor can be elidable?
3694  ExprResult
3695  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3696                        CXXConstructorDecl *Constructor, bool Elidable,
3697                        MultiExprArg Exprs, bool HadMultipleCandidates,
3698                        bool IsListInitialization, bool RequiresZeroInit,
3699                        unsigned ConstructKind, SourceRange ParenRange);
3700
3701  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3702  /// the default expr if needed.
3703  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3704                                    FunctionDecl *FD,
3705                                    ParmVarDecl *Param);
3706
3707  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3708  /// constructed variable.
3709  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3710
3711  /// \brief Helper class that collects exception specifications for
3712  /// implicitly-declared special member functions.
3713  class ImplicitExceptionSpecification {
3714    // Pointer to allow copying
3715    Sema *Self;
3716    // We order exception specifications thus:
3717    // noexcept is the most restrictive, but is only used in C++11.
3718    // throw() comes next.
3719    // Then a throw(collected exceptions)
3720    // Finally no specification, which is expressed as noexcept(false).
3721    // throw(...) is used instead if any called function uses it.
3722    ExceptionSpecificationType ComputedEST;
3723    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3724    SmallVector<QualType, 4> Exceptions;
3725
3726    void ClearExceptions() {
3727      ExceptionsSeen.clear();
3728      Exceptions.clear();
3729    }
3730
3731  public:
3732    explicit ImplicitExceptionSpecification(Sema &Self)
3733      : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3734      if (!Self.getLangOpts().CPlusPlus11)
3735        ComputedEST = EST_DynamicNone;
3736    }
3737
3738    /// \brief Get the computed exception specification type.
3739    ExceptionSpecificationType getExceptionSpecType() const {
3740      assert(ComputedEST != EST_ComputedNoexcept &&
3741             "noexcept(expr) should not be a possible result");
3742      return ComputedEST;
3743    }
3744
3745    /// \brief The number of exceptions in the exception specification.
3746    unsigned size() const { return Exceptions.size(); }
3747
3748    /// \brief The set of exceptions in the exception specification.
3749    const QualType *data() const { return Exceptions.data(); }
3750
3751    /// \brief Integrate another called method into the collected data.
3752    void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
3753
3754    /// \brief Integrate an invoked expression into the collected data.
3755    void CalledExpr(Expr *E);
3756
3757    /// \brief Overwrite an EPI's exception specification with this
3758    /// computed exception specification.
3759    void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3760      EPI.ExceptionSpecType = getExceptionSpecType();
3761      if (EPI.ExceptionSpecType == EST_Dynamic) {
3762        EPI.NumExceptions = size();
3763        EPI.Exceptions = data();
3764      } else if (EPI.ExceptionSpecType == EST_None) {
3765        /// C++11 [except.spec]p14:
3766        ///   The exception-specification is noexcept(false) if the set of
3767        ///   potential exceptions of the special member function contains "any"
3768        EPI.ExceptionSpecType = EST_ComputedNoexcept;
3769        EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3770                                                     tok::kw_false).take();
3771      }
3772    }
3773    FunctionProtoType::ExtProtoInfo getEPI() const {
3774      FunctionProtoType::ExtProtoInfo EPI;
3775      getEPI(EPI);
3776      return EPI;
3777    }
3778  };
3779
3780  /// \brief Determine what sort of exception specification a defaulted
3781  /// copy constructor of a class will have.
3782  ImplicitExceptionSpecification
3783  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3784                                           CXXMethodDecl *MD);
3785
3786  /// \brief Determine what sort of exception specification a defaulted
3787  /// default constructor of a class will have, and whether the parameter
3788  /// will be const.
3789  ImplicitExceptionSpecification
3790  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3791
3792  /// \brief Determine what sort of exception specification a defautled
3793  /// copy assignment operator of a class will have, and whether the
3794  /// parameter will be const.
3795  ImplicitExceptionSpecification
3796  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3797
3798  /// \brief Determine what sort of exception specification a defaulted move
3799  /// constructor of a class will have.
3800  ImplicitExceptionSpecification
3801  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3802
3803  /// \brief Determine what sort of exception specification a defaulted move
3804  /// assignment operator of a class will have.
3805  ImplicitExceptionSpecification
3806  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3807
3808  /// \brief Determine what sort of exception specification a defaulted
3809  /// destructor of a class will have.
3810  ImplicitExceptionSpecification
3811  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3812
3813  /// \brief Determine what sort of exception specification an inheriting
3814  /// constructor of a class will have.
3815  ImplicitExceptionSpecification
3816  ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
3817
3818  /// \brief Evaluate the implicit exception specification for a defaulted
3819  /// special member function.
3820  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3821
3822  /// \brief Check the given exception-specification and update the
3823  /// extended prototype information with the results.
3824  void checkExceptionSpecification(ExceptionSpecificationType EST,
3825                                   ArrayRef<ParsedType> DynamicExceptions,
3826                                   ArrayRef<SourceRange> DynamicExceptionRanges,
3827                                   Expr *NoexceptExpr,
3828                                   SmallVectorImpl<QualType> &Exceptions,
3829                                   FunctionProtoType::ExtProtoInfo &EPI);
3830
3831  /// \brief Determine if a special member function should have a deleted
3832  /// definition when it is defaulted.
3833  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3834                                 bool Diagnose = false);
3835
3836  /// \brief Declare the implicit default constructor for the given class.
3837  ///
3838  /// \param ClassDecl The class declaration into which the implicit
3839  /// default constructor will be added.
3840  ///
3841  /// \returns The implicitly-declared default constructor.
3842  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3843                                                     CXXRecordDecl *ClassDecl);
3844
3845  /// DefineImplicitDefaultConstructor - Checks for feasibility of
3846  /// defining this constructor as the default constructor.
3847  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3848                                        CXXConstructorDecl *Constructor);
3849
3850  /// \brief Declare the implicit destructor for the given class.
3851  ///
3852  /// \param ClassDecl The class declaration into which the implicit
3853  /// destructor will be added.
3854  ///
3855  /// \returns The implicitly-declared destructor.
3856  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3857
3858  /// DefineImplicitDestructor - Checks for feasibility of
3859  /// defining this destructor as the default destructor.
3860  void DefineImplicitDestructor(SourceLocation CurrentLocation,
3861                                CXXDestructorDecl *Destructor);
3862
3863  /// \brief Build an exception spec for destructors that don't have one.
3864  ///
3865  /// C++11 says that user-defined destructors with no exception spec get one
3866  /// that looks as if the destructor was implicitly declared.
3867  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3868                                     CXXDestructorDecl *Destructor);
3869
3870  /// \brief Declare all inheriting constructors for the given class.
3871  ///
3872  /// \param ClassDecl The class declaration into which the inheriting
3873  /// constructors will be added.
3874  void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
3875
3876  /// \brief Define the specified inheriting constructor.
3877  void DefineInheritingConstructor(SourceLocation UseLoc,
3878                                   CXXConstructorDecl *Constructor);
3879
3880  /// \brief Declare the implicit copy constructor for the given class.
3881  ///
3882  /// \param ClassDecl The class declaration into which the implicit
3883  /// copy constructor will be added.
3884  ///
3885  /// \returns The implicitly-declared copy constructor.
3886  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3887
3888  /// DefineImplicitCopyConstructor - Checks for feasibility of
3889  /// defining this constructor as the copy constructor.
3890  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3891                                     CXXConstructorDecl *Constructor);
3892
3893  /// \brief Declare the implicit move constructor for the given class.
3894  ///
3895  /// \param ClassDecl The Class declaration into which the implicit
3896  /// move constructor will be added.
3897  ///
3898  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3899  /// declared.
3900  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3901
3902  /// DefineImplicitMoveConstructor - Checks for feasibility of
3903  /// defining this constructor as the move constructor.
3904  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3905                                     CXXConstructorDecl *Constructor);
3906
3907  /// \brief Declare the implicit copy assignment operator for the given class.
3908  ///
3909  /// \param ClassDecl The class declaration into which the implicit
3910  /// copy assignment operator will be added.
3911  ///
3912  /// \returns The implicitly-declared copy assignment operator.
3913  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3914
3915  /// \brief Defines an implicitly-declared copy assignment operator.
3916  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3917                                    CXXMethodDecl *MethodDecl);
3918
3919  /// \brief Declare the implicit move assignment operator for the given class.
3920  ///
3921  /// \param ClassDecl The Class declaration into which the implicit
3922  /// move assignment operator will be added.
3923  ///
3924  /// \returns The implicitly-declared move assignment operator, or NULL if it
3925  /// wasn't declared.
3926  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3927
3928  /// \brief Defines an implicitly-declared move assignment operator.
3929  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3930                                    CXXMethodDecl *MethodDecl);
3931
3932  /// \brief Force the declaration of any implicitly-declared members of this
3933  /// class.
3934  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3935
3936  /// \brief Determine whether the given function is an implicitly-deleted
3937  /// special member function.
3938  bool isImplicitlyDeleted(FunctionDecl *FD);
3939
3940  /// \brief Check whether 'this' shows up in the type of a static member
3941  /// function after the (naturally empty) cv-qualifier-seq would be.
3942  ///
3943  /// \returns true if an error occurred.
3944  bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3945
3946  /// \brief Whether this' shows up in the exception specification of a static
3947  /// member function.
3948  bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3949
3950  /// \brief Check whether 'this' shows up in the attributes of the given
3951  /// static member function.
3952  ///
3953  /// \returns true if an error occurred.
3954  bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3955
3956  /// MaybeBindToTemporary - If the passed in expression has a record type with
3957  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3958  /// it simply returns the passed in expression.
3959  ExprResult MaybeBindToTemporary(Expr *E);
3960
3961  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3962                               MultiExprArg ArgsPtr,
3963                               SourceLocation Loc,
3964                               SmallVectorImpl<Expr*> &ConvertedArgs,
3965                               bool AllowExplicit = false,
3966                               bool IsListInitialization = false);
3967
3968  ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
3969                                          SourceLocation NameLoc,
3970                                          IdentifierInfo &Name);
3971
3972  ParsedType getDestructorName(SourceLocation TildeLoc,
3973                               IdentifierInfo &II, SourceLocation NameLoc,
3974                               Scope *S, CXXScopeSpec &SS,
3975                               ParsedType ObjectType,
3976                               bool EnteringContext);
3977
3978  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3979
3980  // Checks that reinterpret casts don't have undefined behavior.
3981  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3982                                      bool IsDereference, SourceRange Range);
3983
3984  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3985  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3986                               tok::TokenKind Kind,
3987                               SourceLocation LAngleBracketLoc,
3988                               Declarator &D,
3989                               SourceLocation RAngleBracketLoc,
3990                               SourceLocation LParenLoc,
3991                               Expr *E,
3992                               SourceLocation RParenLoc);
3993
3994  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3995                               tok::TokenKind Kind,
3996                               TypeSourceInfo *Ty,
3997                               Expr *E,
3998                               SourceRange AngleBrackets,
3999                               SourceRange Parens);
4000
4001  ExprResult BuildCXXTypeId(QualType TypeInfoType,
4002                            SourceLocation TypeidLoc,
4003                            TypeSourceInfo *Operand,
4004                            SourceLocation RParenLoc);
4005  ExprResult BuildCXXTypeId(QualType TypeInfoType,
4006                            SourceLocation TypeidLoc,
4007                            Expr *Operand,
4008                            SourceLocation RParenLoc);
4009
4010  /// ActOnCXXTypeid - Parse typeid( something ).
4011  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4012                            SourceLocation LParenLoc, bool isType,
4013                            void *TyOrExpr,
4014                            SourceLocation RParenLoc);
4015
4016  ExprResult BuildCXXUuidof(QualType TypeInfoType,
4017                            SourceLocation TypeidLoc,
4018                            TypeSourceInfo *Operand,
4019                            SourceLocation RParenLoc);
4020  ExprResult BuildCXXUuidof(QualType TypeInfoType,
4021                            SourceLocation TypeidLoc,
4022                            Expr *Operand,
4023                            SourceLocation RParenLoc);
4024
4025  /// ActOnCXXUuidof - Parse __uuidof( something ).
4026  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4027                            SourceLocation LParenLoc, bool isType,
4028                            void *TyOrExpr,
4029                            SourceLocation RParenLoc);
4030
4031
4032  //// ActOnCXXThis -  Parse 'this' pointer.
4033  ExprResult ActOnCXXThis(SourceLocation loc);
4034
4035  /// \brief Try to retrieve the type of the 'this' pointer.
4036  ///
4037  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4038  QualType getCurrentThisType();
4039
4040  /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4041  /// current context not being a non-static member function. In such cases,
4042  /// this provides the type used for 'this'.
4043  QualType CXXThisTypeOverride;
4044
4045  /// \brief RAII object used to temporarily allow the C++ 'this' expression
4046  /// to be used, with the given qualifiers on the current class type.
4047  class CXXThisScopeRAII {
4048    Sema &S;
4049    QualType OldCXXThisTypeOverride;
4050    bool Enabled;
4051
4052  public:
4053    /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4054    /// using the given declaration (which is either a class template or a
4055    /// class) along with the given qualifiers.
4056    /// along with the qualifiers placed on '*this'.
4057    CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4058                     bool Enabled = true);
4059
4060    ~CXXThisScopeRAII();
4061  };
4062
4063  /// \brief Make sure the value of 'this' is actually available in the current
4064  /// context, if it is a potentially evaluated context.
4065  ///
4066  /// \param Loc The location at which the capture of 'this' occurs.
4067  ///
4068  /// \param Explicit Whether 'this' is explicitly captured in a lambda
4069  /// capture list.
4070  void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
4071
4072  /// \brief Determine whether the given type is the type of *this that is used
4073  /// outside of the body of a member function for a type that is currently
4074  /// being defined.
4075  bool isThisOutsideMemberFunctionBody(QualType BaseType);
4076
4077  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4078  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4079
4080
4081  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4082  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4083
4084  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4085  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4086
4087  //// ActOnCXXThrow -  Parse throw expressions.
4088  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4089  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4090                           bool IsThrownVarInScope);
4091  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
4092                                  bool IsThrownVarInScope);
4093
4094  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4095  /// Can be interpreted either as function-style casting ("int(x)")
4096  /// or class type construction ("ClassType(x,y,z)")
4097  /// or creation of a value-initialized type ("int()").
4098  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4099                                       SourceLocation LParenLoc,
4100                                       MultiExprArg Exprs,
4101                                       SourceLocation RParenLoc);
4102
4103  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4104                                       SourceLocation LParenLoc,
4105                                       MultiExprArg Exprs,
4106                                       SourceLocation RParenLoc);
4107
4108  /// ActOnCXXNew - Parsed a C++ 'new' expression.
4109  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4110                         SourceLocation PlacementLParen,
4111                         MultiExprArg PlacementArgs,
4112                         SourceLocation PlacementRParen,
4113                         SourceRange TypeIdParens, Declarator &D,
4114                         Expr *Initializer);
4115  ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4116                         SourceLocation PlacementLParen,
4117                         MultiExprArg PlacementArgs,
4118                         SourceLocation PlacementRParen,
4119                         SourceRange TypeIdParens,
4120                         QualType AllocType,
4121                         TypeSourceInfo *AllocTypeInfo,
4122                         Expr *ArraySize,
4123                         SourceRange DirectInitRange,
4124                         Expr *Initializer,
4125                         bool TypeMayContainAuto = true);
4126
4127  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4128                          SourceRange R);
4129  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4130                               bool UseGlobal, QualType AllocType, bool IsArray,
4131                               MultiExprArg PlaceArgs,
4132                               FunctionDecl *&OperatorNew,
4133                               FunctionDecl *&OperatorDelete);
4134  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4135                              DeclarationName Name, MultiExprArg Args,
4136                              DeclContext *Ctx,
4137                              bool AllowMissing, FunctionDecl *&Operator,
4138                              bool Diagnose = true);
4139  void DeclareGlobalNewDelete();
4140  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4141                                       QualType Param1,
4142                                       QualType Param2 = QualType(),
4143                                       bool addMallocAttr = false);
4144
4145  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4146                                DeclarationName Name, FunctionDecl* &Operator,
4147                                bool Diagnose = true);
4148  FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4149                                              bool CanProvideSize,
4150                                              DeclarationName Name);
4151
4152  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4153  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4154                            bool UseGlobal, bool ArrayForm,
4155                            Expr *Operand);
4156
4157  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4158  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4159                                    SourceLocation StmtLoc,
4160                                    bool ConvertToBoolean);
4161
4162  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4163                               Expr *Operand, SourceLocation RParen);
4164  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4165                                  SourceLocation RParen);
4166
4167  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
4168  /// pseudo-functions.
4169  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
4170                                 SourceLocation KWLoc,
4171                                 ParsedType Ty,
4172                                 SourceLocation RParen);
4173
4174  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
4175                                 SourceLocation KWLoc,
4176                                 TypeSourceInfo *T,
4177                                 SourceLocation RParen);
4178
4179  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
4180  /// pseudo-functions.
4181  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
4182                                  SourceLocation KWLoc,
4183                                  ParsedType LhsTy,
4184                                  ParsedType RhsTy,
4185                                  SourceLocation RParen);
4186
4187  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
4188                                  SourceLocation KWLoc,
4189                                  TypeSourceInfo *LhsT,
4190                                  TypeSourceInfo *RhsT,
4191                                  SourceLocation RParen);
4192
4193  /// \brief Parsed one of the type trait support pseudo-functions.
4194  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4195                            ArrayRef<ParsedType> Args,
4196                            SourceLocation RParenLoc);
4197  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4198                            ArrayRef<TypeSourceInfo *> Args,
4199                            SourceLocation RParenLoc);
4200
4201  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4202  /// pseudo-functions.
4203  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4204                                 SourceLocation KWLoc,
4205                                 ParsedType LhsTy,
4206                                 Expr *DimExpr,
4207                                 SourceLocation RParen);
4208
4209  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4210                                 SourceLocation KWLoc,
4211                                 TypeSourceInfo *TSInfo,
4212                                 Expr *DimExpr,
4213                                 SourceLocation RParen);
4214
4215  /// ActOnExpressionTrait - Parsed one of the unary type trait support
4216  /// pseudo-functions.
4217  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4218                                  SourceLocation KWLoc,
4219                                  Expr *Queried,
4220                                  SourceLocation RParen);
4221
4222  ExprResult BuildExpressionTrait(ExpressionTrait OET,
4223                                  SourceLocation KWLoc,
4224                                  Expr *Queried,
4225                                  SourceLocation RParen);
4226
4227  ExprResult ActOnStartCXXMemberReference(Scope *S,
4228                                          Expr *Base,
4229                                          SourceLocation OpLoc,
4230                                          tok::TokenKind OpKind,
4231                                          ParsedType &ObjectType,
4232                                          bool &MayBePseudoDestructor);
4233
4234  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4235
4236  ExprResult BuildPseudoDestructorExpr(Expr *Base,
4237                                       SourceLocation OpLoc,
4238                                       tok::TokenKind OpKind,
4239                                       const CXXScopeSpec &SS,
4240                                       TypeSourceInfo *ScopeType,
4241                                       SourceLocation CCLoc,
4242                                       SourceLocation TildeLoc,
4243                                     PseudoDestructorTypeStorage DestroyedType,
4244                                       bool HasTrailingLParen);
4245
4246  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4247                                       SourceLocation OpLoc,
4248                                       tok::TokenKind OpKind,
4249                                       CXXScopeSpec &SS,
4250                                       UnqualifiedId &FirstTypeName,
4251                                       SourceLocation CCLoc,
4252                                       SourceLocation TildeLoc,
4253                                       UnqualifiedId &SecondTypeName,
4254                                       bool HasTrailingLParen);
4255
4256  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4257                                       SourceLocation OpLoc,
4258                                       tok::TokenKind OpKind,
4259                                       SourceLocation TildeLoc,
4260                                       const DeclSpec& DS,
4261                                       bool HasTrailingLParen);
4262
4263  /// MaybeCreateExprWithCleanups - If the current full-expression
4264  /// requires any cleanups, surround it with a ExprWithCleanups node.
4265  /// Otherwise, just returns the passed-in expression.
4266  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4267  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4268  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4269
4270  ExprResult ActOnFinishFullExpr(Expr *Expr) {
4271    return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4272                                          : SourceLocation());
4273  }
4274  ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4275                                 bool DiscardedValue = false,
4276                                 bool IsConstexpr = false);
4277  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4278
4279  // Marks SS invalid if it represents an incomplete type.
4280  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4281
4282  DeclContext *computeDeclContext(QualType T);
4283  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4284                                  bool EnteringContext = false);
4285  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4286  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4287
4288  /// \brief The parser has parsed a global nested-name-specifier '::'.
4289  ///
4290  /// \param S The scope in which this nested-name-specifier occurs.
4291  ///
4292  /// \param CCLoc The location of the '::'.
4293  ///
4294  /// \param SS The nested-name-specifier, which will be updated in-place
4295  /// to reflect the parsed nested-name-specifier.
4296  ///
4297  /// \returns true if an error occurred, false otherwise.
4298  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4299                                    CXXScopeSpec &SS);
4300
4301  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4302  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4303
4304  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4305                                    SourceLocation IdLoc,
4306                                    IdentifierInfo &II,
4307                                    ParsedType ObjectType);
4308
4309  bool BuildCXXNestedNameSpecifier(Scope *S,
4310                                   IdentifierInfo &Identifier,
4311                                   SourceLocation IdentifierLoc,
4312                                   SourceLocation CCLoc,
4313                                   QualType ObjectType,
4314                                   bool EnteringContext,
4315                                   CXXScopeSpec &SS,
4316                                   NamedDecl *ScopeLookupResult,
4317                                   bool ErrorRecoveryLookup);
4318
4319  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4320  ///
4321  /// \param S The scope in which this nested-name-specifier occurs.
4322  ///
4323  /// \param Identifier The identifier preceding the '::'.
4324  ///
4325  /// \param IdentifierLoc The location of the identifier.
4326  ///
4327  /// \param CCLoc The location of the '::'.
4328  ///
4329  /// \param ObjectType The type of the object, if we're parsing
4330  /// nested-name-specifier in a member access expression.
4331  ///
4332  /// \param EnteringContext Whether we're entering the context nominated by
4333  /// this nested-name-specifier.
4334  ///
4335  /// \param SS The nested-name-specifier, which is both an input
4336  /// parameter (the nested-name-specifier before this type) and an
4337  /// output parameter (containing the full nested-name-specifier,
4338  /// including this new type).
4339  ///
4340  /// \returns true if an error occurred, false otherwise.
4341  bool ActOnCXXNestedNameSpecifier(Scope *S,
4342                                   IdentifierInfo &Identifier,
4343                                   SourceLocation IdentifierLoc,
4344                                   SourceLocation CCLoc,
4345                                   ParsedType ObjectType,
4346                                   bool EnteringContext,
4347                                   CXXScopeSpec &SS);
4348
4349  ExprResult ActOnDecltypeExpression(Expr *E);
4350
4351  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4352                                           const DeclSpec &DS,
4353                                           SourceLocation ColonColonLoc);
4354
4355  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4356                                 IdentifierInfo &Identifier,
4357                                 SourceLocation IdentifierLoc,
4358                                 SourceLocation ColonLoc,
4359                                 ParsedType ObjectType,
4360                                 bool EnteringContext);
4361
4362  /// \brief The parser has parsed a nested-name-specifier
4363  /// 'template[opt] template-name < template-args >::'.
4364  ///
4365  /// \param S The scope in which this nested-name-specifier occurs.
4366  ///
4367  /// \param SS The nested-name-specifier, which is both an input
4368  /// parameter (the nested-name-specifier before this type) and an
4369  /// output parameter (containing the full nested-name-specifier,
4370  /// including this new type).
4371  ///
4372  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4373  /// \param TemplateName the template name.
4374  /// \param TemplateNameLoc The location of the template name.
4375  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4376  /// \param TemplateArgs The template arguments.
4377  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4378  /// \param CCLoc The location of the '::'.
4379  ///
4380  /// \param EnteringContext Whether we're entering the context of the
4381  /// nested-name-specifier.
4382  ///
4383  ///
4384  /// \returns true if an error occurred, false otherwise.
4385  bool ActOnCXXNestedNameSpecifier(Scope *S,
4386                                   CXXScopeSpec &SS,
4387                                   SourceLocation TemplateKWLoc,
4388                                   TemplateTy TemplateName,
4389                                   SourceLocation TemplateNameLoc,
4390                                   SourceLocation LAngleLoc,
4391                                   ASTTemplateArgsPtr TemplateArgs,
4392                                   SourceLocation RAngleLoc,
4393                                   SourceLocation CCLoc,
4394                                   bool EnteringContext);
4395
4396  /// \brief Given a C++ nested-name-specifier, produce an annotation value
4397  /// that the parser can use later to reconstruct the given
4398  /// nested-name-specifier.
4399  ///
4400  /// \param SS A nested-name-specifier.
4401  ///
4402  /// \returns A pointer containing all of the information in the
4403  /// nested-name-specifier \p SS.
4404  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4405
4406  /// \brief Given an annotation pointer for a nested-name-specifier, restore
4407  /// the nested-name-specifier structure.
4408  ///
4409  /// \param Annotation The annotation pointer, produced by
4410  /// \c SaveNestedNameSpecifierAnnotation().
4411  ///
4412  /// \param AnnotationRange The source range corresponding to the annotation.
4413  ///
4414  /// \param SS The nested-name-specifier that will be updated with the contents
4415  /// of the annotation pointer.
4416  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4417                                            SourceRange AnnotationRange,
4418                                            CXXScopeSpec &SS);
4419
4420  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4421
4422  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4423  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4424  /// After this method is called, according to [C++ 3.4.3p3], names should be
4425  /// looked up in the declarator-id's scope, until the declarator is parsed and
4426  /// ActOnCXXExitDeclaratorScope is called.
4427  /// The 'SS' should be a non-empty valid CXXScopeSpec.
4428  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4429
4430  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4431  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4432  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4433  /// Used to indicate that names should revert to being looked up in the
4434  /// defining scope.
4435  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4436
4437  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4438  /// initializer for the declaration 'Dcl'.
4439  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4440  /// static data member of class X, names should be looked up in the scope of
4441  /// class X.
4442  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4443
4444  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4445  /// initializer for the declaration 'Dcl'.
4446  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4447
4448  /// \brief Create a new lambda closure type.
4449  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4450                                         TypeSourceInfo *Info,
4451                                         bool KnownDependent);
4452
4453  /// \brief Start the definition of a lambda expression.
4454  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4455                                       SourceRange IntroducerRange,
4456                                       TypeSourceInfo *MethodType,
4457                                       SourceLocation EndLoc,
4458                                       ArrayRef<ParmVarDecl *> Params);
4459
4460  /// \brief Endow the lambda scope info with the relevant properties.
4461  void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4462                        CXXMethodDecl *CallOperator,
4463                        SourceRange IntroducerRange,
4464                        LambdaCaptureDefault CaptureDefault,
4465                        SourceLocation CaptureDefaultLoc,
4466                        bool ExplicitParams,
4467                        bool ExplicitResultType,
4468                        bool Mutable);
4469
4470  /// \brief Check an init-capture and build the implied variable declaration
4471  /// with the specified name and initializer.
4472  VarDecl *checkInitCapture(SourceLocation Loc, bool ByRef,
4473                            IdentifierInfo *Id, Expr *Init);
4474
4475  /// \brief Build the implicit field for an init-capture.
4476  FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4477
4478  /// \brief Note that we have finished the explicit captures for the
4479  /// given lambda.
4480  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4481
4482  /// \brief Introduce the lambda parameters into scope.
4483  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4484
4485  /// \brief Deduce a block or lambda's return type based on the return
4486  /// statements present in the body.
4487  void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4488
4489  /// ActOnStartOfLambdaDefinition - This is called just before we start
4490  /// parsing the body of a lambda; it analyzes the explicit captures and
4491  /// arguments, and sets up various data-structures for the body of the
4492  /// lambda.
4493  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4494                                    Declarator &ParamInfo, Scope *CurScope);
4495
4496  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4497  /// is invoked to pop the information about the lambda.
4498  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4499                        bool IsInstantiation = false);
4500
4501  /// ActOnLambdaExpr - This is called when the body of a lambda expression
4502  /// was successfully completed.
4503  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4504                             Scope *CurScope,
4505                             bool IsInstantiation = false);
4506
4507  /// \brief Define the "body" of the conversion from a lambda object to a
4508  /// function pointer.
4509  ///
4510  /// This routine doesn't actually define a sensible body; rather, it fills
4511  /// in the initialization expression needed to copy the lambda object into
4512  /// the block, and IR generation actually generates the real body of the
4513  /// block pointer conversion.
4514  void DefineImplicitLambdaToFunctionPointerConversion(
4515         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4516
4517  /// \brief Define the "body" of the conversion from a lambda object to a
4518  /// block pointer.
4519  ///
4520  /// This routine doesn't actually define a sensible body; rather, it fills
4521  /// in the initialization expression needed to copy the lambda object into
4522  /// the block, and IR generation actually generates the real body of the
4523  /// block pointer conversion.
4524  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4525                                                    CXXConversionDecl *Conv);
4526
4527  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4528                                           SourceLocation ConvLocation,
4529                                           CXXConversionDecl *Conv,
4530                                           Expr *Src);
4531
4532  // ParseObjCStringLiteral - Parse Objective-C string literals.
4533  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4534                                    Expr **Strings,
4535                                    unsigned NumStrings);
4536
4537  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4538
4539  /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4540  /// numeric literal expression. Type of the expression will be "NSNumber *"
4541  /// or "id" if NSNumber is unavailable.
4542  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4543  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4544                                  bool Value);
4545  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4546
4547  /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4548  /// '@' prefixed parenthesized expression. The type of the expression will
4549  /// either be "NSNumber *" or "NSString *" depending on the type of
4550  /// ValueType, which is allowed to be a built-in numeric type or
4551  /// "char *" or "const char *".
4552  ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4553
4554  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4555                                          Expr *IndexExpr,
4556                                          ObjCMethodDecl *getterMethod,
4557                                          ObjCMethodDecl *setterMethod);
4558
4559  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4560                                        ObjCDictionaryElement *Elements,
4561                                        unsigned NumElements);
4562
4563  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4564                                  TypeSourceInfo *EncodedTypeInfo,
4565                                  SourceLocation RParenLoc);
4566  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4567                                    CXXConversionDecl *Method,
4568                                    bool HadMultipleCandidates);
4569
4570  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4571                                       SourceLocation EncodeLoc,
4572                                       SourceLocation LParenLoc,
4573                                       ParsedType Ty,
4574                                       SourceLocation RParenLoc);
4575
4576  /// ParseObjCSelectorExpression - Build selector expression for \@selector
4577  ExprResult ParseObjCSelectorExpression(Selector Sel,
4578                                         SourceLocation AtLoc,
4579                                         SourceLocation SelLoc,
4580                                         SourceLocation LParenLoc,
4581                                         SourceLocation RParenLoc);
4582
4583  /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4584  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4585                                         SourceLocation AtLoc,
4586                                         SourceLocation ProtoLoc,
4587                                         SourceLocation LParenLoc,
4588                                         SourceLocation ProtoIdLoc,
4589                                         SourceLocation RParenLoc);
4590
4591  //===--------------------------------------------------------------------===//
4592  // C++ Declarations
4593  //
4594  Decl *ActOnStartLinkageSpecification(Scope *S,
4595                                       SourceLocation ExternLoc,
4596                                       SourceLocation LangLoc,
4597                                       StringRef Lang,
4598                                       SourceLocation LBraceLoc);
4599  Decl *ActOnFinishLinkageSpecification(Scope *S,
4600                                        Decl *LinkageSpec,
4601                                        SourceLocation RBraceLoc);
4602
4603
4604  //===--------------------------------------------------------------------===//
4605  // C++ Classes
4606  //
4607  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4608                          const CXXScopeSpec *SS = 0);
4609
4610  bool ActOnAccessSpecifier(AccessSpecifier Access,
4611                            SourceLocation ASLoc,
4612                            SourceLocation ColonLoc,
4613                            AttributeList *Attrs = 0);
4614
4615  NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4616                                 Declarator &D,
4617                                 MultiTemplateParamsArg TemplateParameterLists,
4618                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4619                                 InClassInitStyle InitStyle);
4620  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4621                                        Expr *Init);
4622
4623  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4624                                    Scope *S,
4625                                    CXXScopeSpec &SS,
4626                                    IdentifierInfo *MemberOrBase,
4627                                    ParsedType TemplateTypeTy,
4628                                    const DeclSpec &DS,
4629                                    SourceLocation IdLoc,
4630                                    SourceLocation LParenLoc,
4631                                    ArrayRef<Expr *> Args,
4632                                    SourceLocation RParenLoc,
4633                                    SourceLocation EllipsisLoc);
4634
4635  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4636                                    Scope *S,
4637                                    CXXScopeSpec &SS,
4638                                    IdentifierInfo *MemberOrBase,
4639                                    ParsedType TemplateTypeTy,
4640                                    const DeclSpec &DS,
4641                                    SourceLocation IdLoc,
4642                                    Expr *InitList,
4643                                    SourceLocation EllipsisLoc);
4644
4645  MemInitResult BuildMemInitializer(Decl *ConstructorD,
4646                                    Scope *S,
4647                                    CXXScopeSpec &SS,
4648                                    IdentifierInfo *MemberOrBase,
4649                                    ParsedType TemplateTypeTy,
4650                                    const DeclSpec &DS,
4651                                    SourceLocation IdLoc,
4652                                    Expr *Init,
4653                                    SourceLocation EllipsisLoc);
4654
4655  MemInitResult BuildMemberInitializer(ValueDecl *Member,
4656                                       Expr *Init,
4657                                       SourceLocation IdLoc);
4658
4659  MemInitResult BuildBaseInitializer(QualType BaseType,
4660                                     TypeSourceInfo *BaseTInfo,
4661                                     Expr *Init,
4662                                     CXXRecordDecl *ClassDecl,
4663                                     SourceLocation EllipsisLoc);
4664
4665  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4666                                           Expr *Init,
4667                                           CXXRecordDecl *ClassDecl);
4668
4669  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4670                                CXXCtorInitializer *Initializer);
4671
4672  bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4673                           ArrayRef<CXXCtorInitializer *> Initializers = None);
4674
4675  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4676
4677
4678  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4679  /// mark all the non-trivial destructors of its members and bases as
4680  /// referenced.
4681  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4682                                              CXXRecordDecl *Record);
4683
4684  /// \brief The list of classes whose vtables have been used within
4685  /// this translation unit, and the source locations at which the
4686  /// first use occurred.
4687  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4688
4689  /// \brief The list of vtables that are required but have not yet been
4690  /// materialized.
4691  SmallVector<VTableUse, 16> VTableUses;
4692
4693  /// \brief The set of classes whose vtables have been used within
4694  /// this translation unit, and a bit that will be true if the vtable is
4695  /// required to be emitted (otherwise, it should be emitted only if needed
4696  /// by code generation).
4697  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4698
4699  /// \brief Load any externally-stored vtable uses.
4700  void LoadExternalVTableUses();
4701
4702  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4703                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4704    DynamicClassesType;
4705
4706  /// \brief A list of all of the dynamic classes in this translation
4707  /// unit.
4708  DynamicClassesType DynamicClasses;
4709
4710  /// \brief Note that the vtable for the given class was used at the
4711  /// given location.
4712  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4713                      bool DefinitionRequired = false);
4714
4715  /// \brief Mark the exception specifications of all virtual member functions
4716  /// in the given class as needed.
4717  void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4718                                             const CXXRecordDecl *RD);
4719
4720  /// MarkVirtualMembersReferenced - Will mark all members of the given
4721  /// CXXRecordDecl referenced.
4722  void MarkVirtualMembersReferenced(SourceLocation Loc,
4723                                    const CXXRecordDecl *RD);
4724
4725  /// \brief Define all of the vtables that have been used in this
4726  /// translation unit and reference any virtual members used by those
4727  /// vtables.
4728  ///
4729  /// \returns true if any work was done, false otherwise.
4730  bool DefineUsedVTables();
4731
4732  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4733
4734  void ActOnMemInitializers(Decl *ConstructorDecl,
4735                            SourceLocation ColonLoc,
4736                            ArrayRef<CXXCtorInitializer*> MemInits,
4737                            bool AnyErrors);
4738
4739  void CheckCompletedCXXClass(CXXRecordDecl *Record);
4740  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4741                                         Decl *TagDecl,
4742                                         SourceLocation LBrac,
4743                                         SourceLocation RBrac,
4744                                         AttributeList *AttrList);
4745  void ActOnFinishCXXMemberDecls();
4746
4747  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4748  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4749  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4750  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4751  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4752  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4753  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4754  void ActOnFinishDelayedMemberInitializers(Decl *Record);
4755  void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
4756                                CachedTokens &Toks);
4757  void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
4758  bool IsInsideALocalClassWithinATemplateFunction();
4759
4760  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4761                                     Expr *AssertExpr,
4762                                     Expr *AssertMessageExpr,
4763                                     SourceLocation RParenLoc);
4764  Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4765                                     Expr *AssertExpr,
4766                                     StringLiteral *AssertMessageExpr,
4767                                     SourceLocation RParenLoc,
4768                                     bool Failed);
4769
4770  FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4771                                  SourceLocation FriendLoc,
4772                                  TypeSourceInfo *TSInfo);
4773  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4774                            MultiTemplateParamsArg TemplateParams);
4775  NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4776                                     MultiTemplateParamsArg TemplateParams);
4777
4778  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4779                                      StorageClass& SC);
4780  void CheckConstructor(CXXConstructorDecl *Constructor);
4781  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4782                                     StorageClass& SC);
4783  bool CheckDestructor(CXXDestructorDecl *Destructor);
4784  void CheckConversionDeclarator(Declarator &D, QualType &R,
4785                                 StorageClass& SC);
4786  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4787
4788  void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4789  void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4790                                                   const FunctionProtoType *T);
4791  void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
4792
4793  //===--------------------------------------------------------------------===//
4794  // C++ Derived Classes
4795  //
4796
4797  /// ActOnBaseSpecifier - Parsed a base specifier
4798  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4799                                       SourceRange SpecifierRange,
4800                                       bool Virtual, AccessSpecifier Access,
4801                                       TypeSourceInfo *TInfo,
4802                                       SourceLocation EllipsisLoc);
4803
4804  BaseResult ActOnBaseSpecifier(Decl *classdecl,
4805                                SourceRange SpecifierRange,
4806                                ParsedAttributes &Attrs,
4807                                bool Virtual, AccessSpecifier Access,
4808                                ParsedType basetype,
4809                                SourceLocation BaseLoc,
4810                                SourceLocation EllipsisLoc);
4811
4812  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4813                            unsigned NumBases);
4814  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4815                           unsigned NumBases);
4816
4817  bool IsDerivedFrom(QualType Derived, QualType Base);
4818  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4819
4820  // FIXME: I don't like this name.
4821  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4822
4823  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4824
4825  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4826                                    SourceLocation Loc, SourceRange Range,
4827                                    CXXCastPath *BasePath = 0,
4828                                    bool IgnoreAccess = false);
4829  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4830                                    unsigned InaccessibleBaseID,
4831                                    unsigned AmbigiousBaseConvID,
4832                                    SourceLocation Loc, SourceRange Range,
4833                                    DeclarationName Name,
4834                                    CXXCastPath *BasePath);
4835
4836  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4837
4838  bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4839                                         const CXXMethodDecl *Old);
4840
4841  /// CheckOverridingFunctionReturnType - Checks whether the return types are
4842  /// covariant, according to C++ [class.virtual]p5.
4843  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4844                                         const CXXMethodDecl *Old);
4845
4846  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4847  /// spec is a subset of base spec.
4848  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4849                                            const CXXMethodDecl *Old);
4850
4851  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4852
4853  /// CheckOverrideControl - Check C++11 override control semantics.
4854  void CheckOverrideControl(NamedDecl *D);
4855
4856  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4857  /// overrides a virtual member function marked 'final', according to
4858  /// C++11 [class.virtual]p4.
4859  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4860                                              const CXXMethodDecl *Old);
4861
4862
4863  //===--------------------------------------------------------------------===//
4864  // C++ Access Control
4865  //
4866
4867  enum AccessResult {
4868    AR_accessible,
4869    AR_inaccessible,
4870    AR_dependent,
4871    AR_delayed
4872  };
4873
4874  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4875                                NamedDecl *PrevMemberDecl,
4876                                AccessSpecifier LexicalAS);
4877
4878  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4879                                           DeclAccessPair FoundDecl);
4880  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4881                                           DeclAccessPair FoundDecl);
4882  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4883                                     SourceRange PlacementRange,
4884                                     CXXRecordDecl *NamingClass,
4885                                     DeclAccessPair FoundDecl,
4886                                     bool Diagnose = true);
4887  AccessResult CheckConstructorAccess(SourceLocation Loc,
4888                                      CXXConstructorDecl *D,
4889                                      const InitializedEntity &Entity,
4890                                      AccessSpecifier Access,
4891                                      bool IsCopyBindingRefToTemp = false);
4892  AccessResult CheckConstructorAccess(SourceLocation Loc,
4893                                      CXXConstructorDecl *D,
4894                                      const InitializedEntity &Entity,
4895                                      AccessSpecifier Access,
4896                                      const PartialDiagnostic &PDiag);
4897  AccessResult CheckDestructorAccess(SourceLocation Loc,
4898                                     CXXDestructorDecl *Dtor,
4899                                     const PartialDiagnostic &PDiag,
4900                                     QualType objectType = QualType());
4901  AccessResult CheckFriendAccess(NamedDecl *D);
4902  AccessResult CheckMemberAccess(SourceLocation UseLoc,
4903                                 CXXRecordDecl *NamingClass,
4904                                 DeclAccessPair Found);
4905  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4906                                         Expr *ObjectExpr,
4907                                         Expr *ArgExpr,
4908                                         DeclAccessPair FoundDecl);
4909  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4910                                          DeclAccessPair FoundDecl);
4911  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4912                                    QualType Base, QualType Derived,
4913                                    const CXXBasePath &Path,
4914                                    unsigned DiagID,
4915                                    bool ForceCheck = false,
4916                                    bool ForceUnprivileged = false);
4917  void CheckLookupAccess(const LookupResult &R);
4918  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4919  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4920                                            AccessSpecifier access,
4921                                            QualType objectType);
4922
4923  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4924                         const MultiLevelTemplateArgumentList &TemplateArgs);
4925  void PerformDependentDiagnostics(const DeclContext *Pattern,
4926                        const MultiLevelTemplateArgumentList &TemplateArgs);
4927
4928  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4929
4930  /// \brief When true, access checking violations are treated as SFINAE
4931  /// failures rather than hard errors.
4932  bool AccessCheckingSFINAE;
4933
4934  enum AbstractDiagSelID {
4935    AbstractNone = -1,
4936    AbstractReturnType,
4937    AbstractParamType,
4938    AbstractVariableType,
4939    AbstractFieldType,
4940    AbstractIvarType,
4941    AbstractSynthesizedIvarType,
4942    AbstractArrayType
4943  };
4944
4945  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4946                              TypeDiagnoser &Diagnoser);
4947  template<typename T1>
4948  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4949                              unsigned DiagID,
4950                              const T1 &Arg1) {
4951    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
4952    return RequireNonAbstractType(Loc, T, Diagnoser);
4953  }
4954
4955  template<typename T1, typename T2>
4956  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4957                              unsigned DiagID,
4958                              const T1 &Arg1, const T2 &Arg2) {
4959    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
4960    return RequireNonAbstractType(Loc, T, Diagnoser);
4961  }
4962
4963  template<typename T1, typename T2, typename T3>
4964  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4965                              unsigned DiagID,
4966                              const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
4967    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
4968    return RequireNonAbstractType(Loc, T, Diagnoser);
4969  }
4970
4971  void DiagnoseAbstractType(const CXXRecordDecl *RD);
4972
4973  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4974                              AbstractDiagSelID SelID = AbstractNone);
4975
4976  //===--------------------------------------------------------------------===//
4977  // C++ Overloaded Operators [C++ 13.5]
4978  //
4979
4980  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4981
4982  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4983
4984  //===--------------------------------------------------------------------===//
4985  // C++ Templates [C++ 14]
4986  //
4987  void FilterAcceptableTemplateNames(LookupResult &R,
4988                                     bool AllowFunctionTemplates = true);
4989  bool hasAnyAcceptableTemplateNames(LookupResult &R,
4990                                     bool AllowFunctionTemplates = true);
4991
4992  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4993                          QualType ObjectType, bool EnteringContext,
4994                          bool &MemberOfUnknownSpecialization);
4995
4996  TemplateNameKind isTemplateName(Scope *S,
4997                                  CXXScopeSpec &SS,
4998                                  bool hasTemplateKeyword,
4999                                  UnqualifiedId &Name,
5000                                  ParsedType ObjectType,
5001                                  bool EnteringContext,
5002                                  TemplateTy &Template,
5003                                  bool &MemberOfUnknownSpecialization);
5004
5005  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5006                                   SourceLocation IILoc,
5007                                   Scope *S,
5008                                   const CXXScopeSpec *SS,
5009                                   TemplateTy &SuggestedTemplate,
5010                                   TemplateNameKind &SuggestedKind);
5011
5012  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5013  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5014
5015  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
5016                           SourceLocation EllipsisLoc,
5017                           SourceLocation KeyLoc,
5018                           IdentifierInfo *ParamName,
5019                           SourceLocation ParamNameLoc,
5020                           unsigned Depth, unsigned Position,
5021                           SourceLocation EqualLoc,
5022                           ParsedType DefaultArg);
5023
5024  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5025  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5026                                      unsigned Depth,
5027                                      unsigned Position,
5028                                      SourceLocation EqualLoc,
5029                                      Expr *DefaultArg);
5030  Decl *ActOnTemplateTemplateParameter(Scope *S,
5031                                       SourceLocation TmpLoc,
5032                                       TemplateParameterList *Params,
5033                                       SourceLocation EllipsisLoc,
5034                                       IdentifierInfo *ParamName,
5035                                       SourceLocation ParamNameLoc,
5036                                       unsigned Depth,
5037                                       unsigned Position,
5038                                       SourceLocation EqualLoc,
5039                                       ParsedTemplateArgument DefaultArg);
5040
5041  TemplateParameterList *
5042  ActOnTemplateParameterList(unsigned Depth,
5043                             SourceLocation ExportLoc,
5044                             SourceLocation TemplateLoc,
5045                             SourceLocation LAngleLoc,
5046                             Decl **Params, unsigned NumParams,
5047                             SourceLocation RAngleLoc);
5048
5049  /// \brief The context in which we are checking a template parameter list.
5050  enum TemplateParamListContext {
5051    TPC_ClassTemplate,
5052    TPC_VarTemplate,
5053    TPC_FunctionTemplate,
5054    TPC_ClassTemplateMember,
5055    TPC_FriendClassTemplate,
5056    TPC_FriendFunctionTemplate,
5057    TPC_FriendFunctionTemplateDefinition,
5058    TPC_TypeAliasTemplate
5059  };
5060
5061  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5062                                  TemplateParameterList *OldParams,
5063                                  TemplateParamListContext TPC);
5064  TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5065      SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5066      const CXXScopeSpec &SS, ArrayRef<TemplateParameterList *> ParamLists,
5067      bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5068
5069  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5070                                SourceLocation KWLoc, CXXScopeSpec &SS,
5071                                IdentifierInfo *Name, SourceLocation NameLoc,
5072                                AttributeList *Attr,
5073                                TemplateParameterList *TemplateParams,
5074                                AccessSpecifier AS,
5075                                SourceLocation ModulePrivateLoc,
5076                                unsigned NumOuterTemplateParamLists,
5077                            TemplateParameterList **OuterTemplateParamLists);
5078
5079  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5080                                  TemplateArgumentListInfo &Out);
5081
5082  void NoteAllFoundTemplates(TemplateName Name);
5083
5084  QualType CheckTemplateIdType(TemplateName Template,
5085                               SourceLocation TemplateLoc,
5086                              TemplateArgumentListInfo &TemplateArgs);
5087
5088  TypeResult
5089  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5090                      TemplateTy Template, SourceLocation TemplateLoc,
5091                      SourceLocation LAngleLoc,
5092                      ASTTemplateArgsPtr TemplateArgs,
5093                      SourceLocation RAngleLoc,
5094                      bool IsCtorOrDtorName = false);
5095
5096  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5097  /// such as \c class T::template apply<U>.
5098  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5099                                    TypeSpecifierType TagSpec,
5100                                    SourceLocation TagLoc,
5101                                    CXXScopeSpec &SS,
5102                                    SourceLocation TemplateKWLoc,
5103                                    TemplateTy TemplateD,
5104                                    SourceLocation TemplateLoc,
5105                                    SourceLocation LAngleLoc,
5106                                    ASTTemplateArgsPtr TemplateArgsIn,
5107                                    SourceLocation RAngleLoc);
5108
5109  DeclResult ActOnVarTemplateSpecialization(
5110      Scope *S, VarTemplateDecl *VarTemplate, Declarator &D, TypeSourceInfo *DI,
5111      SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5112      StorageClass SC, bool IsPartialSpecialization);
5113
5114  DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5115                                SourceLocation TemplateLoc,
5116                                SourceLocation TemplateNameLoc,
5117                                const TemplateArgumentListInfo &TemplateArgs);
5118
5119  ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5120                                const DeclarationNameInfo &NameInfo,
5121                                VarTemplateDecl *Template,
5122                                SourceLocation TemplateLoc,
5123                                const TemplateArgumentListInfo *TemplateArgs);
5124
5125  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5126                                 SourceLocation TemplateKWLoc,
5127                                 LookupResult &R,
5128                                 bool RequiresADL,
5129                               const TemplateArgumentListInfo *TemplateArgs);
5130
5131  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5132                                          SourceLocation TemplateKWLoc,
5133                               const DeclarationNameInfo &NameInfo,
5134                               const TemplateArgumentListInfo *TemplateArgs);
5135
5136  TemplateNameKind ActOnDependentTemplateName(Scope *S,
5137                                              CXXScopeSpec &SS,
5138                                              SourceLocation TemplateKWLoc,
5139                                              UnqualifiedId &Name,
5140                                              ParsedType ObjectType,
5141                                              bool EnteringContext,
5142                                              TemplateTy &Template);
5143
5144  DeclResult
5145  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5146                                   SourceLocation KWLoc,
5147                                   SourceLocation ModulePrivateLoc,
5148                                   CXXScopeSpec &SS,
5149                                   TemplateTy Template,
5150                                   SourceLocation TemplateNameLoc,
5151                                   SourceLocation LAngleLoc,
5152                                   ASTTemplateArgsPtr TemplateArgs,
5153                                   SourceLocation RAngleLoc,
5154                                   AttributeList *Attr,
5155                                 MultiTemplateParamsArg TemplateParameterLists);
5156
5157  Decl *ActOnTemplateDeclarator(Scope *S,
5158                                MultiTemplateParamsArg TemplateParameterLists,
5159                                Declarator &D);
5160
5161  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5162                                  MultiTemplateParamsArg TemplateParameterLists,
5163                                        Declarator &D);
5164
5165  bool
5166  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5167                                         TemplateSpecializationKind NewTSK,
5168                                         NamedDecl *PrevDecl,
5169                                         TemplateSpecializationKind PrevTSK,
5170                                         SourceLocation PrevPtOfInstantiation,
5171                                         bool &SuppressNew);
5172
5173  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5174                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
5175                                                    LookupResult &Previous);
5176
5177  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5178                         TemplateArgumentListInfo *ExplicitTemplateArgs,
5179                                           LookupResult &Previous);
5180  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5181
5182  DeclResult
5183  ActOnExplicitInstantiation(Scope *S,
5184                             SourceLocation ExternLoc,
5185                             SourceLocation TemplateLoc,
5186                             unsigned TagSpec,
5187                             SourceLocation KWLoc,
5188                             const CXXScopeSpec &SS,
5189                             TemplateTy Template,
5190                             SourceLocation TemplateNameLoc,
5191                             SourceLocation LAngleLoc,
5192                             ASTTemplateArgsPtr TemplateArgs,
5193                             SourceLocation RAngleLoc,
5194                             AttributeList *Attr);
5195
5196  DeclResult
5197  ActOnExplicitInstantiation(Scope *S,
5198                             SourceLocation ExternLoc,
5199                             SourceLocation TemplateLoc,
5200                             unsigned TagSpec,
5201                             SourceLocation KWLoc,
5202                             CXXScopeSpec &SS,
5203                             IdentifierInfo *Name,
5204                             SourceLocation NameLoc,
5205                             AttributeList *Attr);
5206
5207  DeclResult ActOnExplicitInstantiation(Scope *S,
5208                                        SourceLocation ExternLoc,
5209                                        SourceLocation TemplateLoc,
5210                                        Declarator &D);
5211
5212  TemplateArgumentLoc
5213  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5214                                          SourceLocation TemplateLoc,
5215                                          SourceLocation RAngleLoc,
5216                                          Decl *Param,
5217                                          SmallVectorImpl<TemplateArgument>
5218                                            &Converted,
5219                                          bool &HasDefaultArg);
5220
5221  /// \brief Specifies the context in which a particular template
5222  /// argument is being checked.
5223  enum CheckTemplateArgumentKind {
5224    /// \brief The template argument was specified in the code or was
5225    /// instantiated with some deduced template arguments.
5226    CTAK_Specified,
5227
5228    /// \brief The template argument was deduced via template argument
5229    /// deduction.
5230    CTAK_Deduced,
5231
5232    /// \brief The template argument was deduced from an array bound
5233    /// via template argument deduction.
5234    CTAK_DeducedFromArrayBound
5235  };
5236
5237  bool CheckTemplateArgument(NamedDecl *Param,
5238                             const TemplateArgumentLoc &Arg,
5239                             NamedDecl *Template,
5240                             SourceLocation TemplateLoc,
5241                             SourceLocation RAngleLoc,
5242                             unsigned ArgumentPackIndex,
5243                           SmallVectorImpl<TemplateArgument> &Converted,
5244                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
5245
5246  /// \brief Check that the given template arguments can be be provided to
5247  /// the given template, converting the arguments along the way.
5248  ///
5249  /// \param Template The template to which the template arguments are being
5250  /// provided.
5251  ///
5252  /// \param TemplateLoc The location of the template name in the source.
5253  ///
5254  /// \param TemplateArgs The list of template arguments. If the template is
5255  /// a template template parameter, this function may extend the set of
5256  /// template arguments to also include substituted, defaulted template
5257  /// arguments.
5258  ///
5259  /// \param PartialTemplateArgs True if the list of template arguments is
5260  /// intentionally partial, e.g., because we're checking just the initial
5261  /// set of template arguments.
5262  ///
5263  /// \param Converted Will receive the converted, canonicalized template
5264  /// arguments.
5265  ///
5266  ///
5267  /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
5268  /// when the template arguments contain a pack expansion that is being
5269  /// expanded into a fixed parameter list.
5270  ///
5271  /// \returns True if an error occurred, false otherwise.
5272  bool CheckTemplateArgumentList(TemplateDecl *Template,
5273                                 SourceLocation TemplateLoc,
5274                                 TemplateArgumentListInfo &TemplateArgs,
5275                                 bool PartialTemplateArgs,
5276                           SmallVectorImpl<TemplateArgument> &Converted,
5277                                 bool *ExpansionIntoFixedList = 0);
5278
5279  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5280                                 const TemplateArgumentLoc &Arg,
5281                           SmallVectorImpl<TemplateArgument> &Converted);
5282
5283  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5284                             TypeSourceInfo *Arg);
5285  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5286                                   QualType InstantiatedParamType, Expr *Arg,
5287                                   TemplateArgument &Converted,
5288                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
5289  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5290                             const TemplateArgumentLoc &Arg,
5291                             unsigned ArgumentPackIndex);
5292
5293  ExprResult
5294  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5295                                          QualType ParamType,
5296                                          SourceLocation Loc);
5297  ExprResult
5298  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5299                                              SourceLocation Loc);
5300
5301  /// \brief Enumeration describing how template parameter lists are compared
5302  /// for equality.
5303  enum TemplateParameterListEqualKind {
5304    /// \brief We are matching the template parameter lists of two templates
5305    /// that might be redeclarations.
5306    ///
5307    /// \code
5308    /// template<typename T> struct X;
5309    /// template<typename T> struct X;
5310    /// \endcode
5311    TPL_TemplateMatch,
5312
5313    /// \brief We are matching the template parameter lists of two template
5314    /// template parameters as part of matching the template parameter lists
5315    /// of two templates that might be redeclarations.
5316    ///
5317    /// \code
5318    /// template<template<int I> class TT> struct X;
5319    /// template<template<int Value> class Other> struct X;
5320    /// \endcode
5321    TPL_TemplateTemplateParmMatch,
5322
5323    /// \brief We are matching the template parameter lists of a template
5324    /// template argument against the template parameter lists of a template
5325    /// template parameter.
5326    ///
5327    /// \code
5328    /// template<template<int Value> class Metafun> struct X;
5329    /// template<int Value> struct integer_c;
5330    /// X<integer_c> xic;
5331    /// \endcode
5332    TPL_TemplateTemplateArgumentMatch
5333  };
5334
5335  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5336                                      TemplateParameterList *Old,
5337                                      bool Complain,
5338                                      TemplateParameterListEqualKind Kind,
5339                                      SourceLocation TemplateArgLoc
5340                                        = SourceLocation());
5341
5342  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5343
5344  /// \brief Called when the parser has parsed a C++ typename
5345  /// specifier, e.g., "typename T::type".
5346  ///
5347  /// \param S The scope in which this typename type occurs.
5348  /// \param TypenameLoc the location of the 'typename' keyword
5349  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5350  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5351  /// \param IdLoc the location of the identifier.
5352  TypeResult
5353  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5354                    const CXXScopeSpec &SS, const IdentifierInfo &II,
5355                    SourceLocation IdLoc);
5356
5357  /// \brief Called when the parser has parsed a C++ typename
5358  /// specifier that ends in a template-id, e.g.,
5359  /// "typename MetaFun::template apply<T1, T2>".
5360  ///
5361  /// \param S The scope in which this typename type occurs.
5362  /// \param TypenameLoc the location of the 'typename' keyword
5363  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5364  /// \param TemplateLoc the location of the 'template' keyword, if any.
5365  /// \param TemplateName The template name.
5366  /// \param TemplateNameLoc The location of the template name.
5367  /// \param LAngleLoc The location of the opening angle bracket  ('<').
5368  /// \param TemplateArgs The template arguments.
5369  /// \param RAngleLoc The location of the closing angle bracket  ('>').
5370  TypeResult
5371  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5372                    const CXXScopeSpec &SS,
5373                    SourceLocation TemplateLoc,
5374                    TemplateTy TemplateName,
5375                    SourceLocation TemplateNameLoc,
5376                    SourceLocation LAngleLoc,
5377                    ASTTemplateArgsPtr TemplateArgs,
5378                    SourceLocation RAngleLoc);
5379
5380  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5381                             SourceLocation KeywordLoc,
5382                             NestedNameSpecifierLoc QualifierLoc,
5383                             const IdentifierInfo &II,
5384                             SourceLocation IILoc);
5385
5386  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5387                                                    SourceLocation Loc,
5388                                                    DeclarationName Name);
5389  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5390
5391  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5392  bool RebuildTemplateParamsInCurrentInstantiation(
5393                                                TemplateParameterList *Params);
5394
5395  std::string
5396  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5397                                  const TemplateArgumentList &Args);
5398
5399  std::string
5400  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5401                                  const TemplateArgument *Args,
5402                                  unsigned NumArgs);
5403
5404  //===--------------------------------------------------------------------===//
5405  // C++ Variadic Templates (C++0x [temp.variadic])
5406  //===--------------------------------------------------------------------===//
5407
5408  /// \brief The context in which an unexpanded parameter pack is
5409  /// being diagnosed.
5410  ///
5411  /// Note that the values of this enumeration line up with the first
5412  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5413  enum UnexpandedParameterPackContext {
5414    /// \brief An arbitrary expression.
5415    UPPC_Expression = 0,
5416
5417    /// \brief The base type of a class type.
5418    UPPC_BaseType,
5419
5420    /// \brief The type of an arbitrary declaration.
5421    UPPC_DeclarationType,
5422
5423    /// \brief The type of a data member.
5424    UPPC_DataMemberType,
5425
5426    /// \brief The size of a bit-field.
5427    UPPC_BitFieldWidth,
5428
5429    /// \brief The expression in a static assertion.
5430    UPPC_StaticAssertExpression,
5431
5432    /// \brief The fixed underlying type of an enumeration.
5433    UPPC_FixedUnderlyingType,
5434
5435    /// \brief The enumerator value.
5436    UPPC_EnumeratorValue,
5437
5438    /// \brief A using declaration.
5439    UPPC_UsingDeclaration,
5440
5441    /// \brief A friend declaration.
5442    UPPC_FriendDeclaration,
5443
5444    /// \brief A declaration qualifier.
5445    UPPC_DeclarationQualifier,
5446
5447    /// \brief An initializer.
5448    UPPC_Initializer,
5449
5450    /// \brief A default argument.
5451    UPPC_DefaultArgument,
5452
5453    /// \brief The type of a non-type template parameter.
5454    UPPC_NonTypeTemplateParameterType,
5455
5456    /// \brief The type of an exception.
5457    UPPC_ExceptionType,
5458
5459    /// \brief Partial specialization.
5460    UPPC_PartialSpecialization,
5461
5462    /// \brief Microsoft __if_exists.
5463    UPPC_IfExists,
5464
5465    /// \brief Microsoft __if_not_exists.
5466    UPPC_IfNotExists,
5467
5468    /// \brief Lambda expression.
5469    UPPC_Lambda,
5470
5471    /// \brief Block expression,
5472    UPPC_Block
5473  };
5474
5475  /// \brief Diagnose unexpanded parameter packs.
5476  ///
5477  /// \param Loc The location at which we should emit the diagnostic.
5478  ///
5479  /// \param UPPC The context in which we are diagnosing unexpanded
5480  /// parameter packs.
5481  ///
5482  /// \param Unexpanded the set of unexpanded parameter packs.
5483  ///
5484  /// \returns true if an error occurred, false otherwise.
5485  bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5486                                        UnexpandedParameterPackContext UPPC,
5487                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
5488
5489  /// \brief If the given type contains an unexpanded parameter pack,
5490  /// diagnose the error.
5491  ///
5492  /// \param Loc The source location where a diagnostc should be emitted.
5493  ///
5494  /// \param T The type that is being checked for unexpanded parameter
5495  /// packs.
5496  ///
5497  /// \returns true if an error occurred, false otherwise.
5498  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5499                                       UnexpandedParameterPackContext UPPC);
5500
5501  /// \brief If the given expression contains an unexpanded parameter
5502  /// pack, diagnose the error.
5503  ///
5504  /// \param E The expression that is being checked for unexpanded
5505  /// parameter packs.
5506  ///
5507  /// \returns true if an error occurred, false otherwise.
5508  bool DiagnoseUnexpandedParameterPack(Expr *E,
5509                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
5510
5511  /// \brief If the given nested-name-specifier contains an unexpanded
5512  /// parameter pack, diagnose the error.
5513  ///
5514  /// \param SS The nested-name-specifier that is being checked for
5515  /// unexpanded parameter packs.
5516  ///
5517  /// \returns true if an error occurred, false otherwise.
5518  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5519                                       UnexpandedParameterPackContext UPPC);
5520
5521  /// \brief If the given name contains an unexpanded parameter pack,
5522  /// diagnose the error.
5523  ///
5524  /// \param NameInfo The name (with source location information) that
5525  /// is being checked for unexpanded parameter packs.
5526  ///
5527  /// \returns true if an error occurred, false otherwise.
5528  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5529                                       UnexpandedParameterPackContext UPPC);
5530
5531  /// \brief If the given template name contains an unexpanded parameter pack,
5532  /// diagnose the error.
5533  ///
5534  /// \param Loc The location of the template name.
5535  ///
5536  /// \param Template The template name that is being checked for unexpanded
5537  /// parameter packs.
5538  ///
5539  /// \returns true if an error occurred, false otherwise.
5540  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5541                                       TemplateName Template,
5542                                       UnexpandedParameterPackContext UPPC);
5543
5544  /// \brief If the given template argument contains an unexpanded parameter
5545  /// pack, diagnose the error.
5546  ///
5547  /// \param Arg The template argument that is being checked for unexpanded
5548  /// parameter packs.
5549  ///
5550  /// \returns true if an error occurred, false otherwise.
5551  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5552                                       UnexpandedParameterPackContext UPPC);
5553
5554  /// \brief Collect the set of unexpanded parameter packs within the given
5555  /// template argument.
5556  ///
5557  /// \param Arg The template argument that will be traversed to find
5558  /// unexpanded parameter packs.
5559  void collectUnexpandedParameterPacks(TemplateArgument Arg,
5560                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5561
5562  /// \brief Collect the set of unexpanded parameter packs within the given
5563  /// template argument.
5564  ///
5565  /// \param Arg The template argument that will be traversed to find
5566  /// unexpanded parameter packs.
5567  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5568                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5569
5570  /// \brief Collect the set of unexpanded parameter packs within the given
5571  /// type.
5572  ///
5573  /// \param T The type that will be traversed to find
5574  /// unexpanded parameter packs.
5575  void collectUnexpandedParameterPacks(QualType T,
5576                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5577
5578  /// \brief Collect the set of unexpanded parameter packs within the given
5579  /// type.
5580  ///
5581  /// \param TL The type that will be traversed to find
5582  /// unexpanded parameter packs.
5583  void collectUnexpandedParameterPacks(TypeLoc TL,
5584                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5585
5586  /// \brief Collect the set of unexpanded parameter packs within the given
5587  /// nested-name-specifier.
5588  ///
5589  /// \param SS The nested-name-specifier that will be traversed to find
5590  /// unexpanded parameter packs.
5591  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5592                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5593
5594  /// \brief Collect the set of unexpanded parameter packs within the given
5595  /// name.
5596  ///
5597  /// \param NameInfo The name that will be traversed to find
5598  /// unexpanded parameter packs.
5599  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5600                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5601
5602  /// \brief Invoked when parsing a template argument followed by an
5603  /// ellipsis, which creates a pack expansion.
5604  ///
5605  /// \param Arg The template argument preceding the ellipsis, which
5606  /// may already be invalid.
5607  ///
5608  /// \param EllipsisLoc The location of the ellipsis.
5609  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5610                                            SourceLocation EllipsisLoc);
5611
5612  /// \brief Invoked when parsing a type followed by an ellipsis, which
5613  /// creates a pack expansion.
5614  ///
5615  /// \param Type The type preceding the ellipsis, which will become
5616  /// the pattern of the pack expansion.
5617  ///
5618  /// \param EllipsisLoc The location of the ellipsis.
5619  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5620
5621  /// \brief Construct a pack expansion type from the pattern of the pack
5622  /// expansion.
5623  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5624                                     SourceLocation EllipsisLoc,
5625                                     Optional<unsigned> NumExpansions);
5626
5627  /// \brief Construct a pack expansion type from the pattern of the pack
5628  /// expansion.
5629  QualType CheckPackExpansion(QualType Pattern,
5630                              SourceRange PatternRange,
5631                              SourceLocation EllipsisLoc,
5632                              Optional<unsigned> NumExpansions);
5633
5634  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5635  /// creates a pack expansion.
5636  ///
5637  /// \param Pattern The expression preceding the ellipsis, which will become
5638  /// the pattern of the pack expansion.
5639  ///
5640  /// \param EllipsisLoc The location of the ellipsis.
5641  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5642
5643  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5644  /// creates a pack expansion.
5645  ///
5646  /// \param Pattern The expression preceding the ellipsis, which will become
5647  /// the pattern of the pack expansion.
5648  ///
5649  /// \param EllipsisLoc The location of the ellipsis.
5650  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5651                                Optional<unsigned> NumExpansions);
5652
5653  /// \brief Determine whether we could expand a pack expansion with the
5654  /// given set of parameter packs into separate arguments by repeatedly
5655  /// transforming the pattern.
5656  ///
5657  /// \param EllipsisLoc The location of the ellipsis that identifies the
5658  /// pack expansion.
5659  ///
5660  /// \param PatternRange The source range that covers the entire pattern of
5661  /// the pack expansion.
5662  ///
5663  /// \param Unexpanded The set of unexpanded parameter packs within the
5664  /// pattern.
5665  ///
5666  /// \param ShouldExpand Will be set to \c true if the transformer should
5667  /// expand the corresponding pack expansions into separate arguments. When
5668  /// set, \c NumExpansions must also be set.
5669  ///
5670  /// \param RetainExpansion Whether the caller should add an unexpanded
5671  /// pack expansion after all of the expanded arguments. This is used
5672  /// when extending explicitly-specified template argument packs per
5673  /// C++0x [temp.arg.explicit]p9.
5674  ///
5675  /// \param NumExpansions The number of separate arguments that will be in
5676  /// the expanded form of the corresponding pack expansion. This is both an
5677  /// input and an output parameter, which can be set by the caller if the
5678  /// number of expansions is known a priori (e.g., due to a prior substitution)
5679  /// and will be set by the callee when the number of expansions is known.
5680  /// The callee must set this value when \c ShouldExpand is \c true; it may
5681  /// set this value in other cases.
5682  ///
5683  /// \returns true if an error occurred (e.g., because the parameter packs
5684  /// are to be instantiated with arguments of different lengths), false
5685  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5686  /// must be set.
5687  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5688                                       SourceRange PatternRange,
5689                             ArrayRef<UnexpandedParameterPack> Unexpanded,
5690                             const MultiLevelTemplateArgumentList &TemplateArgs,
5691                                       bool &ShouldExpand,
5692                                       bool &RetainExpansion,
5693                                       Optional<unsigned> &NumExpansions);
5694
5695  /// \brief Determine the number of arguments in the given pack expansion
5696  /// type.
5697  ///
5698  /// This routine assumes that the number of arguments in the expansion is
5699  /// consistent across all of the unexpanded parameter packs in its pattern.
5700  ///
5701  /// Returns an empty Optional if the type can't be expanded.
5702  Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5703      const MultiLevelTemplateArgumentList &TemplateArgs);
5704
5705  /// \brief Determine whether the given declarator contains any unexpanded
5706  /// parameter packs.
5707  ///
5708  /// This routine is used by the parser to disambiguate function declarators
5709  /// with an ellipsis prior to the ')', e.g.,
5710  ///
5711  /// \code
5712  ///   void f(T...);
5713  /// \endcode
5714  ///
5715  /// To determine whether we have an (unnamed) function parameter pack or
5716  /// a variadic function.
5717  ///
5718  /// \returns true if the declarator contains any unexpanded parameter packs,
5719  /// false otherwise.
5720  bool containsUnexpandedParameterPacks(Declarator &D);
5721
5722  /// \brief Returns the pattern of the pack expansion for a template argument.
5723  ///
5724  /// \param OrigLoc The template argument to expand.
5725  ///
5726  /// \param Ellipsis Will be set to the location of the ellipsis.
5727  ///
5728  /// \param NumExpansions Will be set to the number of expansions that will
5729  /// be generated from this pack expansion, if known a priori.
5730  TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
5731      TemplateArgumentLoc OrigLoc,
5732      SourceLocation &Ellipsis,
5733      Optional<unsigned> &NumExpansions) const;
5734
5735  //===--------------------------------------------------------------------===//
5736  // C++ Template Argument Deduction (C++ [temp.deduct])
5737  //===--------------------------------------------------------------------===//
5738
5739  /// \brief Describes the result of template argument deduction.
5740  ///
5741  /// The TemplateDeductionResult enumeration describes the result of
5742  /// template argument deduction, as returned from
5743  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5744  /// structure provides additional information about the results of
5745  /// template argument deduction, e.g., the deduced template argument
5746  /// list (if successful) or the specific template parameters or
5747  /// deduced arguments that were involved in the failure.
5748  enum TemplateDeductionResult {
5749    /// \brief Template argument deduction was successful.
5750    TDK_Success = 0,
5751    /// \brief The declaration was invalid; do nothing.
5752    TDK_Invalid,
5753    /// \brief Template argument deduction exceeded the maximum template
5754    /// instantiation depth (which has already been diagnosed).
5755    TDK_InstantiationDepth,
5756    /// \brief Template argument deduction did not deduce a value
5757    /// for every template parameter.
5758    TDK_Incomplete,
5759    /// \brief Template argument deduction produced inconsistent
5760    /// deduced values for the given template parameter.
5761    TDK_Inconsistent,
5762    /// \brief Template argument deduction failed due to inconsistent
5763    /// cv-qualifiers on a template parameter type that would
5764    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5765    /// but were given a non-const "X".
5766    TDK_Underqualified,
5767    /// \brief Substitution of the deduced template argument values
5768    /// resulted in an error.
5769    TDK_SubstitutionFailure,
5770    /// \brief A non-depnedent component of the parameter did not match the
5771    /// corresponding component of the argument.
5772    TDK_NonDeducedMismatch,
5773    /// \brief When performing template argument deduction for a function
5774    /// template, there were too many call arguments.
5775    TDK_TooManyArguments,
5776    /// \brief When performing template argument deduction for a function
5777    /// template, there were too few call arguments.
5778    TDK_TooFewArguments,
5779    /// \brief The explicitly-specified template arguments were not valid
5780    /// template arguments for the given template.
5781    TDK_InvalidExplicitArguments,
5782    /// \brief The arguments included an overloaded function name that could
5783    /// not be resolved to a suitable function.
5784    TDK_FailedOverloadResolution,
5785    /// \brief Deduction failed; that's all we know.
5786    TDK_MiscellaneousDeductionFailure
5787  };
5788
5789  TemplateDeductionResult
5790  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5791                          const TemplateArgumentList &TemplateArgs,
5792                          sema::TemplateDeductionInfo &Info);
5793
5794  TemplateDeductionResult
5795  DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
5796                          const TemplateArgumentList &TemplateArgs,
5797                          sema::TemplateDeductionInfo &Info);
5798
5799  TemplateDeductionResult SubstituteExplicitTemplateArguments(
5800      FunctionTemplateDecl *FunctionTemplate,
5801      TemplateArgumentListInfo &ExplicitTemplateArgs,
5802      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5803      SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
5804      sema::TemplateDeductionInfo &Info);
5805
5806  /// brief A function argument from which we performed template argument
5807  // deduction for a call.
5808  struct OriginalCallArg {
5809    OriginalCallArg(QualType OriginalParamType,
5810                    unsigned ArgIdx,
5811                    QualType OriginalArgType)
5812      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5813        OriginalArgType(OriginalArgType) { }
5814
5815    QualType OriginalParamType;
5816    unsigned ArgIdx;
5817    QualType OriginalArgType;
5818  };
5819
5820  TemplateDeductionResult
5821  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5822                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5823                                  unsigned NumExplicitlySpecified,
5824                                  FunctionDecl *&Specialization,
5825                                  sema::TemplateDeductionInfo &Info,
5826           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5827
5828  TemplateDeductionResult
5829  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5830                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5831                          ArrayRef<Expr *> Args,
5832                          FunctionDecl *&Specialization,
5833                          sema::TemplateDeductionInfo &Info);
5834
5835  TemplateDeductionResult
5836  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5837                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5838                          QualType ArgFunctionType,
5839                          FunctionDecl *&Specialization,
5840                          sema::TemplateDeductionInfo &Info,
5841                          bool InOverloadResolution = false);
5842
5843  TemplateDeductionResult
5844  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5845                          QualType ToType,
5846                          CXXConversionDecl *&Specialization,
5847                          sema::TemplateDeductionInfo &Info);
5848
5849  TemplateDeductionResult
5850  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5851                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5852                          FunctionDecl *&Specialization,
5853                          sema::TemplateDeductionInfo &Info,
5854                          bool InOverloadResolution = false);
5855
5856  /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
5857  QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
5858  /// \brief Substitute Replacement for auto in TypeWithAuto
5859  TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5860                                          QualType Replacement);
5861
5862  /// \brief Result type of DeduceAutoType.
5863  enum DeduceAutoResult {
5864    DAR_Succeeded,
5865    DAR_Failed,
5866    DAR_FailedAlreadyDiagnosed
5867  };
5868
5869  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5870                                  QualType &Result);
5871  DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
5872                                  QualType &Result);
5873  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5874  bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5875                        bool Diagnose = true);
5876
5877  bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
5878                                        SourceLocation ReturnLoc,
5879                                        Expr *&RetExpr, AutoType *AT);
5880
5881  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5882                                                   FunctionTemplateDecl *FT2,
5883                                                   SourceLocation Loc,
5884                                           TemplatePartialOrderingContext TPOC,
5885                                                   unsigned NumCallArguments1,
5886                                                   unsigned NumCallArguments2);
5887  UnresolvedSetIterator
5888  getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
5889                     TemplateSpecCandidateSet &FailedCandidates,
5890                     SourceLocation Loc,
5891                     const PartialDiagnostic &NoneDiag,
5892                     const PartialDiagnostic &AmbigDiag,
5893                     const PartialDiagnostic &CandidateDiag,
5894                     bool Complain = true, QualType TargetType = QualType());
5895
5896  ClassTemplatePartialSpecializationDecl *
5897  getMoreSpecializedPartialSpecialization(
5898                                  ClassTemplatePartialSpecializationDecl *PS1,
5899                                  ClassTemplatePartialSpecializationDecl *PS2,
5900                                  SourceLocation Loc);
5901
5902  VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
5903      VarTemplatePartialSpecializationDecl *PS1,
5904      VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
5905
5906  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5907                                  bool OnlyDeduced,
5908                                  unsigned Depth,
5909                                  llvm::SmallBitVector &Used);
5910  void MarkDeducedTemplateParameters(
5911                                  const FunctionTemplateDecl *FunctionTemplate,
5912                                  llvm::SmallBitVector &Deduced) {
5913    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5914  }
5915  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5916                                  const FunctionTemplateDecl *FunctionTemplate,
5917                                  llvm::SmallBitVector &Deduced);
5918
5919  //===--------------------------------------------------------------------===//
5920  // C++ Template Instantiation
5921  //
5922
5923  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5924                                     const TemplateArgumentList *Innermost = 0,
5925                                                bool RelativeToPrimary = false,
5926                                               const FunctionDecl *Pattern = 0);
5927
5928  /// \brief A template instantiation that is currently in progress.
5929  struct ActiveTemplateInstantiation {
5930    /// \brief The kind of template instantiation we are performing
5931    enum InstantiationKind {
5932      /// We are instantiating a template declaration. The entity is
5933      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5934      TemplateInstantiation,
5935
5936      /// We are instantiating a default argument for a template
5937      /// parameter. The Entity is the template, and
5938      /// TemplateArgs/NumTemplateArguments provides the template
5939      /// arguments as specified.
5940      /// FIXME: Use a TemplateArgumentList
5941      DefaultTemplateArgumentInstantiation,
5942
5943      /// We are instantiating a default argument for a function.
5944      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5945      /// provides the template arguments as specified.
5946      DefaultFunctionArgumentInstantiation,
5947
5948      /// We are substituting explicit template arguments provided for
5949      /// a function template. The entity is a FunctionTemplateDecl.
5950      ExplicitTemplateArgumentSubstitution,
5951
5952      /// We are substituting template argument determined as part of
5953      /// template argument deduction for either a class template
5954      /// partial specialization or a function template. The
5955      /// Entity is either a ClassTemplatePartialSpecializationDecl or
5956      /// a FunctionTemplateDecl.
5957      DeducedTemplateArgumentSubstitution,
5958
5959      /// We are substituting prior template arguments into a new
5960      /// template parameter. The template parameter itself is either a
5961      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5962      PriorTemplateArgumentSubstitution,
5963
5964      /// We are checking the validity of a default template argument that
5965      /// has been used when naming a template-id.
5966      DefaultTemplateArgumentChecking,
5967
5968      /// We are instantiating the exception specification for a function
5969      /// template which was deferred until it was needed.
5970      ExceptionSpecInstantiation
5971    } Kind;
5972
5973    /// \brief The point of instantiation within the source code.
5974    SourceLocation PointOfInstantiation;
5975
5976    /// \brief The template (or partial specialization) in which we are
5977    /// performing the instantiation, for substitutions of prior template
5978    /// arguments.
5979    NamedDecl *Template;
5980
5981    /// \brief The entity that is being instantiated.
5982    Decl *Entity;
5983
5984    /// \brief The list of template arguments we are substituting, if they
5985    /// are not part of the entity.
5986    const TemplateArgument *TemplateArgs;
5987
5988    /// \brief The number of template arguments in TemplateArgs.
5989    unsigned NumTemplateArgs;
5990
5991    /// \brief The template deduction info object associated with the
5992    /// substitution or checking of explicit or deduced template arguments.
5993    sema::TemplateDeductionInfo *DeductionInfo;
5994
5995    /// \brief The source range that covers the construct that cause
5996    /// the instantiation, e.g., the template-id that causes a class
5997    /// template instantiation.
5998    SourceRange InstantiationRange;
5999
6000    ActiveTemplateInstantiation()
6001      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
6002        NumTemplateArgs(0), DeductionInfo(0) {}
6003
6004    /// \brief Determines whether this template is an actual instantiation
6005    /// that should be counted toward the maximum instantiation depth.
6006    bool isInstantiationRecord() const;
6007
6008    friend bool operator==(const ActiveTemplateInstantiation &X,
6009                           const ActiveTemplateInstantiation &Y) {
6010      if (X.Kind != Y.Kind)
6011        return false;
6012
6013      if (X.Entity != Y.Entity)
6014        return false;
6015
6016      switch (X.Kind) {
6017      case TemplateInstantiation:
6018      case ExceptionSpecInstantiation:
6019        return true;
6020
6021      case PriorTemplateArgumentSubstitution:
6022      case DefaultTemplateArgumentChecking:
6023        return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6024
6025      case DefaultTemplateArgumentInstantiation:
6026      case ExplicitTemplateArgumentSubstitution:
6027      case DeducedTemplateArgumentSubstitution:
6028      case DefaultFunctionArgumentInstantiation:
6029        return X.TemplateArgs == Y.TemplateArgs;
6030
6031      }
6032
6033      llvm_unreachable("Invalid InstantiationKind!");
6034    }
6035
6036    friend bool operator!=(const ActiveTemplateInstantiation &X,
6037                           const ActiveTemplateInstantiation &Y) {
6038      return !(X == Y);
6039    }
6040  };
6041
6042  /// \brief List of active template instantiations.
6043  ///
6044  /// This vector is treated as a stack. As one template instantiation
6045  /// requires another template instantiation, additional
6046  /// instantiations are pushed onto the stack up to a
6047  /// user-configurable limit LangOptions::InstantiationDepth.
6048  SmallVector<ActiveTemplateInstantiation, 16>
6049    ActiveTemplateInstantiations;
6050
6051  /// \brief Extra modules inspected when performing a lookup during a template
6052  /// instantiation. Computed lazily.
6053  SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6054
6055  /// \brief Cache of additional modules that should be used for name lookup
6056  /// within the current template instantiation. Computed lazily; use
6057  /// getLookupModules() to get a complete set.
6058  llvm::DenseSet<Module*> LookupModulesCache;
6059
6060  /// \brief Get the set of additional modules that should be checked during
6061  /// name lookup. A module and its imports become visible when instanting a
6062  /// template defined within it.
6063  llvm::DenseSet<Module*> &getLookupModules();
6064
6065  /// \brief Whether we are in a SFINAE context that is not associated with
6066  /// template instantiation.
6067  ///
6068  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6069  /// of a template instantiation or template argument deduction.
6070  bool InNonInstantiationSFINAEContext;
6071
6072  /// \brief The number of ActiveTemplateInstantiation entries in
6073  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6074  /// therefore, should not be counted as part of the instantiation depth.
6075  unsigned NonInstantiationEntries;
6076
6077  /// \brief The last template from which a template instantiation
6078  /// error or warning was produced.
6079  ///
6080  /// This value is used to suppress printing of redundant template
6081  /// instantiation backtraces when there are multiple errors in the
6082  /// same instantiation. FIXME: Does this belong in Sema? It's tough
6083  /// to implement it anywhere else.
6084  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6085
6086  /// \brief The current index into pack expansion arguments that will be
6087  /// used for substitution of parameter packs.
6088  ///
6089  /// The pack expansion index will be -1 to indicate that parameter packs
6090  /// should be instantiated as themselves. Otherwise, the index specifies
6091  /// which argument within the parameter pack will be used for substitution.
6092  int ArgumentPackSubstitutionIndex;
6093
6094  /// \brief RAII object used to change the argument pack substitution index
6095  /// within a \c Sema object.
6096  ///
6097  /// See \c ArgumentPackSubstitutionIndex for more information.
6098  class ArgumentPackSubstitutionIndexRAII {
6099    Sema &Self;
6100    int OldSubstitutionIndex;
6101
6102  public:
6103    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6104      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6105      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6106    }
6107
6108    ~ArgumentPackSubstitutionIndexRAII() {
6109      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6110    }
6111  };
6112
6113  friend class ArgumentPackSubstitutionRAII;
6114
6115  /// \brief The stack of calls expression undergoing template instantiation.
6116  ///
6117  /// The top of this stack is used by a fixit instantiating unresolved
6118  /// function calls to fix the AST to match the textual change it prints.
6119  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6120
6121  /// \brief For each declaration that involved template argument deduction, the
6122  /// set of diagnostics that were suppressed during that template argument
6123  /// deduction.
6124  ///
6125  /// FIXME: Serialize this structure to the AST file.
6126  typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6127    SuppressedDiagnosticsMap;
6128  SuppressedDiagnosticsMap SuppressedDiagnostics;
6129
6130  /// \brief A stack object to be created when performing template
6131  /// instantiation.
6132  ///
6133  /// Construction of an object of type \c InstantiatingTemplate
6134  /// pushes the current instantiation onto the stack of active
6135  /// instantiations. If the size of this stack exceeds the maximum
6136  /// number of recursive template instantiations, construction
6137  /// produces an error and evaluates true.
6138  ///
6139  /// Destruction of this object will pop the named instantiation off
6140  /// the stack.
6141  struct InstantiatingTemplate {
6142    /// \brief Note that we are instantiating a class template,
6143    /// function template, or a member thereof.
6144    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6145                          Decl *Entity,
6146                          SourceRange InstantiationRange = SourceRange());
6147
6148    struct ExceptionSpecification {};
6149    /// \brief Note that we are instantiating an exception specification
6150    /// of a function template.
6151    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6152                          FunctionDecl *Entity, ExceptionSpecification,
6153                          SourceRange InstantiationRange = SourceRange());
6154
6155    /// \brief Note that we are instantiating a default argument in a
6156    /// template-id.
6157    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6158                          TemplateDecl *Template,
6159                          ArrayRef<TemplateArgument> TemplateArgs,
6160                          SourceRange InstantiationRange = SourceRange());
6161
6162    /// \brief Note that we are instantiating a default argument in a
6163    /// template-id.
6164    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6165                          FunctionTemplateDecl *FunctionTemplate,
6166                          ArrayRef<TemplateArgument> TemplateArgs,
6167                          ActiveTemplateInstantiation::InstantiationKind Kind,
6168                          sema::TemplateDeductionInfo &DeductionInfo,
6169                          SourceRange InstantiationRange = SourceRange());
6170
6171    /// \brief Note that we are instantiating as part of template
6172    /// argument deduction for a class template partial
6173    /// specialization.
6174    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6175                          ClassTemplatePartialSpecializationDecl *PartialSpec,
6176                          ArrayRef<TemplateArgument> TemplateArgs,
6177                          sema::TemplateDeductionInfo &DeductionInfo,
6178                          SourceRange InstantiationRange = SourceRange());
6179
6180    /// \brief Note that we are instantiating as part of template
6181    /// argument deduction for a variable template partial
6182    /// specialization.
6183    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6184                          VarTemplatePartialSpecializationDecl *PartialSpec,
6185                          ArrayRef<TemplateArgument> TemplateArgs,
6186                          sema::TemplateDeductionInfo &DeductionInfo,
6187                          SourceRange InstantiationRange = SourceRange());
6188
6189    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6190                          ParmVarDecl *Param,
6191                          ArrayRef<TemplateArgument> TemplateArgs,
6192                          SourceRange InstantiationRange = SourceRange());
6193
6194    /// \brief Note that we are substituting prior template arguments into a
6195    /// non-type or template template parameter.
6196    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6197                          NamedDecl *Template,
6198                          NonTypeTemplateParmDecl *Param,
6199                          ArrayRef<TemplateArgument> TemplateArgs,
6200                          SourceRange InstantiationRange);
6201
6202    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6203                          NamedDecl *Template,
6204                          TemplateTemplateParmDecl *Param,
6205                          ArrayRef<TemplateArgument> TemplateArgs,
6206                          SourceRange InstantiationRange);
6207
6208    /// \brief Note that we are checking the default template argument
6209    /// against the template parameter for a given template-id.
6210    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6211                          TemplateDecl *Template,
6212                          NamedDecl *Param,
6213                          ArrayRef<TemplateArgument> TemplateArgs,
6214                          SourceRange InstantiationRange);
6215
6216
6217    /// \brief Note that we have finished instantiating this template.
6218    void Clear();
6219
6220    ~InstantiatingTemplate() { Clear(); }
6221
6222    /// \brief Determines whether we have exceeded the maximum
6223    /// recursive template instantiations.
6224    LLVM_EXPLICIT operator bool() const { return Invalid; }
6225
6226  private:
6227    Sema &SemaRef;
6228    bool Invalid;
6229    bool SavedInNonInstantiationSFINAEContext;
6230    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6231                                 SourceRange InstantiationRange);
6232
6233    InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6234
6235    InstantiatingTemplate&
6236    operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6237  };
6238
6239  void PrintInstantiationStack();
6240
6241  /// \brief Determines whether we are currently in a context where
6242  /// template argument substitution failures are not considered
6243  /// errors.
6244  ///
6245  /// \returns An empty \c Optional if we're not in a SFINAE context.
6246  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6247  /// template-deduction context object, which can be used to capture
6248  /// diagnostics that will be suppressed.
6249  Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6250
6251  /// \brief Determines whether we are currently in a context that
6252  /// is not evaluated as per C++ [expr] p5.
6253  bool isUnevaluatedContext() const {
6254    assert(!ExprEvalContexts.empty() &&
6255           "Must be in an expression evaluation context");
6256    return ExprEvalContexts.back().isUnevaluated();
6257  }
6258
6259  /// \brief RAII class used to determine whether SFINAE has
6260  /// trapped any errors that occur during template argument
6261  /// deduction.
6262  class SFINAETrap {
6263    Sema &SemaRef;
6264    unsigned PrevSFINAEErrors;
6265    bool PrevInNonInstantiationSFINAEContext;
6266    bool PrevAccessCheckingSFINAE;
6267
6268  public:
6269    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6270      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6271        PrevInNonInstantiationSFINAEContext(
6272                                      SemaRef.InNonInstantiationSFINAEContext),
6273        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6274    {
6275      if (!SemaRef.isSFINAEContext())
6276        SemaRef.InNonInstantiationSFINAEContext = true;
6277      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6278    }
6279
6280    ~SFINAETrap() {
6281      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6282      SemaRef.InNonInstantiationSFINAEContext
6283        = PrevInNonInstantiationSFINAEContext;
6284      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6285    }
6286
6287    /// \brief Determine whether any SFINAE errors have been trapped.
6288    bool hasErrorOccurred() const {
6289      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6290    }
6291  };
6292
6293  /// \brief RAII class used to indicate that we are performing provisional
6294  /// semantic analysis to determine the validity of a construct, so
6295  /// typo-correction and diagnostics in the immediate context (not within
6296  /// implicitly-instantiated templates) should be suppressed.
6297  class TentativeAnalysisScope {
6298    Sema &SemaRef;
6299    // FIXME: Using a SFINAETrap for this is a hack.
6300    SFINAETrap Trap;
6301    bool PrevDisableTypoCorrection;
6302  public:
6303    explicit TentativeAnalysisScope(Sema &SemaRef)
6304        : SemaRef(SemaRef), Trap(SemaRef, true),
6305          PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6306      SemaRef.DisableTypoCorrection = true;
6307    }
6308    ~TentativeAnalysisScope() {
6309      SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6310    }
6311  };
6312
6313  /// \brief The current instantiation scope used to store local
6314  /// variables.
6315  LocalInstantiationScope *CurrentInstantiationScope;
6316
6317  /// \brief Tracks whether we are in a context where typo correction is
6318  /// disabled.
6319  bool DisableTypoCorrection;
6320
6321  /// \brief The number of typos corrected by CorrectTypo.
6322  unsigned TyposCorrected;
6323
6324  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
6325    UnqualifiedTyposCorrectedMap;
6326
6327  /// \brief A cache containing the results of typo correction for unqualified
6328  /// name lookup.
6329  ///
6330  /// The string is the string that we corrected to (which may be empty, if
6331  /// there was no correction), while the boolean will be true when the
6332  /// string represents a keyword.
6333  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6334
6335  typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6336  typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6337
6338  /// \brief A cache containing identifiers for which typo correction failed and
6339  /// their locations, so that repeated attempts to correct an identifier in a
6340  /// given location are ignored if typo correction already failed for it.
6341  IdentifierSourceLocations TypoCorrectionFailures;
6342
6343  /// \brief Worker object for performing CFG-based warnings.
6344  sema::AnalysisBasedWarnings AnalysisWarnings;
6345
6346  /// \brief An entity for which implicit template instantiation is required.
6347  ///
6348  /// The source location associated with the declaration is the first place in
6349  /// the source code where the declaration was "used". It is not necessarily
6350  /// the point of instantiation (which will be either before or after the
6351  /// namespace-scope declaration that triggered this implicit instantiation),
6352  /// However, it is the location that diagnostics should generally refer to,
6353  /// because users will need to know what code triggered the instantiation.
6354  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6355
6356  /// \brief The queue of implicit template instantiations that are required
6357  /// but have not yet been performed.
6358  std::deque<PendingImplicitInstantiation> PendingInstantiations;
6359
6360  /// \brief The queue of implicit template instantiations that are required
6361  /// and must be performed within the current local scope.
6362  ///
6363  /// This queue is only used for member functions of local classes in
6364  /// templates, which must be instantiated in the same scope as their
6365  /// enclosing function, so that they can reference function-local
6366  /// types, static variables, enumerators, etc.
6367  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6368
6369  void PerformPendingInstantiations(bool LocalOnly = false);
6370
6371  TypeSourceInfo *SubstType(TypeSourceInfo *T,
6372                            const MultiLevelTemplateArgumentList &TemplateArgs,
6373                            SourceLocation Loc, DeclarationName Entity);
6374
6375  QualType SubstType(QualType T,
6376                     const MultiLevelTemplateArgumentList &TemplateArgs,
6377                     SourceLocation Loc, DeclarationName Entity);
6378
6379  TypeSourceInfo *SubstType(TypeLoc TL,
6380                            const MultiLevelTemplateArgumentList &TemplateArgs,
6381                            SourceLocation Loc, DeclarationName Entity);
6382
6383  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6384                            const MultiLevelTemplateArgumentList &TemplateArgs,
6385                                        SourceLocation Loc,
6386                                        DeclarationName Entity,
6387                                        CXXRecordDecl *ThisContext,
6388                                        unsigned ThisTypeQuals);
6389  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6390                            const MultiLevelTemplateArgumentList &TemplateArgs,
6391                                int indexAdjustment,
6392                                Optional<unsigned> NumExpansions,
6393                                bool ExpectParameterPack);
6394  bool SubstParmTypes(SourceLocation Loc,
6395                      ParmVarDecl **Params, unsigned NumParams,
6396                      const MultiLevelTemplateArgumentList &TemplateArgs,
6397                      SmallVectorImpl<QualType> &ParamTypes,
6398                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
6399  ExprResult SubstExpr(Expr *E,
6400                       const MultiLevelTemplateArgumentList &TemplateArgs);
6401
6402  /// \brief Substitute the given template arguments into a list of
6403  /// expressions, expanding pack expansions if required.
6404  ///
6405  /// \param Exprs The list of expressions to substitute into.
6406  ///
6407  /// \param NumExprs The number of expressions in \p Exprs.
6408  ///
6409  /// \param IsCall Whether this is some form of call, in which case
6410  /// default arguments will be dropped.
6411  ///
6412  /// \param TemplateArgs The set of template arguments to substitute.
6413  ///
6414  /// \param Outputs Will receive all of the substituted arguments.
6415  ///
6416  /// \returns true if an error occurred, false otherwise.
6417  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6418                  const MultiLevelTemplateArgumentList &TemplateArgs,
6419                  SmallVectorImpl<Expr *> &Outputs);
6420
6421  StmtResult SubstStmt(Stmt *S,
6422                       const MultiLevelTemplateArgumentList &TemplateArgs);
6423
6424  Decl *SubstDecl(Decl *D, DeclContext *Owner,
6425                  const MultiLevelTemplateArgumentList &TemplateArgs);
6426
6427  ExprResult SubstInitializer(Expr *E,
6428                       const MultiLevelTemplateArgumentList &TemplateArgs,
6429                       bool CXXDirectInit);
6430
6431  bool
6432  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6433                      CXXRecordDecl *Pattern,
6434                      const MultiLevelTemplateArgumentList &TemplateArgs);
6435
6436  bool
6437  InstantiateClass(SourceLocation PointOfInstantiation,
6438                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6439                   const MultiLevelTemplateArgumentList &TemplateArgs,
6440                   TemplateSpecializationKind TSK,
6441                   bool Complain = true);
6442
6443  bool InstantiateEnum(SourceLocation PointOfInstantiation,
6444                       EnumDecl *Instantiation, EnumDecl *Pattern,
6445                       const MultiLevelTemplateArgumentList &TemplateArgs,
6446                       TemplateSpecializationKind TSK);
6447
6448  struct LateInstantiatedAttribute {
6449    const Attr *TmplAttr;
6450    LocalInstantiationScope *Scope;
6451    Decl *NewDecl;
6452
6453    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6454                              Decl *D)
6455      : TmplAttr(A), Scope(S), NewDecl(D)
6456    { }
6457  };
6458  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6459
6460  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6461                        const Decl *Pattern, Decl *Inst,
6462                        LateInstantiatedAttrVec *LateAttrs = 0,
6463                        LocalInstantiationScope *OuterMostScope = 0);
6464
6465  bool
6466  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6467                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6468                           TemplateSpecializationKind TSK,
6469                           bool Complain = true);
6470
6471  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6472                               CXXRecordDecl *Instantiation,
6473                            const MultiLevelTemplateArgumentList &TemplateArgs,
6474                               TemplateSpecializationKind TSK);
6475
6476  void InstantiateClassTemplateSpecializationMembers(
6477                                          SourceLocation PointOfInstantiation,
6478                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6479                                                TemplateSpecializationKind TSK);
6480
6481  NestedNameSpecifierLoc
6482  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6483                           const MultiLevelTemplateArgumentList &TemplateArgs);
6484
6485  DeclarationNameInfo
6486  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6487                           const MultiLevelTemplateArgumentList &TemplateArgs);
6488  TemplateName
6489  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6490                    SourceLocation Loc,
6491                    const MultiLevelTemplateArgumentList &TemplateArgs);
6492  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6493             TemplateArgumentListInfo &Result,
6494             const MultiLevelTemplateArgumentList &TemplateArgs);
6495
6496  void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6497                                FunctionDecl *Function);
6498  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6499                                     FunctionDecl *Function,
6500                                     bool Recursive = false,
6501                                     bool DefinitionRequired = false);
6502  VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
6503      VarTemplateDecl *VarTemplate, VarDecl *FromVar,
6504      const TemplateArgumentList &TemplateArgList,
6505      const TemplateArgumentListInfo &TemplateArgsInfo,
6506      SmallVectorImpl<TemplateArgument> &Converted,
6507      SourceLocation PointOfInstantiation, void *InsertPos,
6508      LateInstantiatedAttrVec *LateAttrs = 0,
6509      LocalInstantiationScope *StartingScope = 0);
6510  VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
6511      VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6512      const MultiLevelTemplateArgumentList &TemplateArgs);
6513  void
6514  BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
6515                             const MultiLevelTemplateArgumentList &TemplateArgs,
6516                             LateInstantiatedAttrVec *LateAttrs,
6517                             DeclContext *Owner,
6518                             LocalInstantiationScope *StartingScope,
6519                             bool InstantiatingVarTemplate = false);
6520  void InstantiateVariableInitializer(
6521      VarDecl *Var, VarDecl *OldVar,
6522      const MultiLevelTemplateArgumentList &TemplateArgs);
6523  void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
6524                                     VarDecl *Var, bool Recursive = false,
6525                                     bool DefinitionRequired = false);
6526  void InstantiateStaticDataMemberDefinition(
6527                                     SourceLocation PointOfInstantiation,
6528                                     VarDecl *Var,
6529                                     bool Recursive = false,
6530                                     bool DefinitionRequired = false);
6531
6532  void InstantiateMemInitializers(CXXConstructorDecl *New,
6533                                  const CXXConstructorDecl *Tmpl,
6534                            const MultiLevelTemplateArgumentList &TemplateArgs);
6535
6536  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6537                          const MultiLevelTemplateArgumentList &TemplateArgs);
6538  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6539                          const MultiLevelTemplateArgumentList &TemplateArgs);
6540
6541  // Objective-C declarations.
6542  enum ObjCContainerKind {
6543    OCK_None = -1,
6544    OCK_Interface = 0,
6545    OCK_Protocol,
6546    OCK_Category,
6547    OCK_ClassExtension,
6548    OCK_Implementation,
6549    OCK_CategoryImplementation
6550  };
6551  ObjCContainerKind getObjCContainerKind() const;
6552
6553  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6554                                 IdentifierInfo *ClassName,
6555                                 SourceLocation ClassLoc,
6556                                 IdentifierInfo *SuperName,
6557                                 SourceLocation SuperLoc,
6558                                 Decl * const *ProtoRefs,
6559                                 unsigned NumProtoRefs,
6560                                 const SourceLocation *ProtoLocs,
6561                                 SourceLocation EndProtoLoc,
6562                                 AttributeList *AttrList);
6563
6564  void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
6565                               IdentifierInfo *SuperName,
6566                               SourceLocation SuperLoc);
6567
6568  Decl *ActOnCompatibilityAlias(
6569                    SourceLocation AtCompatibilityAliasLoc,
6570                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
6571                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
6572
6573  bool CheckForwardProtocolDeclarationForCircularDependency(
6574    IdentifierInfo *PName,
6575    SourceLocation &PLoc, SourceLocation PrevLoc,
6576    const ObjCList<ObjCProtocolDecl> &PList);
6577
6578  Decl *ActOnStartProtocolInterface(
6579                    SourceLocation AtProtoInterfaceLoc,
6580                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6581                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6582                    const SourceLocation *ProtoLocs,
6583                    SourceLocation EndProtoLoc,
6584                    AttributeList *AttrList);
6585
6586  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6587                                    IdentifierInfo *ClassName,
6588                                    SourceLocation ClassLoc,
6589                                    IdentifierInfo *CategoryName,
6590                                    SourceLocation CategoryLoc,
6591                                    Decl * const *ProtoRefs,
6592                                    unsigned NumProtoRefs,
6593                                    const SourceLocation *ProtoLocs,
6594                                    SourceLocation EndProtoLoc);
6595
6596  Decl *ActOnStartClassImplementation(
6597                    SourceLocation AtClassImplLoc,
6598                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
6599                    IdentifierInfo *SuperClassname,
6600                    SourceLocation SuperClassLoc);
6601
6602  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6603                                         IdentifierInfo *ClassName,
6604                                         SourceLocation ClassLoc,
6605                                         IdentifierInfo *CatName,
6606                                         SourceLocation CatLoc);
6607
6608  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6609                                               ArrayRef<Decl *> Decls);
6610
6611  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6612                                     IdentifierInfo **IdentList,
6613                                     SourceLocation *IdentLocs,
6614                                     unsigned NumElts);
6615
6616  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6617                                        const IdentifierLocPair *IdentList,
6618                                        unsigned NumElts,
6619                                        AttributeList *attrList);
6620
6621  void FindProtocolDeclaration(bool WarnOnDeclarations,
6622                               const IdentifierLocPair *ProtocolId,
6623                               unsigned NumProtocols,
6624                               SmallVectorImpl<Decl *> &Protocols);
6625
6626  /// Ensure attributes are consistent with type.
6627  /// \param [in, out] Attributes The attributes to check; they will
6628  /// be modified to be consistent with \p PropertyTy.
6629  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6630                                   SourceLocation Loc,
6631                                   unsigned &Attributes,
6632                                   bool propertyInPrimaryClass);
6633
6634  /// Process the specified property declaration and create decls for the
6635  /// setters and getters as needed.
6636  /// \param property The property declaration being processed
6637  /// \param CD The semantic container for the property
6638  /// \param redeclaredProperty Declaration for property if redeclared
6639  ///        in class extension.
6640  /// \param lexicalDC Container for redeclaredProperty.
6641  void ProcessPropertyDecl(ObjCPropertyDecl *property,
6642                           ObjCContainerDecl *CD,
6643                           ObjCPropertyDecl *redeclaredProperty = 0,
6644                           ObjCContainerDecl *lexicalDC = 0);
6645
6646
6647  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6648                                ObjCPropertyDecl *SuperProperty,
6649                                const IdentifierInfo *Name,
6650                                bool OverridingProtocolProperty);
6651
6652  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6653                                        ObjCInterfaceDecl *ID);
6654
6655  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6656                   ArrayRef<Decl *> allMethods = None,
6657                   ArrayRef<DeclGroupPtrTy> allTUVars = None);
6658
6659  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6660                      SourceLocation LParenLoc,
6661                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
6662                      Selector GetterSel, Selector SetterSel,
6663                      bool *OverridingProperty,
6664                      tok::ObjCKeywordKind MethodImplKind,
6665                      DeclContext *lexicalDC = 0);
6666
6667  Decl *ActOnPropertyImplDecl(Scope *S,
6668                              SourceLocation AtLoc,
6669                              SourceLocation PropertyLoc,
6670                              bool ImplKind,
6671                              IdentifierInfo *PropertyId,
6672                              IdentifierInfo *PropertyIvar,
6673                              SourceLocation PropertyIvarLoc);
6674
6675  enum ObjCSpecialMethodKind {
6676    OSMK_None,
6677    OSMK_Alloc,
6678    OSMK_New,
6679    OSMK_Copy,
6680    OSMK_RetainingInit,
6681    OSMK_NonRetainingInit
6682  };
6683
6684  struct ObjCArgInfo {
6685    IdentifierInfo *Name;
6686    SourceLocation NameLoc;
6687    // The Type is null if no type was specified, and the DeclSpec is invalid
6688    // in this case.
6689    ParsedType Type;
6690    ObjCDeclSpec DeclSpec;
6691
6692    /// ArgAttrs - Attribute list for this argument.
6693    AttributeList *ArgAttrs;
6694  };
6695
6696  Decl *ActOnMethodDeclaration(
6697    Scope *S,
6698    SourceLocation BeginLoc, // location of the + or -.
6699    SourceLocation EndLoc,   // location of the ; or {.
6700    tok::TokenKind MethodType,
6701    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6702    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6703    // optional arguments. The number of types/arguments is obtained
6704    // from the Sel.getNumArgs().
6705    ObjCArgInfo *ArgInfo,
6706    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6707    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6708    bool isVariadic, bool MethodDefinition);
6709
6710  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6711                                              const ObjCObjectPointerType *OPT,
6712                                              bool IsInstance);
6713  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6714                                           bool IsInstance);
6715
6716  bool CheckARCMethodDecl(ObjCMethodDecl *method);
6717  bool inferObjCARCLifetime(ValueDecl *decl);
6718
6719  ExprResult
6720  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6721                            Expr *BaseExpr,
6722                            SourceLocation OpLoc,
6723                            DeclarationName MemberName,
6724                            SourceLocation MemberLoc,
6725                            SourceLocation SuperLoc, QualType SuperType,
6726                            bool Super);
6727
6728  ExprResult
6729  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6730                            IdentifierInfo &propertyName,
6731                            SourceLocation receiverNameLoc,
6732                            SourceLocation propertyNameLoc);
6733
6734  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6735
6736  /// \brief Describes the kind of message expression indicated by a message
6737  /// send that starts with an identifier.
6738  enum ObjCMessageKind {
6739    /// \brief The message is sent to 'super'.
6740    ObjCSuperMessage,
6741    /// \brief The message is an instance message.
6742    ObjCInstanceMessage,
6743    /// \brief The message is a class message, and the identifier is a type
6744    /// name.
6745    ObjCClassMessage
6746  };
6747
6748  ObjCMessageKind getObjCMessageKind(Scope *S,
6749                                     IdentifierInfo *Name,
6750                                     SourceLocation NameLoc,
6751                                     bool IsSuper,
6752                                     bool HasTrailingDot,
6753                                     ParsedType &ReceiverType);
6754
6755  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6756                               Selector Sel,
6757                               SourceLocation LBracLoc,
6758                               ArrayRef<SourceLocation> SelectorLocs,
6759                               SourceLocation RBracLoc,
6760                               MultiExprArg Args);
6761
6762  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6763                               QualType ReceiverType,
6764                               SourceLocation SuperLoc,
6765                               Selector Sel,
6766                               ObjCMethodDecl *Method,
6767                               SourceLocation LBracLoc,
6768                               ArrayRef<SourceLocation> SelectorLocs,
6769                               SourceLocation RBracLoc,
6770                               MultiExprArg Args,
6771                               bool isImplicit = false);
6772
6773  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6774                                       bool isSuperReceiver,
6775                                       SourceLocation Loc,
6776                                       Selector Sel,
6777                                       ObjCMethodDecl *Method,
6778                                       MultiExprArg Args);
6779
6780  ExprResult ActOnClassMessage(Scope *S,
6781                               ParsedType Receiver,
6782                               Selector Sel,
6783                               SourceLocation LBracLoc,
6784                               ArrayRef<SourceLocation> SelectorLocs,
6785                               SourceLocation RBracLoc,
6786                               MultiExprArg Args);
6787
6788  ExprResult BuildInstanceMessage(Expr *Receiver,
6789                                  QualType ReceiverType,
6790                                  SourceLocation SuperLoc,
6791                                  Selector Sel,
6792                                  ObjCMethodDecl *Method,
6793                                  SourceLocation LBracLoc,
6794                                  ArrayRef<SourceLocation> SelectorLocs,
6795                                  SourceLocation RBracLoc,
6796                                  MultiExprArg Args,
6797                                  bool isImplicit = false);
6798
6799  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6800                                          QualType ReceiverType,
6801                                          SourceLocation Loc,
6802                                          Selector Sel,
6803                                          ObjCMethodDecl *Method,
6804                                          MultiExprArg Args);
6805
6806  ExprResult ActOnInstanceMessage(Scope *S,
6807                                  Expr *Receiver,
6808                                  Selector Sel,
6809                                  SourceLocation LBracLoc,
6810                                  ArrayRef<SourceLocation> SelectorLocs,
6811                                  SourceLocation RBracLoc,
6812                                  MultiExprArg Args);
6813
6814  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6815                                  ObjCBridgeCastKind Kind,
6816                                  SourceLocation BridgeKeywordLoc,
6817                                  TypeSourceInfo *TSInfo,
6818                                  Expr *SubExpr);
6819
6820  ExprResult ActOnObjCBridgedCast(Scope *S,
6821                                  SourceLocation LParenLoc,
6822                                  ObjCBridgeCastKind Kind,
6823                                  SourceLocation BridgeKeywordLoc,
6824                                  ParsedType Type,
6825                                  SourceLocation RParenLoc,
6826                                  Expr *SubExpr);
6827
6828  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6829
6830  /// \brief Check whether the given new method is a valid override of the
6831  /// given overridden method, and set any properties that should be inherited.
6832  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6833                               const ObjCMethodDecl *Overridden);
6834
6835  /// \brief Describes the compatibility of a result type with its method.
6836  enum ResultTypeCompatibilityKind {
6837    RTC_Compatible,
6838    RTC_Incompatible,
6839    RTC_Unknown
6840  };
6841
6842  void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6843                                ObjCInterfaceDecl *CurrentClass,
6844                                ResultTypeCompatibilityKind RTC);
6845
6846  enum PragmaOptionsAlignKind {
6847    POAK_Native,  // #pragma options align=native
6848    POAK_Natural, // #pragma options align=natural
6849    POAK_Packed,  // #pragma options align=packed
6850    POAK_Power,   // #pragma options align=power
6851    POAK_Mac68k,  // #pragma options align=mac68k
6852    POAK_Reset    // #pragma options align=reset
6853  };
6854
6855  /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6856  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6857                               SourceLocation PragmaLoc);
6858
6859  enum PragmaPackKind {
6860    PPK_Default, // #pragma pack([n])
6861    PPK_Show,    // #pragma pack(show), only supported by MSVC.
6862    PPK_Push,    // #pragma pack(push, [identifier], [n])
6863    PPK_Pop      // #pragma pack(pop, [identifier], [n])
6864  };
6865
6866  enum PragmaMSStructKind {
6867    PMSST_OFF,  // #pragms ms_struct off
6868    PMSST_ON    // #pragms ms_struct on
6869  };
6870
6871  enum PragmaMSCommentKind {
6872    PCK_Unknown,
6873    PCK_Linker,   // #pragma comment(linker, ...)
6874    PCK_Lib,      // #pragma comment(lib, ...)
6875    PCK_Compiler, // #pragma comment(compiler, ...)
6876    PCK_ExeStr,   // #pragma comment(exestr, ...)
6877    PCK_User      // #pragma comment(user, ...)
6878  };
6879
6880  /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6881  void ActOnPragmaPack(PragmaPackKind Kind,
6882                       IdentifierInfo *Name,
6883                       Expr *Alignment,
6884                       SourceLocation PragmaLoc,
6885                       SourceLocation LParenLoc,
6886                       SourceLocation RParenLoc);
6887
6888  /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6889  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6890
6891  /// ActOnPragmaMSComment - Called on well formed
6892  /// \#pragma comment(kind, "arg").
6893  void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
6894
6895  /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
6896  void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
6897
6898  /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6899  void ActOnPragmaUnused(const Token &Identifier,
6900                         Scope *curScope,
6901                         SourceLocation PragmaLoc);
6902
6903  /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6904  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6905                             SourceLocation PragmaLoc);
6906
6907  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6908                                 SourceLocation Loc);
6909  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6910
6911  /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6912  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6913                         SourceLocation PragmaLoc,
6914                         SourceLocation WeakNameLoc);
6915
6916  /// ActOnPragmaRedefineExtname - Called on well formed
6917  /// \#pragma redefine_extname oldname newname.
6918  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6919                                  IdentifierInfo* AliasName,
6920                                  SourceLocation PragmaLoc,
6921                                  SourceLocation WeakNameLoc,
6922                                  SourceLocation AliasNameLoc);
6923
6924  /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
6925  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
6926                            IdentifierInfo* AliasName,
6927                            SourceLocation PragmaLoc,
6928                            SourceLocation WeakNameLoc,
6929                            SourceLocation AliasNameLoc);
6930
6931  /// ActOnPragmaFPContract - Called on well formed
6932  /// \#pragma {STDC,OPENCL} FP_CONTRACT
6933  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
6934
6935  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
6936  /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
6937  void AddAlignmentAttributesForRecord(RecordDecl *RD);
6938
6939  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
6940  void AddMsStructLayoutForRecord(RecordDecl *RD);
6941
6942  /// FreePackedContext - Deallocate and null out PackContext.
6943  void FreePackedContext();
6944
6945  /// PushNamespaceVisibilityAttr - Note that we've entered a
6946  /// namespace with a visibility attribute.
6947  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
6948                                   SourceLocation Loc);
6949
6950  /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
6951  /// add an appropriate visibility attribute.
6952  void AddPushedVisibilityAttribute(Decl *RD);
6953
6954  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6955  /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
6956  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6957
6958  /// FreeVisContext - Deallocate and null out VisContext.
6959  void FreeVisContext();
6960
6961  /// AddCFAuditedAttribute - Check whether we're currently within
6962  /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
6963  /// the appropriate attribute.
6964  void AddCFAuditedAttribute(Decl *D);
6965
6966  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6967  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
6968                      unsigned SpellingListIndex, bool IsPackExpansion);
6969  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
6970                      unsigned SpellingListIndex, bool IsPackExpansion);
6971
6972  // OpenMP directives and clauses.
6973private:
6974  void *VarDataSharingAttributesStack;
6975  /// \brief Initialization of data-sharing attributes stack.
6976  void InitDataSharingAttributesStack();
6977  void DestroyDataSharingAttributesStack();
6978public:
6979  /// \brief Called on start of new data sharing attribute block.
6980  void StartOpenMPDSABlock(OpenMPDirectiveKind K,
6981                           const DeclarationNameInfo &DirName,
6982                           Scope *CurScope);
6983  /// \brief Called on end of data sharing attribute block.
6984  void EndOpenMPDSABlock(Stmt *CurDirective);
6985
6986  // OpenMP directives and clauses.
6987  /// \brief Called on correct id-expression from the '#pragma omp
6988  /// threadprivate'.
6989  ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
6990                                     CXXScopeSpec &ScopeSpec,
6991                                     const DeclarationNameInfo &Id);
6992  /// \brief Called on well-formed '#pragma omp threadprivate'.
6993  DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
6994                                     SourceLocation Loc,
6995                                     ArrayRef<Expr *> VarList);
6996  // \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
6997  OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
6998                                     SourceLocation Loc,
6999                                     ArrayRef<Expr *> VarList);
7000
7001  StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
7002                                            ArrayRef<OMPClause *> Clauses,
7003                                            Stmt *AStmt,
7004                                            SourceLocation StartLoc,
7005                                            SourceLocation EndLoc);
7006  /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7007  /// of the  associated statement.
7008  StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7009                                          Stmt *AStmt,
7010                                          SourceLocation StartLoc,
7011                                          SourceLocation EndLoc);
7012
7013  OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7014                                     unsigned Argument,
7015                                     SourceLocation ArgumentLoc,
7016                                     SourceLocation StartLoc,
7017                                     SourceLocation LParenLoc,
7018                                     SourceLocation EndLoc);
7019  /// \brief Called on well-formed 'default' clause.
7020  OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7021                                      SourceLocation KindLoc,
7022                                      SourceLocation StartLoc,
7023                                      SourceLocation LParenLoc,
7024                                      SourceLocation EndLoc);
7025
7026  OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
7027                                      ArrayRef<Expr *> Vars,
7028                                      SourceLocation StartLoc,
7029                                      SourceLocation LParenLoc,
7030                                      SourceLocation EndLoc);
7031  /// \brief Called on well-formed 'private' clause.
7032  OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7033                                      SourceLocation StartLoc,
7034                                      SourceLocation LParenLoc,
7035                                      SourceLocation EndLoc);
7036  /// \brief Called on well-formed 'firstprivate' clause.
7037  OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7038                                           SourceLocation StartLoc,
7039                                           SourceLocation LParenLoc,
7040                                           SourceLocation EndLoc);
7041  /// \brief Called on well-formed 'shared' clause.
7042  OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7043                                     SourceLocation StartLoc,
7044                                     SourceLocation LParenLoc,
7045                                     SourceLocation EndLoc);
7046
7047  /// \brief The kind of conversion being performed.
7048  enum CheckedConversionKind {
7049    /// \brief An implicit conversion.
7050    CCK_ImplicitConversion,
7051    /// \brief A C-style cast.
7052    CCK_CStyleCast,
7053    /// \brief A functional-style cast.
7054    CCK_FunctionalCast,
7055    /// \brief A cast other than a C-style cast.
7056    CCK_OtherCast
7057  };
7058
7059  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
7060  /// cast.  If there is already an implicit cast, merge into the existing one.
7061  /// If isLvalue, the result of the cast is an lvalue.
7062  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
7063                               ExprValueKind VK = VK_RValue,
7064                               const CXXCastPath *BasePath = 0,
7065                               CheckedConversionKind CCK
7066                                  = CCK_ImplicitConversion);
7067
7068  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7069  /// to the conversion from scalar type ScalarTy to the Boolean type.
7070  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
7071
7072  /// IgnoredValueConversions - Given that an expression's result is
7073  /// syntactically ignored, perform any conversions that are
7074  /// required.
7075  ExprResult IgnoredValueConversions(Expr *E);
7076
7077  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
7078  // functions and arrays to their respective pointers (C99 6.3.2.1).
7079  ExprResult UsualUnaryConversions(Expr *E);
7080
7081  // DefaultFunctionArrayConversion - converts functions and arrays
7082  // to their respective pointers (C99 6.3.2.1).
7083  ExprResult DefaultFunctionArrayConversion(Expr *E);
7084
7085  // DefaultFunctionArrayLvalueConversion - converts functions and
7086  // arrays to their respective pointers and performs the
7087  // lvalue-to-rvalue conversion.
7088  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
7089
7090  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7091  // the operand.  This is DefaultFunctionArrayLvalueConversion,
7092  // except that it assumes the operand isn't of function or array
7093  // type.
7094  ExprResult DefaultLvalueConversion(Expr *E);
7095
7096  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7097  // do not have a prototype. Integer promotions are performed on each
7098  // argument, and arguments that have type float are promoted to double.
7099  ExprResult DefaultArgumentPromotion(Expr *E);
7100
7101  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
7102  enum VariadicCallType {
7103    VariadicFunction,
7104    VariadicBlock,
7105    VariadicMethod,
7106    VariadicConstructor,
7107    VariadicDoesNotApply
7108  };
7109
7110  VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
7111                                       const FunctionProtoType *Proto,
7112                                       Expr *Fn);
7113
7114  // Used for determining in which context a type is allowed to be passed to a
7115  // vararg function.
7116  enum VarArgKind {
7117    VAK_Valid,
7118    VAK_ValidInCXX11,
7119    VAK_Undefined,
7120    VAK_Invalid
7121  };
7122
7123  // Determines which VarArgKind fits an expression.
7124  VarArgKind isValidVarArgType(const QualType &Ty);
7125
7126  /// Check to see if the given expression is a valid argument to a variadic
7127  /// function, issuing a diagnostic if not.
7128  void checkVariadicArgument(const Expr *E, VariadicCallType CT);
7129
7130  /// GatherArgumentsForCall - Collector argument expressions for various
7131  /// form of call prototypes.
7132  bool GatherArgumentsForCall(SourceLocation CallLoc,
7133                              FunctionDecl *FDecl,
7134                              const FunctionProtoType *Proto,
7135                              unsigned FirstProtoArg,
7136                              ArrayRef<Expr *> Args,
7137                              SmallVectorImpl<Expr *> &AllArgs,
7138                              VariadicCallType CallType = VariadicDoesNotApply,
7139                              bool AllowExplicit = false,
7140                              bool IsListInitialization = false);
7141
7142  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
7143  // will create a runtime trap if the resulting type is not a POD type.
7144  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
7145                                              FunctionDecl *FDecl);
7146
7147  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
7148  // operands and then handles various conversions that are common to binary
7149  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
7150  // routine returns the first non-arithmetic type found. The client is
7151  // responsible for emitting appropriate error diagnostics.
7152  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
7153                                      bool IsCompAssign = false);
7154
7155  /// AssignConvertType - All of the 'assignment' semantic checks return this
7156  /// enum to indicate whether the assignment was allowed.  These checks are
7157  /// done for simple assignments, as well as initialization, return from
7158  /// function, argument passing, etc.  The query is phrased in terms of a
7159  /// source and destination type.
7160  enum AssignConvertType {
7161    /// Compatible - the types are compatible according to the standard.
7162    Compatible,
7163
7164    /// PointerToInt - The assignment converts a pointer to an int, which we
7165    /// accept as an extension.
7166    PointerToInt,
7167
7168    /// IntToPointer - The assignment converts an int to a pointer, which we
7169    /// accept as an extension.
7170    IntToPointer,
7171
7172    /// FunctionVoidPointer - The assignment is between a function pointer and
7173    /// void*, which the standard doesn't allow, but we accept as an extension.
7174    FunctionVoidPointer,
7175
7176    /// IncompatiblePointer - The assignment is between two pointers types that
7177    /// are not compatible, but we accept them as an extension.
7178    IncompatiblePointer,
7179
7180    /// IncompatiblePointer - The assignment is between two pointers types which
7181    /// point to integers which have a different sign, but are otherwise
7182    /// identical. This is a subset of the above, but broken out because it's by
7183    /// far the most common case of incompatible pointers.
7184    IncompatiblePointerSign,
7185
7186    /// CompatiblePointerDiscardsQualifiers - The assignment discards
7187    /// c/v/r qualifiers, which we accept as an extension.
7188    CompatiblePointerDiscardsQualifiers,
7189
7190    /// IncompatiblePointerDiscardsQualifiers - The assignment
7191    /// discards qualifiers that we don't permit to be discarded,
7192    /// like address spaces.
7193    IncompatiblePointerDiscardsQualifiers,
7194
7195    /// IncompatibleNestedPointerQualifiers - The assignment is between two
7196    /// nested pointer types, and the qualifiers other than the first two
7197    /// levels differ e.g. char ** -> const char **, but we accept them as an
7198    /// extension.
7199    IncompatibleNestedPointerQualifiers,
7200
7201    /// IncompatibleVectors - The assignment is between two vector types that
7202    /// have the same size, which we accept as an extension.
7203    IncompatibleVectors,
7204
7205    /// IntToBlockPointer - The assignment converts an int to a block
7206    /// pointer. We disallow this.
7207    IntToBlockPointer,
7208
7209    /// IncompatibleBlockPointer - The assignment is between two block
7210    /// pointers types that are not compatible.
7211    IncompatibleBlockPointer,
7212
7213    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
7214    /// id type and something else (that is incompatible with it). For example,
7215    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
7216    IncompatibleObjCQualifiedId,
7217
7218    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
7219    /// object with __weak qualifier.
7220    IncompatibleObjCWeakRef,
7221
7222    /// Incompatible - We reject this conversion outright, it is invalid to
7223    /// represent it in the AST.
7224    Incompatible
7225  };
7226
7227  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
7228  /// assignment conversion type specified by ConvTy.  This returns true if the
7229  /// conversion was invalid or false if the conversion was accepted.
7230  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
7231                                SourceLocation Loc,
7232                                QualType DstType, QualType SrcType,
7233                                Expr *SrcExpr, AssignmentAction Action,
7234                                bool *Complained = 0);
7235
7236  /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
7237  /// integer not in the range of enum values.
7238  void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
7239                              Expr *SrcExpr);
7240
7241  /// CheckAssignmentConstraints - Perform type checking for assignment,
7242  /// argument passing, variable initialization, and function return values.
7243  /// C99 6.5.16.
7244  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
7245                                               QualType LHSType,
7246                                               QualType RHSType);
7247
7248  /// Check assignment constraints and prepare for a conversion of the
7249  /// RHS to the LHS type.
7250  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
7251                                               ExprResult &RHS,
7252                                               CastKind &Kind);
7253
7254  // CheckSingleAssignmentConstraints - Currently used by
7255  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
7256  // this routine performs the default function/array converions.
7257  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
7258                                                     ExprResult &RHS,
7259                                                     bool Diagnose = true,
7260                                                     bool DiagnoseCFAudited = false);
7261
7262  // \brief If the lhs type is a transparent union, check whether we
7263  // can initialize the transparent union with the given expression.
7264  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
7265                                                             ExprResult &RHS);
7266
7267  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
7268
7269  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
7270
7271  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7272                                       AssignmentAction Action,
7273                                       bool AllowExplicit = false);
7274  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7275                                       AssignmentAction Action,
7276                                       bool AllowExplicit,
7277                                       ImplicitConversionSequence& ICS);
7278  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7279                                       const ImplicitConversionSequence& ICS,
7280                                       AssignmentAction Action,
7281                                       CheckedConversionKind CCK
7282                                          = CCK_ImplicitConversion);
7283  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7284                                       const StandardConversionSequence& SCS,
7285                                       AssignmentAction Action,
7286                                       CheckedConversionKind CCK);
7287
7288  /// the following "Check" methods will return a valid/converted QualType
7289  /// or a null QualType (indicating an error diagnostic was issued).
7290
7291  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
7292  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7293                           ExprResult &RHS);
7294  QualType CheckPointerToMemberOperands( // C++ 5.5
7295    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7296    SourceLocation OpLoc, bool isIndirect);
7297  QualType CheckMultiplyDivideOperands( // C99 6.5.5
7298    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
7299    bool IsDivide);
7300  QualType CheckRemainderOperands( // C99 6.5.5
7301    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7302    bool IsCompAssign = false);
7303  QualType CheckAdditionOperands( // C99 6.5.6
7304    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7305    QualType* CompLHSTy = 0);
7306  QualType CheckSubtractionOperands( // C99 6.5.6
7307    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7308    QualType* CompLHSTy = 0);
7309  QualType CheckShiftOperands( // C99 6.5.7
7310    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7311    bool IsCompAssign = false);
7312  QualType CheckCompareOperands( // C99 6.5.8/9
7313    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
7314                                bool isRelational);
7315  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
7316    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7317    bool IsCompAssign = false);
7318  QualType CheckLogicalOperands( // C99 6.5.[13,14]
7319    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
7320  // CheckAssignmentOperands is used for both simple and compound assignment.
7321  // For simple assignment, pass both expressions and a null converted type.
7322  // For compound assignment, pass both expressions and the converted type.
7323  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
7324    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
7325
7326  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
7327                                     UnaryOperatorKind Opcode, Expr *Op);
7328  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
7329                                         BinaryOperatorKind Opcode,
7330                                         Expr *LHS, Expr *RHS);
7331  ExprResult checkPseudoObjectRValue(Expr *E);
7332  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
7333
7334  QualType CheckConditionalOperands( // C99 6.5.15
7335    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
7336    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
7337  QualType CXXCheckConditionalOperands( // C++ 5.16
7338    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
7339    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
7340  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
7341                                    bool *NonStandardCompositeType = 0);
7342  QualType FindCompositePointerType(SourceLocation Loc,
7343                                    ExprResult &E1, ExprResult &E2,
7344                                    bool *NonStandardCompositeType = 0) {
7345    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
7346    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
7347                                                  NonStandardCompositeType);
7348    E1 = Owned(E1Tmp);
7349    E2 = Owned(E2Tmp);
7350    return Composite;
7351  }
7352
7353  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7354                                        SourceLocation QuestionLoc);
7355
7356  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7357                                  SourceLocation QuestionLoc);
7358
7359  /// type checking for vector binary operators.
7360  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7361                               SourceLocation Loc, bool IsCompAssign);
7362  QualType GetSignedVectorType(QualType V);
7363  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7364                                      SourceLocation Loc, bool isRelational);
7365  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7366                                      SourceLocation Loc);
7367
7368  /// type checking declaration initializers (C99 6.7.8)
7369  bool CheckForConstantInitializer(Expr *e, QualType t);
7370
7371  // type checking C++ declaration initializers (C++ [dcl.init]).
7372
7373  /// ReferenceCompareResult - Expresses the result of comparing two
7374  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
7375  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
7376  enum ReferenceCompareResult {
7377    /// Ref_Incompatible - The two types are incompatible, so direct
7378    /// reference binding is not possible.
7379    Ref_Incompatible = 0,
7380    /// Ref_Related - The two types are reference-related, which means
7381    /// that their unqualified forms (T1 and T2) are either the same
7382    /// or T1 is a base class of T2.
7383    Ref_Related,
7384    /// Ref_Compatible_With_Added_Qualification - The two types are
7385    /// reference-compatible with added qualification, meaning that
7386    /// they are reference-compatible and the qualifiers on T1 (cv1)
7387    /// are greater than the qualifiers on T2 (cv2).
7388    Ref_Compatible_With_Added_Qualification,
7389    /// Ref_Compatible - The two types are reference-compatible and
7390    /// have equivalent qualifiers (cv1 == cv2).
7391    Ref_Compatible
7392  };
7393
7394  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
7395                                                      QualType T1, QualType T2,
7396                                                      bool &DerivedToBase,
7397                                                      bool &ObjCConversion,
7398                                                bool &ObjCLifetimeConversion);
7399
7400  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7401                                 Expr *CastExpr, CastKind &CastKind,
7402                                 ExprValueKind &VK, CXXCastPath &Path);
7403
7404  /// \brief Force an expression with unknown-type to an expression of the
7405  /// given type.
7406  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7407
7408  /// \brief Type-check an expression that's being passed to an
7409  /// __unknown_anytype parameter.
7410  ExprResult checkUnknownAnyArg(SourceLocation callLoc,
7411                                Expr *result, QualType &paramType);
7412
7413  // CheckVectorCast - check type constraints for vectors.
7414  // Since vectors are an extension, there are no C standard reference for this.
7415  // We allow casting between vectors and integer datatypes of the same size.
7416  // returns true if the cast is invalid
7417  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7418                       CastKind &Kind);
7419
7420  // CheckExtVectorCast - check type constraints for extended vectors.
7421  // Since vectors are an extension, there are no C standard reference for this.
7422  // We allow casting between vectors and integer datatypes of the same size,
7423  // or vectors and the element type of that vector.
7424  // returns the cast expr
7425  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7426                                CastKind &Kind);
7427
7428  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
7429                                        SourceLocation LParenLoc,
7430                                        Expr *CastExpr,
7431                                        SourceLocation RParenLoc);
7432
7433  enum ARCConversionResult { ACR_okay, ACR_unbridged };
7434
7435  /// \brief Checks for invalid conversions and casts between
7436  /// retainable pointers and other pointer kinds.
7437  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
7438                                             QualType castType, Expr *&op,
7439                                             CheckedConversionKind CCK,
7440                                             bool DiagnoseCFAudited = false);
7441
7442  Expr *stripARCUnbridgedCast(Expr *e);
7443  void diagnoseARCUnbridgedCast(Expr *e);
7444
7445  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7446                                             QualType ExprType);
7447
7448  /// checkRetainCycles - Check whether an Objective-C message send
7449  /// might create an obvious retain cycle.
7450  void checkRetainCycles(ObjCMessageExpr *msg);
7451  void checkRetainCycles(Expr *receiver, Expr *argument);
7452  void checkRetainCycles(VarDecl *Var, Expr *Init);
7453
7454  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7455  /// to weak/__unsafe_unretained type.
7456  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7457
7458  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7459  /// to weak/__unsafe_unretained expression.
7460  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7461
7462  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7463  /// \param Method - May be null.
7464  /// \param [out] ReturnType - The return type of the send.
7465  /// \return true iff there were any incompatible types.
7466  bool CheckMessageArgumentTypes(QualType ReceiverType,
7467                                 MultiExprArg Args, Selector Sel,
7468                                 ArrayRef<SourceLocation> SelectorLocs,
7469                                 ObjCMethodDecl *Method, bool isClassMessage,
7470                                 bool isSuperMessage,
7471                                 SourceLocation lbrac, SourceLocation rbrac,
7472                                 QualType &ReturnType, ExprValueKind &VK);
7473
7474  /// \brief Determine the result of a message send expression based on
7475  /// the type of the receiver, the method expected to receive the message,
7476  /// and the form of the message send.
7477  QualType getMessageSendResultType(QualType ReceiverType,
7478                                    ObjCMethodDecl *Method,
7479                                    bool isClassMessage, bool isSuperMessage);
7480
7481  /// \brief If the given expression involves a message send to a method
7482  /// with a related result type, emit a note describing what happened.
7483  void EmitRelatedResultTypeNote(const Expr *E);
7484
7485  /// \brief Given that we had incompatible pointer types in a return
7486  /// statement, check whether we're in a method with a related result
7487  /// type, and if so, emit a note describing what happened.
7488  void EmitRelatedResultTypeNoteForReturn(QualType destType);
7489
7490  /// CheckBooleanCondition - Diagnose problems involving the use of
7491  /// the given expression as a boolean condition (e.g. in an if
7492  /// statement).  Also performs the standard function and array
7493  /// decays, possibly changing the input variable.
7494  ///
7495  /// \param Loc - A location associated with the condition, e.g. the
7496  /// 'if' keyword.
7497  /// \return true iff there were any errors
7498  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7499
7500  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7501                                   Expr *SubExpr);
7502
7503  /// DiagnoseAssignmentAsCondition - Given that an expression is
7504  /// being used as a boolean condition, warn if it's an assignment.
7505  void DiagnoseAssignmentAsCondition(Expr *E);
7506
7507  /// \brief Redundant parentheses over an equality comparison can indicate
7508  /// that the user intended an assignment used as condition.
7509  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7510
7511  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7512  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7513
7514  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7515  /// the specified width and sign.  If an overflow occurs, detect it and emit
7516  /// the specified diagnostic.
7517  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7518                                          unsigned NewWidth, bool NewSign,
7519                                          SourceLocation Loc, unsigned DiagID);
7520
7521  /// Checks that the Objective-C declaration is declared in the global scope.
7522  /// Emits an error and marks the declaration as invalid if it's not declared
7523  /// in the global scope.
7524  bool CheckObjCDeclScope(Decl *D);
7525
7526  /// \brief Abstract base class used for diagnosing integer constant
7527  /// expression violations.
7528  class VerifyICEDiagnoser {
7529  public:
7530    bool Suppress;
7531
7532    VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7533
7534    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7535    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
7536    virtual ~VerifyICEDiagnoser() { }
7537  };
7538
7539  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7540  /// and reports the appropriate diagnostics. Returns false on success.
7541  /// Can optionally return the value of the expression.
7542  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7543                                             VerifyICEDiagnoser &Diagnoser,
7544                                             bool AllowFold = true);
7545  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7546                                             unsigned DiagID,
7547                                             bool AllowFold = true);
7548  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
7549
7550  /// VerifyBitField - verifies that a bit field expression is an ICE and has
7551  /// the correct width, and that the field type is valid.
7552  /// Returns false on success.
7553  /// Can optionally return whether the bit-field is of width 0
7554  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
7555                            QualType FieldTy, bool IsMsStruct,
7556                            Expr *BitWidth, bool *ZeroWidth = 0);
7557
7558  enum CUDAFunctionTarget {
7559    CFT_Device,
7560    CFT_Global,
7561    CFT_Host,
7562    CFT_HostDevice
7563  };
7564
7565  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
7566
7567  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
7568                       CUDAFunctionTarget CalleeTarget);
7569
7570  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
7571    return CheckCUDATarget(IdentifyCUDATarget(Caller),
7572                           IdentifyCUDATarget(Callee));
7573  }
7574
7575  /// \name Code completion
7576  //@{
7577  /// \brief Describes the context in which code completion occurs.
7578  enum ParserCompletionContext {
7579    /// \brief Code completion occurs at top-level or namespace context.
7580    PCC_Namespace,
7581    /// \brief Code completion occurs within a class, struct, or union.
7582    PCC_Class,
7583    /// \brief Code completion occurs within an Objective-C interface, protocol,
7584    /// or category.
7585    PCC_ObjCInterface,
7586    /// \brief Code completion occurs within an Objective-C implementation or
7587    /// category implementation
7588    PCC_ObjCImplementation,
7589    /// \brief Code completion occurs within the list of instance variables
7590    /// in an Objective-C interface, protocol, category, or implementation.
7591    PCC_ObjCInstanceVariableList,
7592    /// \brief Code completion occurs following one or more template
7593    /// headers.
7594    PCC_Template,
7595    /// \brief Code completion occurs following one or more template
7596    /// headers within a class.
7597    PCC_MemberTemplate,
7598    /// \brief Code completion occurs within an expression.
7599    PCC_Expression,
7600    /// \brief Code completion occurs within a statement, which may
7601    /// also be an expression or a declaration.
7602    PCC_Statement,
7603    /// \brief Code completion occurs at the beginning of the
7604    /// initialization statement (or expression) in a for loop.
7605    PCC_ForInit,
7606    /// \brief Code completion occurs within the condition of an if,
7607    /// while, switch, or for statement.
7608    PCC_Condition,
7609    /// \brief Code completion occurs within the body of a function on a
7610    /// recovery path, where we do not have a specific handle on our position
7611    /// in the grammar.
7612    PCC_RecoveryInFunction,
7613    /// \brief Code completion occurs where only a type is permitted.
7614    PCC_Type,
7615    /// \brief Code completion occurs in a parenthesized expression, which
7616    /// might also be a type cast.
7617    PCC_ParenthesizedExpression,
7618    /// \brief Code completion occurs within a sequence of declaration
7619    /// specifiers within a function, method, or block.
7620    PCC_LocalDeclarationSpecifiers
7621  };
7622
7623  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
7624  void CodeCompleteOrdinaryName(Scope *S,
7625                                ParserCompletionContext CompletionContext);
7626  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
7627                            bool AllowNonIdentifiers,
7628                            bool AllowNestedNameSpecifiers);
7629
7630  struct CodeCompleteExpressionData;
7631  void CodeCompleteExpression(Scope *S,
7632                              const CodeCompleteExpressionData &Data);
7633  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
7634                                       SourceLocation OpLoc,
7635                                       bool IsArrow);
7636  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
7637  void CodeCompleteTag(Scope *S, unsigned TagSpec);
7638  void CodeCompleteTypeQualifiers(DeclSpec &DS);
7639  void CodeCompleteCase(Scope *S);
7640  void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
7641  void CodeCompleteInitializer(Scope *S, Decl *D);
7642  void CodeCompleteReturn(Scope *S);
7643  void CodeCompleteAfterIf(Scope *S);
7644  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
7645
7646  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
7647                               bool EnteringContext);
7648  void CodeCompleteUsing(Scope *S);
7649  void CodeCompleteUsingDirective(Scope *S);
7650  void CodeCompleteNamespaceDecl(Scope *S);
7651  void CodeCompleteNamespaceAliasDecl(Scope *S);
7652  void CodeCompleteOperatorName(Scope *S);
7653  void CodeCompleteConstructorInitializer(
7654                                Decl *Constructor,
7655                                ArrayRef<CXXCtorInitializer *> Initializers);
7656
7657  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7658                                    bool AfterAmpersand);
7659
7660  void CodeCompleteObjCAtDirective(Scope *S);
7661  void CodeCompleteObjCAtVisibility(Scope *S);
7662  void CodeCompleteObjCAtStatement(Scope *S);
7663  void CodeCompleteObjCAtExpression(Scope *S);
7664  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
7665  void CodeCompleteObjCPropertyGetter(Scope *S);
7666  void CodeCompleteObjCPropertySetter(Scope *S);
7667  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7668                                   bool IsParameter);
7669  void CodeCompleteObjCMessageReceiver(Scope *S);
7670  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7671                                    ArrayRef<IdentifierInfo *> SelIdents,
7672                                    bool AtArgumentExpression);
7673  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7674                                    ArrayRef<IdentifierInfo *> SelIdents,
7675                                    bool AtArgumentExpression,
7676                                    bool IsSuper = false);
7677  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7678                                       ArrayRef<IdentifierInfo *> SelIdents,
7679                                       bool AtArgumentExpression,
7680                                       ObjCInterfaceDecl *Super = 0);
7681  void CodeCompleteObjCForCollection(Scope *S,
7682                                     DeclGroupPtrTy IterationVar);
7683  void CodeCompleteObjCSelector(Scope *S,
7684                                ArrayRef<IdentifierInfo *> SelIdents);
7685  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7686                                          unsigned NumProtocols);
7687  void CodeCompleteObjCProtocolDecl(Scope *S);
7688  void CodeCompleteObjCInterfaceDecl(Scope *S);
7689  void CodeCompleteObjCSuperclass(Scope *S,
7690                                  IdentifierInfo *ClassName,
7691                                  SourceLocation ClassNameLoc);
7692  void CodeCompleteObjCImplementationDecl(Scope *S);
7693  void CodeCompleteObjCInterfaceCategory(Scope *S,
7694                                         IdentifierInfo *ClassName,
7695                                         SourceLocation ClassNameLoc);
7696  void CodeCompleteObjCImplementationCategory(Scope *S,
7697                                              IdentifierInfo *ClassName,
7698                                              SourceLocation ClassNameLoc);
7699  void CodeCompleteObjCPropertyDefinition(Scope *S);
7700  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7701                                              IdentifierInfo *PropertyName);
7702  void CodeCompleteObjCMethodDecl(Scope *S,
7703                                  bool IsInstanceMethod,
7704                                  ParsedType ReturnType);
7705  void CodeCompleteObjCMethodDeclSelector(Scope *S,
7706                                          bool IsInstanceMethod,
7707                                          bool AtParameterName,
7708                                          ParsedType ReturnType,
7709                                          ArrayRef<IdentifierInfo *> SelIdents);
7710  void CodeCompletePreprocessorDirective(bool InConditional);
7711  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7712  void CodeCompletePreprocessorMacroName(bool IsDefinition);
7713  void CodeCompletePreprocessorExpression();
7714  void CodeCompletePreprocessorMacroArgument(Scope *S,
7715                                             IdentifierInfo *Macro,
7716                                             MacroInfo *MacroInfo,
7717                                             unsigned Argument);
7718  void CodeCompleteNaturalLanguage();
7719  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7720                                   CodeCompletionTUInfo &CCTUInfo,
7721                  SmallVectorImpl<CodeCompletionResult> &Results);
7722  //@}
7723
7724  //===--------------------------------------------------------------------===//
7725  // Extra semantic analysis beyond the C type system
7726
7727public:
7728  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7729                                                unsigned ByteNo) const;
7730
7731private:
7732  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7733                        const ArraySubscriptExpr *ASE=0,
7734                        bool AllowOnePastEnd=true, bool IndexNegated=false);
7735  void CheckArrayAccess(const Expr *E);
7736  // Used to grab the relevant information from a FormatAttr and a
7737  // FunctionDeclaration.
7738  struct FormatStringInfo {
7739    unsigned FormatIdx;
7740    unsigned FirstDataArg;
7741    bool HasVAListArg;
7742  };
7743
7744  bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7745                           FormatStringInfo *FSI);
7746  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7747                         const FunctionProtoType *Proto);
7748  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7749                           ArrayRef<const Expr *> Args);
7750  bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
7751                        const FunctionProtoType *Proto);
7752  bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
7753  void CheckConstructorCall(FunctionDecl *FDecl,
7754                            ArrayRef<const Expr *> Args,
7755                            const FunctionProtoType *Proto,
7756                            SourceLocation Loc);
7757
7758  void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
7759                 unsigned NumProtoArgs, bool IsMemberFunction,
7760                 SourceLocation Loc, SourceRange Range,
7761                 VariadicCallType CallType);
7762
7763
7764  bool CheckObjCString(Expr *Arg);
7765
7766  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7767
7768  bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall);
7769  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7770  bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7771  bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7772
7773  bool SemaBuiltinVAStart(CallExpr *TheCall);
7774  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7775  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7776
7777public:
7778  // Used by C++ template instantiation.
7779  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7780  ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7781                                   SourceLocation BuiltinLoc,
7782                                   SourceLocation RParenLoc);
7783
7784private:
7785  bool SemaBuiltinPrefetch(CallExpr *TheCall);
7786  bool SemaBuiltinObjectSize(CallExpr *TheCall);
7787  bool SemaBuiltinLongjmp(CallExpr *TheCall);
7788  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7789  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7790                                     AtomicExpr::AtomicOp Op);
7791  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7792                              llvm::APSInt &Result);
7793
7794public:
7795  enum FormatStringType {
7796    FST_Scanf,
7797    FST_Printf,
7798    FST_NSString,
7799    FST_Strftime,
7800    FST_Strfmon,
7801    FST_Kprintf,
7802    FST_Unknown
7803  };
7804  static FormatStringType GetFormatStringType(const FormatAttr *Format);
7805
7806  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7807                         ArrayRef<const Expr *> Args, bool HasVAListArg,
7808                         unsigned format_idx, unsigned firstDataArg,
7809                         FormatStringType Type, bool inFunctionCall,
7810                         VariadicCallType CallType,
7811                         llvm::SmallBitVector &CheckedVarArgs);
7812
7813private:
7814  bool CheckFormatArguments(const FormatAttr *Format,
7815                            ArrayRef<const Expr *> Args,
7816                            bool IsCXXMember,
7817                            VariadicCallType CallType,
7818                            SourceLocation Loc, SourceRange Range,
7819                            llvm::SmallBitVector &CheckedVarArgs);
7820  bool CheckFormatArguments(ArrayRef<const Expr *> Args,
7821                            bool HasVAListArg, unsigned format_idx,
7822                            unsigned firstDataArg, FormatStringType Type,
7823                            VariadicCallType CallType,
7824                            SourceLocation Loc, SourceRange range,
7825                            llvm::SmallBitVector &CheckedVarArgs);
7826
7827  void CheckNonNullArguments(const NonNullAttr *NonNull,
7828                             const Expr * const *ExprArgs,
7829                             SourceLocation CallSiteLoc);
7830
7831  void CheckMemaccessArguments(const CallExpr *Call,
7832                               unsigned BId,
7833                               IdentifierInfo *FnName);
7834
7835  void CheckStrlcpycatArguments(const CallExpr *Call,
7836                                IdentifierInfo *FnName);
7837
7838  void CheckStrncatArguments(const CallExpr *Call,
7839                             IdentifierInfo *FnName);
7840
7841  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7842                            SourceLocation ReturnLoc);
7843  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7844  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7845  void CheckForIntOverflow(Expr *E);
7846  void CheckUnsequencedOperations(Expr *E);
7847
7848  /// \brief Perform semantic checks on a completed expression. This will either
7849  /// be a full-expression or a default argument expression.
7850  void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
7851                          bool IsConstexpr = false);
7852
7853  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7854                                   Expr *Init);
7855
7856public:
7857  /// \brief Register a magic integral constant to be used as a type tag.
7858  void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7859                                  uint64_t MagicValue, QualType Type,
7860                                  bool LayoutCompatible, bool MustBeNull);
7861
7862  struct TypeTagData {
7863    TypeTagData() {}
7864
7865    TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7866        Type(Type), LayoutCompatible(LayoutCompatible),
7867        MustBeNull(MustBeNull)
7868    {}
7869
7870    QualType Type;
7871
7872    /// If true, \c Type should be compared with other expression's types for
7873    /// layout-compatibility.
7874    unsigned LayoutCompatible : 1;
7875    unsigned MustBeNull : 1;
7876  };
7877
7878  /// A pair of ArgumentKind identifier and magic value.  This uniquely
7879  /// identifies the magic value.
7880  typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7881
7882private:
7883  /// \brief A map from magic value to type information.
7884  OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7885      TypeTagForDatatypeMagicValues;
7886
7887  /// \brief Peform checks on a call of a function with argument_with_type_tag
7888  /// or pointer_with_type_tag attributes.
7889  void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7890                                const Expr * const *ExprArgs);
7891
7892  /// \brief The parser's current scope.
7893  ///
7894  /// The parser maintains this state here.
7895  Scope *CurScope;
7896
7897  mutable IdentifierInfo *Ident_super;
7898  mutable IdentifierInfo *Ident___float128;
7899
7900protected:
7901  friend class Parser;
7902  friend class InitializationSequence;
7903  friend class ASTReader;
7904  friend class ASTWriter;
7905
7906public:
7907  /// \brief Retrieve the parser's current scope.
7908  ///
7909  /// This routine must only be used when it is certain that semantic analysis
7910  /// and the parser are in precisely the same context, which is not the case
7911  /// when, e.g., we are performing any kind of template instantiation.
7912  /// Therefore, the only safe places to use this scope are in the parser
7913  /// itself and in routines directly invoked from the parser and *never* from
7914  /// template substitution or instantiation.
7915  Scope *getCurScope() const { return CurScope; }
7916
7917  IdentifierInfo *getSuperIdentifier() const;
7918  IdentifierInfo *getFloat128Identifier() const;
7919
7920  Decl *getObjCDeclContext() const;
7921
7922  DeclContext *getCurLexicalContext() const {
7923    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
7924  }
7925
7926  AvailabilityResult getCurContextAvailability() const;
7927
7928  const DeclContext *getCurObjCLexicalContext() const {
7929    const DeclContext *DC = getCurLexicalContext();
7930    // A category implicitly has the attribute of the interface.
7931    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
7932      DC = CatD->getClassInterface();
7933    return DC;
7934  }
7935};
7936
7937/// \brief RAII object that enters a new expression evaluation context.
7938class EnterExpressionEvaluationContext {
7939  Sema &Actions;
7940
7941public:
7942  EnterExpressionEvaluationContext(Sema &Actions,
7943                                   Sema::ExpressionEvaluationContext NewContext,
7944                                   Decl *LambdaContextDecl = 0,
7945                                   bool IsDecltype = false)
7946    : Actions(Actions) {
7947    Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
7948                                            IsDecltype);
7949  }
7950  EnterExpressionEvaluationContext(Sema &Actions,
7951                                   Sema::ExpressionEvaluationContext NewContext,
7952                                   Sema::ReuseLambdaContextDecl_t,
7953                                   bool IsDecltype = false)
7954    : Actions(Actions) {
7955    Actions.PushExpressionEvaluationContext(NewContext,
7956                                            Sema::ReuseLambdaContextDecl,
7957                                            IsDecltype);
7958  }
7959
7960  ~EnterExpressionEvaluationContext() {
7961    Actions.PopExpressionEvaluationContext();
7962  }
7963};
7964
7965DeductionFailureInfo
7966MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
7967                         sema::TemplateDeductionInfo &Info);
7968
7969/// \brief Contains a late templated function.
7970/// Will be parsed at the end of the translation unit, used by Sema & Parser.
7971struct LateParsedTemplate {
7972  CachedTokens Toks;
7973  /// \brief The template function declaration to be late parsed.
7974  Decl *D;
7975};
7976
7977} // end namespace clang
7978
7979#endif
7980