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