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