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