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