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