Sema.h revision 1d752d7d68359fd8f7701585d4658aa70e129261
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/AST/Expr.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Specifiers.h"
28#include "clang/Basic/TemplateKinds.h"
29#include "clang/Basic/TypeTraits.h"
30#include "llvm/ADT/OwningPtr.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include <deque>
34#include <string>
35
36namespace llvm {
37  class APSInt;
38  template <typename ValueT> struct DenseMapInfo;
39  template <typename ValueT, typename ValueInfoT> class DenseSet;
40}
41
42namespace clang {
43  class ADLResult;
44  class ASTConsumer;
45  class ASTContext;
46  class ArrayType;
47  class AttributeList;
48  class BlockDecl;
49  class CXXBasePath;
50  class CXXBasePaths;
51  typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
52  class CXXConstructorDecl;
53  class CXXConversionDecl;
54  class CXXDestructorDecl;
55  class CXXFieldCollector;
56  class CXXMemberCallExpr;
57  class CXXMethodDecl;
58  class CXXScopeSpec;
59  class CXXTemporary;
60  class CXXTryStmt;
61  class CallExpr;
62  class ClassTemplateDecl;
63  class ClassTemplatePartialSpecializationDecl;
64  class ClassTemplateSpecializationDecl;
65  class CodeCompleteConsumer;
66  class CodeCompletionAllocator;
67  class CodeCompletionResult;
68  class Decl;
69  class DeclAccessPair;
70  class DeclContext;
71  class DeclRefExpr;
72  class DeclaratorDecl;
73  class DeducedTemplateArgument;
74  class DependentDiagnostic;
75  class DesignatedInitExpr;
76  class Designation;
77  class EnumConstantDecl;
78  class Expr;
79  class ExtVectorType;
80  class ExternalSemaSource;
81  class FormatAttr;
82  class FriendDecl;
83  class FunctionDecl;
84  class FunctionProtoType;
85  class FunctionTemplateDecl;
86  class ImplicitConversionSequence;
87  class InitListExpr;
88  class InitializationKind;
89  class InitializationSequence;
90  class InitializedEntity;
91  class IntegerLiteral;
92  class LabelStmt;
93  class LangOptions;
94  class LocalInstantiationScope;
95  class LookupResult;
96  class MacroInfo;
97  class MultiLevelTemplateArgumentList;
98  class NamedDecl;
99  class NonNullAttr;
100  class ObjCCategoryDecl;
101  class ObjCCategoryImplDecl;
102  class ObjCCompatibleAliasDecl;
103  class ObjCContainerDecl;
104  class ObjCImplDecl;
105  class ObjCImplementationDecl;
106  class ObjCInterfaceDecl;
107  class ObjCIvarDecl;
108  template <class T> class ObjCList;
109  class ObjCMethodDecl;
110  class ObjCPropertyDecl;
111  class ObjCProtocolDecl;
112  class OverloadCandidateSet;
113  class ParenListExpr;
114  class ParmVarDecl;
115  class Preprocessor;
116  class PseudoDestructorTypeStorage;
117  class QualType;
118  class StandardConversionSequence;
119  class Stmt;
120  class StringLiteral;
121  class SwitchStmt;
122  class TargetAttributesSema;
123  class TemplateArgument;
124  class TemplateArgumentList;
125  class TemplateArgumentLoc;
126  class TemplateDecl;
127  class TemplateParameterList;
128  class TemplatePartialOrderingContext;
129  class TemplateTemplateParmDecl;
130  class Token;
131  class TypedefDecl;
132  class TypeLoc;
133  class UnqualifiedId;
134  class UnresolvedLookupExpr;
135  class UnresolvedMemberExpr;
136  class UnresolvedSetImpl;
137  class UnresolvedSetIterator;
138  class UsingDecl;
139  class UsingShadowDecl;
140  class ValueDecl;
141  class VarDecl;
142  class VisibilityAttr;
143  class VisibleDeclConsumer;
144  class IndirectFieldDecl;
145
146namespace sema {
147  class AccessedEntity;
148  class BlockScopeInfo;
149  class DelayedDiagnostic;
150  class FunctionScopeInfo;
151  class TemplateDeductionInfo;
152}
153
154/// \brief Holds a QualType and a TypeSourceInfo* that came out of a declarator
155/// parsing.
156///
157/// LocInfoType is a "transient" type, only needed for passing to/from Parser
158/// and Sema, when we want to preserve type source info for a parsed type.
159/// It will not participate in the type system semantics in any way.
160class LocInfoType : public Type {
161  enum {
162    // The last number that can fit in Type's TC.
163    // Avoids conflict with an existing Type class.
164    LocInfo = Type::TypeLast + 1
165  };
166
167  TypeSourceInfo *DeclInfo;
168
169  LocInfoType(QualType ty, TypeSourceInfo *TInfo)
170    : Type((TypeClass)LocInfo, ty, ty->isDependentType(),
171           ty->isVariablyModifiedType(),
172           ty->containsUnexpandedParameterPack()),
173      DeclInfo(TInfo) {
174    assert(getTypeClass() == (TypeClass)LocInfo && "LocInfo didn't fit in TC?");
175  }
176  friend class Sema;
177
178public:
179  QualType getType() const { return getCanonicalTypeInternal(); }
180  TypeSourceInfo *getTypeSourceInfo() const { return DeclInfo; }
181
182  void getAsStringInternal(std::string &Str,
183                                   const PrintingPolicy &Policy) const;
184
185  static bool classof(const Type *T) {
186    return T->getTypeClass() == (TypeClass)LocInfo;
187  }
188  static bool classof(const LocInfoType *) { return true; }
189};
190
191// FIXME: No way to easily map from TemplateTypeParmTypes to
192// TemplateTypeParmDecls, so we have this horrible PointerUnion.
193typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
194                  SourceLocation> UnexpandedParameterPack;
195
196/// Sema - This implements semantic analysis and AST building for C.
197class Sema {
198  Sema(const Sema&);           // DO NOT IMPLEMENT
199  void operator=(const Sema&); // DO NOT IMPLEMENT
200  mutable const TargetAttributesSema* TheTargetAttributesSema;
201public:
202  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
203  typedef OpaquePtr<TemplateName> TemplateTy;
204  typedef OpaquePtr<QualType> TypeTy;
205  typedef Attr AttrTy;
206  typedef CXXBaseSpecifier BaseTy;
207  typedef CXXCtorInitializer MemInitTy;
208  typedef Expr ExprTy;
209  typedef Stmt StmtTy;
210  typedef TemplateParameterList TemplateParamsTy;
211  typedef NestedNameSpecifier CXXScopeTy;
212
213  OpenCLOptions OpenCLFeatures;
214  FPOptions FPFeatures;
215
216  const LangOptions &LangOpts;
217  Preprocessor &PP;
218  ASTContext &Context;
219  ASTConsumer &Consumer;
220  Diagnostic &Diags;
221  SourceManager &SourceMgr;
222
223  /// \brief Source of additional semantic information.
224  ExternalSemaSource *ExternalSource;
225
226  /// \brief Code-completion consumer.
227  CodeCompleteConsumer *CodeCompleter;
228
229  /// CurContext - This is the current declaration context of parsing.
230  DeclContext *CurContext;
231
232  /// VAListTagName - The declaration name corresponding to __va_list_tag.
233  /// This is used as part of a hack to omit that class from ADL results.
234  DeclarationName VAListTagName;
235
236  /// PackContext - Manages the stack for #pragma pack. An alignment
237  /// of 0 indicates default alignment.
238  void *PackContext; // Really a "PragmaPackStack*"
239
240  /// VisContext - Manages the stack for #pragma GCC visibility.
241  void *VisContext; // Really a "PragmaVisStack*"
242
243  /// \brief Stack containing information about each of the nested
244  /// function, block, and method scopes that are currently active.
245  ///
246  /// This array is never empty.  Clients should ignore the first
247  /// element, which is used to cache a single FunctionScopeInfo
248  /// that's used to parse every top-level function.
249  llvm::SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
250
251  /// ExprTemporaries - This is the stack of temporaries that are created by
252  /// the current full expression.
253  llvm::SmallVector<CXXTemporary*, 8> ExprTemporaries;
254
255  /// ExtVectorDecls - This is a list all the extended vector types. This allows
256  /// us to associate a raw vector type with one of the ext_vector type names.
257  /// This is only necessary for issuing pretty diagnostics.
258  llvm::SmallVector<TypedefDecl*, 24> ExtVectorDecls;
259
260  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
261  llvm::OwningPtr<CXXFieldCollector> FieldCollector;
262
263  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
264
265  /// PureVirtualClassDiagSet - a set of class declarations which we have
266  /// emitted a list of pure virtual functions. Used to prevent emitting the
267  /// same list more than once.
268  llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
269
270  /// ParsingInitForAutoVars - a set of declarations with auto types for which
271  /// we are currently parsing the initializer.
272  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
273
274  /// \brief A mapping from external names to the most recent
275  /// locally-scoped external declaration with that name.
276  ///
277  /// This map contains external declarations introduced in local
278  /// scoped, e.g.,
279  ///
280  /// \code
281  /// void f() {
282  ///   void foo(int, int);
283  /// }
284  /// \endcode
285  ///
286  /// Here, the name "foo" will be associated with the declaration on
287  /// "foo" within f. This name is not visible outside of
288  /// "f". However, we still find it in two cases:
289  ///
290  ///   - If we are declaring another external with the name "foo", we
291  ///     can find "foo" as a previous declaration, so that the types
292  ///     of this external declaration can be checked for
293  ///     compatibility.
294  ///
295  ///   - If we would implicitly declare "foo" (e.g., due to a call to
296  ///     "foo" in C when no prototype or definition is visible), then
297  ///     we find this declaration of "foo" and complain that it is
298  ///     not visible.
299  llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls;
300
301  /// \brief All the tentative definitions encountered in the TU.
302  llvm::SmallVector<VarDecl *, 2> TentativeDefinitions;
303
304  /// \brief The set of file scoped decls seen so far that have not been used
305  /// and must warn if not used. Only contains the first declaration.
306  llvm::SmallVector<const DeclaratorDecl*, 4> UnusedFileScopedDecls;
307
308  class DelayedDiagnostics;
309
310  class ParsingDeclState {
311    unsigned SavedStackSize;
312    friend class Sema::DelayedDiagnostics;
313  };
314
315  class ProcessingContextState {
316    unsigned SavedParsingDepth;
317    unsigned SavedActiveStackBase;
318    friend class Sema::DelayedDiagnostics;
319  };
320
321  /// A class which encapsulates the logic for delaying diagnostics
322  /// during parsing and other processing.
323  class DelayedDiagnostics {
324    /// \brief The stack of diagnostics that were delayed due to being
325    /// produced during the parsing of a declaration.
326    sema::DelayedDiagnostic *Stack;
327
328    /// \brief The number of objects on the delayed-diagnostics stack.
329    unsigned StackSize;
330
331    /// \brief The current capacity of the delayed-diagnostics stack.
332    unsigned StackCapacity;
333
334    /// \brief The index of the first "active" delayed diagnostic in
335    /// the stack.  When parsing class definitions, we ignore active
336    /// delayed diagnostics from the surrounding context.
337    unsigned ActiveStackBase;
338
339    /// \brief The depth of the declarations we're currently parsing.
340    /// This gets saved and reset whenever we enter a class definition.
341    unsigned ParsingDepth;
342
343  public:
344    DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0),
345      ActiveStackBase(0), ParsingDepth(0) {}
346
347    ~DelayedDiagnostics() {
348      delete[] reinterpret_cast<char*>(Stack);
349    }
350
351    /// Adds a delayed diagnostic.
352    void add(const sema::DelayedDiagnostic &diag);
353
354    /// Determines whether diagnostics should be delayed.
355    bool shouldDelayDiagnostics() { return ParsingDepth > 0; }
356
357    /// Observe that we've started parsing a declaration.  Access and
358    /// deprecation diagnostics will be delayed; when the declaration
359    /// is completed, all active delayed diagnostics will be evaluated
360    /// in its context, and then active diagnostics stack will be
361    /// popped down to the saved depth.
362    ParsingDeclState pushParsingDecl() {
363      ParsingDepth++;
364
365      ParsingDeclState state;
366      state.SavedStackSize = StackSize;
367      return state;
368    }
369
370    /// Observe that we're completed parsing a declaration.
371    static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl);
372
373    /// Observe that we've started processing a different context, the
374    /// contents of which are semantically separate from the
375    /// declarations it may lexically appear in.  This sets aside the
376    /// current stack of active diagnostics and starts afresh.
377    ProcessingContextState pushContext() {
378      assert(StackSize >= ActiveStackBase);
379
380      ProcessingContextState state;
381      state.SavedParsingDepth = ParsingDepth;
382      state.SavedActiveStackBase = ActiveStackBase;
383
384      ActiveStackBase = StackSize;
385      ParsingDepth = 0;
386
387      return state;
388    }
389
390    /// Observe that we've stopped processing a context.  This
391    /// restores the previous stack of active diagnostics.
392    void popContext(ProcessingContextState state) {
393      assert(ActiveStackBase == StackSize);
394      assert(ParsingDepth == 0);
395      ActiveStackBase = state.SavedActiveStackBase;
396      ParsingDepth = state.SavedParsingDepth;
397    }
398  } DelayedDiagnostics;
399
400  /// A RAII object to temporarily push a declaration context.
401  class ContextRAII {
402  private:
403    Sema &S;
404    DeclContext *SavedContext;
405    ProcessingContextState SavedContextState;
406
407  public:
408    ContextRAII(Sema &S, DeclContext *ContextToPush)
409      : S(S), SavedContext(S.CurContext),
410        SavedContextState(S.DelayedDiagnostics.pushContext())
411    {
412      assert(ContextToPush && "pushing null context");
413      S.CurContext = ContextToPush;
414    }
415
416    void pop() {
417      if (!SavedContext) return;
418      S.CurContext = SavedContext;
419      S.DelayedDiagnostics.popContext(SavedContextState);
420      SavedContext = 0;
421    }
422
423    ~ContextRAII() {
424      pop();
425    }
426  };
427
428  /// WeakUndeclaredIdentifiers - Identifiers contained in
429  /// #pragma weak before declared. rare. may alias another
430  /// identifier, declared or undeclared
431  class WeakInfo {
432    IdentifierInfo *alias;  // alias (optional)
433    SourceLocation loc;     // for diagnostics
434    bool used;              // identifier later declared?
435  public:
436    WeakInfo()
437      : alias(0), loc(SourceLocation()), used(false) {}
438    WeakInfo(IdentifierInfo *Alias, SourceLocation Loc)
439      : alias(Alias), loc(Loc), used(false) {}
440    inline IdentifierInfo * getAlias() const { return alias; }
441    inline SourceLocation getLocation() const { return loc; }
442    void setUsed(bool Used=true) { used = Used; }
443    inline bool getUsed() { return used; }
444    bool operator==(WeakInfo RHS) const {
445      return alias == RHS.getAlias() && loc == RHS.getLocation();
446    }
447    bool operator!=(WeakInfo RHS) const { return !(*this == RHS); }
448  };
449  llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
450
451  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
452  /// #pragma weak during processing of other Decls.
453  /// I couldn't figure out a clean way to generate these in-line, so
454  /// we store them here and handle separately -- which is a hack.
455  /// It would be best to refactor this.
456  llvm::SmallVector<Decl*,2> WeakTopLevelDecl;
457
458  IdentifierResolver IdResolver;
459
460  /// Translation Unit Scope - useful to Objective-C actions that need
461  /// to lookup file scope declarations in the "ordinary" C decl namespace.
462  /// For example, user-defined classes, built-in "id" type, etc.
463  Scope *TUScope;
464
465  /// \brief The C++ "std" namespace, where the standard library resides.
466  LazyDeclPtr StdNamespace;
467
468  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
469  /// standard library.
470  LazyDeclPtr StdBadAlloc;
471
472  /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>.
473  RecordDecl *CXXTypeInfoDecl;
474
475  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
476  RecordDecl *MSVCGuidDecl;
477
478  /// A flag to remember whether the implicit forms of operator new and delete
479  /// have been declared.
480  bool GlobalNewDeleteDeclared;
481
482  /// \brief The set of declarations that have been referenced within
483  /// a potentially evaluated expression.
484  typedef llvm::SmallVector<std::pair<SourceLocation, Decl *>, 10>
485    PotentiallyReferencedDecls;
486
487  /// \brief A set of diagnostics that may be emitted.
488  typedef llvm::SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10>
489    PotentiallyEmittedDiagnostics;
490
491  /// \brief Describes how the expressions currently being parsed are
492  /// evaluated at run-time, if at all.
493  enum ExpressionEvaluationContext {
494    /// \brief The current expression and its subexpressions occur within an
495    /// unevaluated operand (C++0x [expr]p8), such as a constant expression
496    /// or the subexpression of \c sizeof, where the type or the value of the
497    /// expression may be significant but no code will be generated to evaluate
498    /// the value of the expression at run time.
499    Unevaluated,
500
501    /// \brief The current expression is potentially evaluated at run time,
502    /// which means that code may be generated to evaluate the value of the
503    /// expression at run time.
504    PotentiallyEvaluated,
505
506    /// \brief The current expression may be potentially evaluated or it may
507    /// be unevaluated, but it is impossible to tell from the lexical context.
508    /// This evaluation context is used primary for the operand of the C++
509    /// \c typeid expression, whose argument is potentially evaluated only when
510    /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2).
511    PotentiallyPotentiallyEvaluated,
512
513    /// \brief The current expression is potentially evaluated, but any
514    /// declarations referenced inside that expression are only used if
515    /// in fact the current expression is used.
516    ///
517    /// This value is used when parsing default function arguments, for which
518    /// we would like to provide diagnostics (e.g., passing non-POD arguments
519    /// through varargs) but do not want to mark declarations as "referenced"
520    /// until the default argument is used.
521    PotentiallyEvaluatedIfUsed
522  };
523
524  /// \brief Data structure used to record current or nested
525  /// expression evaluation contexts.
526  struct ExpressionEvaluationContextRecord {
527    /// \brief The expression evaluation context.
528    ExpressionEvaluationContext Context;
529
530    /// \brief The number of temporaries that were active when we
531    /// entered this expression evaluation context.
532    unsigned NumTemporaries;
533
534    /// \brief The set of declarations referenced within a
535    /// potentially potentially-evaluated context.
536    ///
537    /// When leaving a potentially potentially-evaluated context, each
538    /// of these elements will be as referenced if the corresponding
539    /// potentially potentially evaluated expression is potentially
540    /// evaluated.
541    PotentiallyReferencedDecls *PotentiallyReferenced;
542
543    /// \brief The set of diagnostics to emit should this potentially
544    /// potentially-evaluated context become evaluated.
545    PotentiallyEmittedDiagnostics *PotentiallyDiagnosed;
546
547    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
548                                      unsigned NumTemporaries)
549      : Context(Context), NumTemporaries(NumTemporaries),
550        PotentiallyReferenced(0), PotentiallyDiagnosed(0) { }
551
552    void addReferencedDecl(SourceLocation Loc, Decl *Decl) {
553      if (!PotentiallyReferenced)
554        PotentiallyReferenced = new PotentiallyReferencedDecls;
555      PotentiallyReferenced->push_back(std::make_pair(Loc, Decl));
556    }
557
558    void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) {
559      if (!PotentiallyDiagnosed)
560        PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics;
561      PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD));
562    }
563
564    void Destroy() {
565      delete PotentiallyReferenced;
566      delete PotentiallyDiagnosed;
567      PotentiallyReferenced = 0;
568      PotentiallyDiagnosed = 0;
569    }
570  };
571
572  /// A stack of expression evaluation contexts.
573  llvm::SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
574
575  /// \brief Whether the code handled by Sema should be considered a
576  /// complete translation unit or not.
577  ///
578  /// When true (which is generally the case), Sema will perform
579  /// end-of-translation-unit semantic tasks (such as creating
580  /// initializers for tentative definitions in C) once parsing has
581  /// completed. This flag will be false when building PCH files,
582  /// since a PCH file is by definition not a complete translation
583  /// unit.
584  bool CompleteTranslationUnit;
585
586  llvm::BumpPtrAllocator BumpAlloc;
587
588  /// \brief The number of SFINAE diagnostics that have been trapped.
589  unsigned NumSFINAEErrors;
590
591  typedef llvm::DenseMap<ParmVarDecl *, llvm::SmallVector<ParmVarDecl *, 1> >
592    UnparsedDefaultArgInstantiationsMap;
593
594  /// \brief A mapping from parameters with unparsed default arguments to the
595  /// set of instantiations of each parameter.
596  ///
597  /// This mapping is a temporary data structure used when parsing
598  /// nested class templates or nested classes of class templates,
599  /// where we might end up instantiating an inner class before the
600  /// default arguments of its methods have been parsed.
601  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
602
603  // Contains the locations of the beginning of unparsed default
604  // argument locations.
605  llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs;
606
607  /// UndefinedInternals - all the used, undefined objects with
608  /// internal linkage in this translation unit.
609  llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals;
610
611  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
612  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
613
614  /// Method Pool - allows efficient lookup when typechecking messages to "id".
615  /// We need to maintain a list, since selectors can have differing signatures
616  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
617  /// of selectors are "overloaded").
618  GlobalMethodPool MethodPool;
619
620  /// Method selectors used in a @selector expression. Used for implementation
621  /// of -Wselector.
622  llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
623
624  GlobalMethodPool::iterator ReadMethodPool(Selector Sel);
625
626  /// Private Helper predicate to check for 'self'.
627  bool isSelfExpr(Expr *RExpr);
628public:
629  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
630       bool CompleteTranslationUnit = true,
631       CodeCompleteConsumer *CompletionConsumer = 0);
632  ~Sema();
633
634  /// \brief Perform initialization that occurs after the parser has been
635  /// initialized but before it parses anything.
636  void Initialize();
637
638  const LangOptions &getLangOptions() const { return LangOpts; }
639  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
640  FPOptions     &getFPOptions() { return FPFeatures; }
641
642  Diagnostic &getDiagnostics() const { return Diags; }
643  SourceManager &getSourceManager() const { return SourceMgr; }
644  const TargetAttributesSema &getTargetAttributesSema() const;
645  Preprocessor &getPreprocessor() const { return PP; }
646  ASTContext &getASTContext() const { return Context; }
647  ASTConsumer &getASTConsumer() const { return Consumer; }
648
649  /// \brief Helper class that creates diagnostics with optional
650  /// template instantiation stacks.
651  ///
652  /// This class provides a wrapper around the basic DiagnosticBuilder
653  /// class that emits diagnostics. SemaDiagnosticBuilder is
654  /// responsible for emitting the diagnostic (as DiagnosticBuilder
655  /// does) and, if the diagnostic comes from inside a template
656  /// instantiation, printing the template instantiation stack as
657  /// well.
658  class SemaDiagnosticBuilder : public DiagnosticBuilder {
659    Sema &SemaRef;
660    unsigned DiagID;
661
662  public:
663    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
664      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
665
666    explicit SemaDiagnosticBuilder(Sema &SemaRef)
667      : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { }
668
669    ~SemaDiagnosticBuilder();
670  };
671
672  /// \brief Emit a diagnostic.
673  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
674
675  /// \brief Emit a partial diagnostic.
676  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
677
678  /// \brief Build a partial diagnostic.
679  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
680
681  ExprResult Owned(Expr* E) { return E; }
682  ExprResult Owned(ExprResult R) { return R; }
683  StmtResult Owned(Stmt* S) { return S; }
684
685  void ActOnEndOfTranslationUnit();
686
687  Scope *getScopeForContext(DeclContext *Ctx);
688
689  void PushFunctionScope();
690  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
691  void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0,
692                               const Decl *D = 0, const BlockExpr *blkExpr = 0);
693
694  sema::FunctionScopeInfo *getCurFunction() const {
695    return FunctionScopes.back();
696  }
697
698  bool hasAnyErrorsInThisFunction() const;
699
700  /// \brief Retrieve the current block, if any.
701  sema::BlockScopeInfo *getCurBlock();
702
703  /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls
704  llvm::SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
705
706  //===--------------------------------------------------------------------===//
707  // Type Analysis / Processing: SemaType.cpp.
708  //
709
710  QualType adjustParameterType(QualType T);
711  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs);
712  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) {
713    return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR));
714  }
715  QualType BuildPointerType(QualType T,
716                            SourceLocation Loc, DeclarationName Entity);
717  QualType BuildReferenceType(QualType T, bool LValueRef,
718                              SourceLocation Loc, DeclarationName Entity);
719  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
720                          Expr *ArraySize, unsigned Quals,
721                          SourceRange Brackets, DeclarationName Entity);
722  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
723                              SourceLocation AttrLoc);
724  QualType BuildFunctionType(QualType T,
725                             QualType *ParamTypes, unsigned NumParamTypes,
726                             bool Variadic, unsigned Quals,
727                             RefQualifierKind RefQualifier,
728                             SourceLocation Loc, DeclarationName Entity,
729                             FunctionType::ExtInfo Info);
730  QualType BuildMemberPointerType(QualType T, QualType Class,
731                                  SourceLocation Loc,
732                                  DeclarationName Entity);
733  QualType BuildBlockPointerType(QualType T,
734                                 SourceLocation Loc, DeclarationName Entity);
735  QualType BuildParenType(QualType T);
736
737  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S,
738                                       TagDecl **OwnedDecl = 0,
739                                       bool AllowAutoInTypeName = false);
740  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
741                                               TypeSourceInfo *ReturnTypeInfo);
742  /// \brief Package the given type and TSI into a ParsedType.
743  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
744  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
745  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
746  static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
747  bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range);
748  bool CheckDistantExceptionSpec(QualType T);
749  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
750  bool CheckEquivalentExceptionSpec(
751      const FunctionProtoType *Old, SourceLocation OldLoc,
752      const FunctionProtoType *New, SourceLocation NewLoc);
753  bool CheckEquivalentExceptionSpec(
754      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
755      const FunctionProtoType *Old, SourceLocation OldLoc,
756      const FunctionProtoType *New, SourceLocation NewLoc,
757      bool *MissingExceptionSpecification = 0,
758      bool *MissingEmptyExceptionSpecification = 0);
759  bool CheckExceptionSpecSubset(
760      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
761      const FunctionProtoType *Superset, SourceLocation SuperLoc,
762      const FunctionProtoType *Subset, SourceLocation SubLoc);
763  bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
764      const FunctionProtoType *Target, SourceLocation TargetLoc,
765      const FunctionProtoType *Source, SourceLocation SourceLoc);
766
767  TypeResult ActOnTypeName(Scope *S, Declarator &D);
768
769  bool RequireCompleteType(SourceLocation Loc, QualType T,
770                           const PartialDiagnostic &PD,
771                           std::pair<SourceLocation, PartialDiagnostic> Note);
772  bool RequireCompleteType(SourceLocation Loc, QualType T,
773                           const PartialDiagnostic &PD);
774  bool RequireCompleteType(SourceLocation Loc, QualType T,
775                           unsigned DiagID);
776
777  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
778                             const CXXScopeSpec &SS, QualType T);
779
780  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
781  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
782
783  //===--------------------------------------------------------------------===//
784  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
785  //
786
787  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr);
788
789  void DiagnoseUseOfUnimplementedSelectors();
790
791  ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
792                         Scope *S, CXXScopeSpec *SS = 0,
793                         bool isClassName = false,
794                         bool HasTrailingDot = false,
795                         ParsedType ObjectType = ParsedType(),
796                         bool WantNontrivialTypeSourceInfo = false);
797  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
798  bool DiagnoseUnknownTypeName(const IdentifierInfo &II,
799                               SourceLocation IILoc,
800                               Scope *S,
801                               CXXScopeSpec *SS,
802                               ParsedType &SuggestedType);
803
804  Decl *ActOnDeclarator(Scope *S, Declarator &D);
805
806  Decl *HandleDeclarator(Scope *S, Declarator &D,
807                         MultiTemplateParamsArg TemplateParameterLists,
808                         bool IsFunctionDefinition);
809  void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
810                                        const LookupResult &Previous,
811                                        Scope *S);
812  void DiagnoseFunctionSpecifiers(Declarator& D);
813  void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
814  void CheckShadow(Scope *S, VarDecl *D);
815  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
816  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
817                                    QualType R, TypeSourceInfo *TInfo,
818                                    LookupResult &Previous, bool &Redeclaration);
819  NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
820                                     QualType R, TypeSourceInfo *TInfo,
821                                     LookupResult &Previous,
822                                     MultiTemplateParamsArg TemplateParamLists,
823                                     bool &Redeclaration);
824  void CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous,
825                                bool &Redeclaration);
826  void CheckCompleteVariableDeclaration(VarDecl *var);
827  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
828                                     QualType R, TypeSourceInfo *TInfo,
829                                     LookupResult &Previous,
830                                     MultiTemplateParamsArg TemplateParamLists,
831                                     bool IsFunctionDefinition,
832                                     bool &Redeclaration);
833  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
834  void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
835  void CheckFunctionDeclaration(Scope *S,
836                                FunctionDecl *NewFD, LookupResult &Previous,
837                                bool IsExplicitSpecialization,
838                                bool &Redeclaration);
839  void CheckMain(FunctionDecl *FD);
840  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
841  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
842                                          SourceLocation Loc,
843                                          QualType T);
844  ParmVarDecl *CheckParameter(DeclContext *DC,
845                              TypeSourceInfo *TSInfo, QualType T,
846                              IdentifierInfo *Name,
847                              SourceLocation NameLoc,
848                              StorageClass SC,
849                              StorageClass SCAsWritten);
850  void ActOnParamDefaultArgument(Decl *param,
851                                 SourceLocation EqualLoc,
852                                 Expr *defarg);
853  void ActOnParamUnparsedDefaultArgument(Decl *param,
854                                         SourceLocation EqualLoc,
855                                         SourceLocation ArgLoc);
856  void ActOnParamDefaultArgumentError(Decl *param);
857  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
858                               SourceLocation EqualLoc);
859
860  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
861                            bool TypeMayContainAuto);
862  void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
863  void ActOnInitializerError(Decl *Dcl);
864  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
865  void FinalizeDeclaration(Decl *D);
866  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
867                                         Decl **Group,
868                                         unsigned NumDecls);
869  DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
870                                      bool TypeMayContainAuto = true);
871  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
872                                       SourceLocation LocAfterDecls);
873  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
874  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
875  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
876
877  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
878  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
879
880  /// \brief Diagnose any unused parameters in the given sequence of
881  /// ParmVarDecl pointers.
882  void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
883                                ParmVarDecl * const *End);
884
885  /// \brief Diagnose whether the size of parameters or return value of a
886  /// function or obj-c method definition is pass-by-value and larger than a
887  /// specified threshold.
888  void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
889                                              ParmVarDecl * const *End,
890                                              QualType ReturnTy,
891                                              NamedDecl *D);
892
893  void DiagnoseInvalidJumps(Stmt *Body);
894  Decl *ActOnFileScopeAsmDecl(SourceLocation Loc, Expr *expr);
895
896  /// Scope actions.
897  void ActOnPopScope(SourceLocation Loc, Scope *S);
898  void ActOnTranslationUnitScope(Scope *S);
899
900  /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
901  /// no declarator (e.g. "struct foo;") is parsed.
902  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
903                                   DeclSpec &DS);
904
905  StmtResult ActOnVlaStmt(const DeclSpec &DS);
906
907  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
908                                    AccessSpecifier AS,
909                                    RecordDecl *Record);
910
911  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
912                                       RecordDecl *Record);
913
914  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
915                                    TagTypeKind NewTag,
916                                    SourceLocation NewTagLoc,
917                                    const IdentifierInfo &Name);
918
919  enum TagUseKind {
920    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
921    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
922    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
923    TUK_Friend       // Friend declaration:  'friend struct foo;'
924  };
925
926  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
927                 SourceLocation KWLoc, CXXScopeSpec &SS,
928                 IdentifierInfo *Name, SourceLocation NameLoc,
929                 AttributeList *Attr, AccessSpecifier AS,
930                 MultiTemplateParamsArg TemplateParameterLists,
931                 bool &OwnedDecl, bool &IsDependent, bool ScopedEnum,
932                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
933
934  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
935                                unsigned TagSpec, SourceLocation TagLoc,
936                                CXXScopeSpec &SS,
937                                IdentifierInfo *Name, SourceLocation NameLoc,
938                                AttributeList *Attr,
939                                MultiTemplateParamsArg TempParamLists);
940
941  TypeResult ActOnDependentTag(Scope *S,
942                               unsigned TagSpec,
943                               TagUseKind TUK,
944                               const CXXScopeSpec &SS,
945                               IdentifierInfo *Name,
946                               SourceLocation TagLoc,
947                               SourceLocation NameLoc);
948
949  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
950                 IdentifierInfo *ClassName,
951                 llvm::SmallVectorImpl<Decl *> &Decls);
952  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
953                   Declarator &D, Expr *BitfieldWidth);
954
955  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
956                         Declarator &D, Expr *BitfieldWidth,
957                         AccessSpecifier AS);
958
959  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
960                            TypeSourceInfo *TInfo,
961                            RecordDecl *Record, SourceLocation Loc,
962                            bool Mutable, Expr *BitfieldWidth,
963                            SourceLocation TSSL,
964                            AccessSpecifier AS, NamedDecl *PrevDecl,
965                            Declarator *D = 0);
966
967  enum CXXSpecialMember {
968    CXXInvalid = -1,
969    CXXConstructor = 0,
970    CXXCopyConstructor = 1,
971    CXXCopyAssignment = 2,
972    CXXDestructor = 3
973  };
974  bool CheckNontrivialField(FieldDecl *FD);
975  void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem);
976  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
977  void ActOnLastBitfield(SourceLocation DeclStart, Decl *IntfDecl,
978                         llvm::SmallVectorImpl<Decl *> &AllIvarDecls);
979  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Decl *IntfDecl,
980                  Declarator &D, Expr *BitfieldWidth,
981                  tok::ObjCKeywordKind visibility);
982
983  // This is used for both record definitions and ObjC interface declarations.
984  void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
985                   Decl **Fields, unsigned NumFields,
986                   SourceLocation LBrac, SourceLocation RBrac,
987                   AttributeList *AttrList);
988
989  /// ActOnTagStartDefinition - Invoked when we have entered the
990  /// scope of a tag's definition (e.g., for an enumeration, class,
991  /// struct, or union).
992  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
993
994  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
995  /// C++ record definition's base-specifiers clause and are starting its
996  /// member declarations.
997  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
998                                       ClassVirtSpecifiers &CVS,
999                                       SourceLocation LBraceLoc);
1000
1001  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1002  /// the definition of a tag (enumeration, class, struct, or union).
1003  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1004                                SourceLocation RBraceLoc);
1005
1006  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1007  /// error parsing the definition of a tag.
1008  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1009
1010  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1011                                      EnumConstantDecl *LastEnumConst,
1012                                      SourceLocation IdLoc,
1013                                      IdentifierInfo *Id,
1014                                      Expr *val);
1015
1016  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1017                          SourceLocation IdLoc, IdentifierInfo *Id,
1018                          AttributeList *Attrs,
1019                          SourceLocation EqualLoc, Expr *Val);
1020  void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1021                     SourceLocation RBraceLoc, Decl *EnumDecl,
1022                     Decl **Elements, unsigned NumElements,
1023                     Scope *S, AttributeList *Attr);
1024
1025  DeclContext *getContainingDC(DeclContext *DC);
1026
1027  /// Set the current declaration context until it gets popped.
1028  void PushDeclContext(Scope *S, DeclContext *DC);
1029  void PopDeclContext();
1030
1031  /// EnterDeclaratorContext - Used when we must lookup names in the context
1032  /// of a declarator's nested name specifier.
1033  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1034  void ExitDeclaratorContext(Scope *S);
1035
1036  DeclContext *getFunctionLevelDeclContext();
1037
1038  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1039  /// to the function decl for the function being parsed.  If we're currently
1040  /// in a 'block', this returns the containing context.
1041  FunctionDecl *getCurFunctionDecl();
1042
1043  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1044  /// the method decl for the method being parsed.  If we're currently
1045  /// in a 'block', this returns the containing context.
1046  ObjCMethodDecl *getCurMethodDecl();
1047
1048  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1049  /// or C function we're in, otherwise return null.  If we're currently
1050  /// in a 'block', this returns the containing context.
1051  NamedDecl *getCurFunctionOrMethodDecl();
1052
1053  /// Add this decl to the scope shadowed decl chains.
1054  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1055
1056  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1057  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1058  /// true if 'D' belongs to the given declaration context.
1059  bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0);
1060
1061  /// Finds the scope corresponding to the given decl context, if it
1062  /// happens to be an enclosing scope.  Otherwise return NULL.
1063  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1064
1065  /// Subroutines of ActOnDeclarator().
1066  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1067                                TypeSourceInfo *TInfo);
1068  void MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls);
1069  bool MergeFunctionDecl(FunctionDecl *New, Decl *Old);
1070  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old);
1071  void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old);
1072  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old);
1073  void MergeVarDecl(VarDecl *New, LookupResult &OldDecls);
1074  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old);
1075
1076  // AssignmentAction - This is used by all the assignment diagnostic functions
1077  // to represent what is actually causing the operation
1078  enum AssignmentAction {
1079    AA_Assigning,
1080    AA_Passing,
1081    AA_Returning,
1082    AA_Converting,
1083    AA_Initializing,
1084    AA_Sending,
1085    AA_Casting
1086  };
1087
1088  /// C++ Overloading.
1089  enum OverloadKind {
1090    /// This is a legitimate overload: the existing declarations are
1091    /// functions or function templates with different signatures.
1092    Ovl_Overload,
1093
1094    /// This is not an overload because the signature exactly matches
1095    /// an existing declaration.
1096    Ovl_Match,
1097
1098    /// This is not an overload because the lookup results contain a
1099    /// non-function.
1100    Ovl_NonFunction
1101  };
1102  OverloadKind CheckOverload(Scope *S,
1103                             FunctionDecl *New,
1104                             const LookupResult &OldDecls,
1105                             NamedDecl *&OldDecl,
1106                             bool IsForUsingDecl);
1107  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1108
1109  bool TryImplicitConversion(InitializationSequence &Sequence,
1110                             const InitializedEntity &Entity,
1111                             Expr *From,
1112                             bool SuppressUserConversions,
1113                             bool AllowExplicit,
1114                             bool InOverloadResolution,
1115                             bool CStyle);
1116
1117  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1118  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1119  bool IsComplexPromotion(QualType FromType, QualType ToType);
1120  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1121                           bool InOverloadResolution,
1122                           QualType& ConvertedType, bool &IncompatibleObjC);
1123  bool isObjCPointerConversion(QualType FromType, QualType ToType,
1124                               QualType& ConvertedType, bool &IncompatibleObjC);
1125  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1126                                QualType& ConvertedType);
1127  bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1128                                const FunctionProtoType *NewType);
1129
1130  bool CheckPointerConversion(Expr *From, QualType ToType,
1131                              CastKind &Kind,
1132                              CXXCastPath& BasePath,
1133                              bool IgnoreBaseAccess);
1134  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1135                                 bool InOverloadResolution,
1136                                 QualType &ConvertedType);
1137  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1138                                    CastKind &Kind,
1139                                    CXXCastPath &BasePath,
1140                                    bool IgnoreBaseAccess);
1141  bool IsQualificationConversion(QualType FromType, QualType ToType,
1142                                 bool CStyle);
1143  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1144
1145
1146  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1147                                             const VarDecl *NRVOCandidate,
1148                                             QualType ResultType,
1149                                             Expr *Value);
1150
1151  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1152                                       SourceLocation EqualLoc,
1153                                       ExprResult Init);
1154  bool PerformObjectArgumentInitialization(Expr *&From,
1155                                           NestedNameSpecifier *Qualifier,
1156                                           NamedDecl *FoundDecl,
1157                                           CXXMethodDecl *Method);
1158
1159  bool PerformContextuallyConvertToBool(Expr *&From);
1160  bool PerformContextuallyConvertToObjCId(Expr *&From);
1161
1162  ExprResult
1163  ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
1164                                     const PartialDiagnostic &NotIntDiag,
1165                                     const PartialDiagnostic &IncompleteDiag,
1166                                     const PartialDiagnostic &ExplicitConvDiag,
1167                                     const PartialDiagnostic &ExplicitConvNote,
1168                                     const PartialDiagnostic &AmbigDiag,
1169                                     const PartialDiagnostic &AmbigNote,
1170                                     const PartialDiagnostic &ConvDiag);
1171
1172  bool PerformObjectMemberConversion(Expr *&From,
1173                                     NestedNameSpecifier *Qualifier,
1174                                     NamedDecl *FoundDecl,
1175                                     NamedDecl *Member);
1176
1177  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
1178  // TODO: make this is a typesafe union.
1179  typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
1180  typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
1181
1182  void AddOverloadCandidate(NamedDecl *Function,
1183                            DeclAccessPair FoundDecl,
1184                            Expr **Args, unsigned NumArgs,
1185                            OverloadCandidateSet &CandidateSet);
1186
1187  void AddOverloadCandidate(FunctionDecl *Function,
1188                            DeclAccessPair FoundDecl,
1189                            Expr **Args, unsigned NumArgs,
1190                            OverloadCandidateSet& CandidateSet,
1191                            bool SuppressUserConversions = false,
1192                            bool PartialOverloading = false);
1193  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
1194                             Expr **Args, unsigned NumArgs,
1195                             OverloadCandidateSet& CandidateSet,
1196                             bool SuppressUserConversions = false);
1197  void AddMethodCandidate(DeclAccessPair FoundDecl,
1198                          QualType ObjectType,
1199                          Expr::Classification ObjectClassification,
1200                          Expr **Args, unsigned NumArgs,
1201                          OverloadCandidateSet& CandidateSet,
1202                          bool SuppressUserConversion = false);
1203  void AddMethodCandidate(CXXMethodDecl *Method,
1204                          DeclAccessPair FoundDecl,
1205                          CXXRecordDecl *ActingContext, QualType ObjectType,
1206                          Expr::Classification ObjectClassification,
1207                          Expr **Args, unsigned NumArgs,
1208                          OverloadCandidateSet& CandidateSet,
1209                          bool SuppressUserConversions = false);
1210  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
1211                                  DeclAccessPair FoundDecl,
1212                                  CXXRecordDecl *ActingContext,
1213                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
1214                                  QualType ObjectType,
1215                                  Expr::Classification ObjectClassification,
1216                                  Expr **Args, unsigned NumArgs,
1217                                  OverloadCandidateSet& CandidateSet,
1218                                  bool SuppressUserConversions = false);
1219  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
1220                                    DeclAccessPair FoundDecl,
1221                      const TemplateArgumentListInfo *ExplicitTemplateArgs,
1222                                    Expr **Args, unsigned NumArgs,
1223                                    OverloadCandidateSet& CandidateSet,
1224                                    bool SuppressUserConversions = false);
1225  void AddConversionCandidate(CXXConversionDecl *Conversion,
1226                              DeclAccessPair FoundDecl,
1227                              CXXRecordDecl *ActingContext,
1228                              Expr *From, QualType ToType,
1229                              OverloadCandidateSet& CandidateSet);
1230  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
1231                                      DeclAccessPair FoundDecl,
1232                                      CXXRecordDecl *ActingContext,
1233                                      Expr *From, QualType ToType,
1234                                      OverloadCandidateSet &CandidateSet);
1235  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
1236                             DeclAccessPair FoundDecl,
1237                             CXXRecordDecl *ActingContext,
1238                             const FunctionProtoType *Proto,
1239                             Expr *Object, Expr **Args, unsigned NumArgs,
1240                             OverloadCandidateSet& CandidateSet);
1241  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
1242                                   SourceLocation OpLoc,
1243                                   Expr **Args, unsigned NumArgs,
1244                                   OverloadCandidateSet& CandidateSet,
1245                                   SourceRange OpRange = SourceRange());
1246  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1247                           Expr **Args, unsigned NumArgs,
1248                           OverloadCandidateSet& CandidateSet,
1249                           bool IsAssignmentOperator = false,
1250                           unsigned NumContextualBoolArguments = 0);
1251  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
1252                                    SourceLocation OpLoc,
1253                                    Expr **Args, unsigned NumArgs,
1254                                    OverloadCandidateSet& CandidateSet);
1255  void AddArgumentDependentLookupCandidates(DeclarationName Name,
1256                                            bool Operator,
1257                                            Expr **Args, unsigned NumArgs,
1258                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
1259                                            OverloadCandidateSet& CandidateSet,
1260                                            bool PartialOverloading = false);
1261
1262  // Emit as a 'note' the specific overload candidate
1263  void NoteOverloadCandidate(FunctionDecl *Fn);
1264
1265  // Emit as a series of 'note's all template and non-templates
1266  // identified by the expression Expr
1267  void NoteAllOverloadCandidates(Expr* E);
1268
1269  // [PossiblyAFunctionType]  -->   [Return]
1270  // NonFunctionType --> NonFunctionType
1271  // R (A) --> R(A)
1272  // R (*)(A) --> R (A)
1273  // R (&)(A) --> R (A)
1274  // R (S::*)(A) --> R (A)
1275  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
1276
1277  FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
1278                                                   bool Complain,
1279                                                   DeclAccessPair &Found);
1280
1281  FunctionDecl *ResolveSingleFunctionTemplateSpecialization(Expr *From,
1282                                                   bool Complain = false,
1283                                                   DeclAccessPair* Found = 0);
1284
1285  Expr *FixOverloadedFunctionReference(Expr *E,
1286                                       DeclAccessPair FoundDecl,
1287                                       FunctionDecl *Fn);
1288  ExprResult FixOverloadedFunctionReference(ExprResult,
1289                                            DeclAccessPair FoundDecl,
1290                                            FunctionDecl *Fn);
1291
1292  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
1293                                   Expr **Args, unsigned NumArgs,
1294                                   OverloadCandidateSet &CandidateSet,
1295                                   bool PartialOverloading = false);
1296
1297  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
1298                                     UnresolvedLookupExpr *ULE,
1299                                     SourceLocation LParenLoc,
1300                                     Expr **Args, unsigned NumArgs,
1301                                     SourceLocation RParenLoc,
1302                                     Expr *ExecConfig);
1303
1304  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
1305                                     unsigned Opc,
1306                                     const UnresolvedSetImpl &Fns,
1307                                     Expr *input);
1308
1309  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
1310                                   unsigned Opc,
1311                                   const UnresolvedSetImpl &Fns,
1312                                   Expr *LHS, Expr *RHS);
1313
1314  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
1315                                                SourceLocation RLoc,
1316                                                Expr *Base,Expr *Idx);
1317
1318  ExprResult
1319  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
1320                            SourceLocation LParenLoc, Expr **Args,
1321                            unsigned NumArgs, SourceLocation RParenLoc);
1322  ExprResult
1323  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
1324                               Expr **Args, unsigned NumArgs,
1325                               SourceLocation RParenLoc);
1326
1327  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
1328                                      SourceLocation OpLoc);
1329
1330  /// CheckCallReturnType - Checks that a call expression's return type is
1331  /// complete. Returns true on failure. The location passed in is the location
1332  /// that best represents the call.
1333  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
1334                           CallExpr *CE, FunctionDecl *FD);
1335
1336  /// Helpers for dealing with blocks and functions.
1337  bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
1338                                bool CheckParameterNames);
1339  void CheckCXXDefaultArguments(FunctionDecl *FD);
1340  void CheckExtraCXXDefaultArguments(Declarator &D);
1341  Scope *getNonFieldDeclScope(Scope *S);
1342
1343  /// \name Name lookup
1344  ///
1345  /// These routines provide name lookup that is used during semantic
1346  /// analysis to resolve the various kinds of names (identifiers,
1347  /// overloaded operator names, constructor names, etc.) into zero or
1348  /// more declarations within a particular scope. The major entry
1349  /// points are LookupName, which performs unqualified name lookup,
1350  /// and LookupQualifiedName, which performs qualified name lookup.
1351  ///
1352  /// All name lookup is performed based on some specific criteria,
1353  /// which specify what names will be visible to name lookup and how
1354  /// far name lookup should work. These criteria are important both
1355  /// for capturing language semantics (certain lookups will ignore
1356  /// certain names, for example) and for performance, since name
1357  /// lookup is often a bottleneck in the compilation of C++. Name
1358  /// lookup criteria is specified via the LookupCriteria enumeration.
1359  ///
1360  /// The results of name lookup can vary based on the kind of name
1361  /// lookup performed, the current language, and the translation
1362  /// unit. In C, for example, name lookup will either return nothing
1363  /// (no entity found) or a single declaration. In C++, name lookup
1364  /// can additionally refer to a set of overloaded functions or
1365  /// result in an ambiguity. All of the possible results of name
1366  /// lookup are captured by the LookupResult class, which provides
1367  /// the ability to distinguish among them.
1368  //@{
1369
1370  /// @brief Describes the kind of name lookup to perform.
1371  enum LookupNameKind {
1372    /// Ordinary name lookup, which finds ordinary names (functions,
1373    /// variables, typedefs, etc.) in C and most kinds of names
1374    /// (functions, variables, members, types, etc.) in C++.
1375    LookupOrdinaryName = 0,
1376    /// Tag name lookup, which finds the names of enums, classes,
1377    /// structs, and unions.
1378    LookupTagName,
1379    /// Label name lookup.
1380    LookupLabel,
1381    /// Member name lookup, which finds the names of
1382    /// class/struct/union members.
1383    LookupMemberName,
1384    /// Look up of an operator name (e.g., operator+) for use with
1385    /// operator overloading. This lookup is similar to ordinary name
1386    /// lookup, but will ignore any declarations that are class members.
1387    LookupOperatorName,
1388    /// Look up of a name that precedes the '::' scope resolution
1389    /// operator in C++. This lookup completely ignores operator, object,
1390    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
1391    LookupNestedNameSpecifierName,
1392    /// Look up a namespace name within a C++ using directive or
1393    /// namespace alias definition, ignoring non-namespace names (C++
1394    /// [basic.lookup.udir]p1).
1395    LookupNamespaceName,
1396    /// Look up all declarations in a scope with the given name,
1397    /// including resolved using declarations.  This is appropriate
1398    /// for checking redeclarations for a using declaration.
1399    LookupUsingDeclName,
1400    /// Look up an ordinary name that is going to be redeclared as a
1401    /// name with linkage. This lookup ignores any declarations that
1402    /// are outside of the current scope unless they have linkage. See
1403    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
1404    LookupRedeclarationWithLinkage,
1405    /// Look up the name of an Objective-C protocol.
1406    LookupObjCProtocolName,
1407    /// \brief Look up any declaration with any name.
1408    LookupAnyName
1409  };
1410
1411  /// \brief Specifies whether (or how) name lookup is being performed for a
1412  /// redeclaration (vs. a reference).
1413  enum RedeclarationKind {
1414    /// \brief The lookup is a reference to this name that is not for the
1415    /// purpose of redeclaring the name.
1416    NotForRedeclaration = 0,
1417    /// \brief The lookup results will be used for redeclaration of a name,
1418    /// if an entity by that name already exists.
1419    ForRedeclaration
1420  };
1421
1422private:
1423  bool CppLookupName(LookupResult &R, Scope *S);
1424
1425public:
1426  /// \brief Look up a name, looking for a single declaration.  Return
1427  /// null if the results were absent, ambiguous, or overloaded.
1428  ///
1429  /// It is preferable to use the elaborated form and explicitly handle
1430  /// ambiguity and overloaded.
1431  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
1432                              SourceLocation Loc,
1433                              LookupNameKind NameKind,
1434                              RedeclarationKind Redecl
1435                                = NotForRedeclaration);
1436  bool LookupName(LookupResult &R, Scope *S,
1437                  bool AllowBuiltinCreation = false);
1438  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1439                           bool InUnqualifiedLookup = false);
1440  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1441                        bool AllowBuiltinCreation = false,
1442                        bool EnteringContext = false);
1443  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc);
1444
1445  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1446                                    QualType T1, QualType T2,
1447                                    UnresolvedSetImpl &Functions);
1448
1449  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
1450                                 bool isLocalLabel = false);
1451
1452  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
1453  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
1454
1455  void ArgumentDependentLookup(DeclarationName Name, bool Operator,
1456                               Expr **Args, unsigned NumArgs,
1457                               ADLResult &Functions);
1458
1459  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
1460                          VisibleDeclConsumer &Consumer,
1461                          bool IncludeGlobalScope = true);
1462  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
1463                          VisibleDeclConsumer &Consumer,
1464                          bool IncludeGlobalScope = true);
1465
1466  /// \brief The context in which typo-correction occurs.
1467  ///
1468  /// The typo-correction context affects which keywords (if any) are
1469  /// considered when trying to correct for typos.
1470  enum CorrectTypoContext {
1471    /// \brief An unknown context, where any keyword might be valid.
1472    CTC_Unknown,
1473    /// \brief A context where no keywords are used (e.g. we expect an actual
1474    /// name).
1475    CTC_NoKeywords,
1476    /// \brief A context where we're correcting a type name.
1477    CTC_Type,
1478    /// \brief An expression context.
1479    CTC_Expression,
1480    /// \brief A type cast, or anything else that can be followed by a '<'.
1481    CTC_CXXCasts,
1482    /// \brief A member lookup context.
1483    CTC_MemberLookup,
1484    /// \brief An Objective-C ivar lookup context (e.g., self->ivar).
1485    CTC_ObjCIvarLookup,
1486    /// \brief An Objective-C property lookup context (e.g., self.prop).
1487    CTC_ObjCPropertyLookup,
1488    /// \brief The receiver of an Objective-C message send within an
1489    /// Objective-C method where 'super' is a valid keyword.
1490    CTC_ObjCMessageReceiver
1491  };
1492
1493  DeclarationName CorrectTypo(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1494                              DeclContext *MemberContext = 0,
1495                              bool EnteringContext = false,
1496                              CorrectTypoContext CTC = CTC_Unknown,
1497                              const ObjCObjectPointerType *OPT = 0);
1498
1499  void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1500                                   AssociatedNamespaceSet &AssociatedNamespaces,
1501                                   AssociatedClassSet &AssociatedClasses);
1502
1503  bool DiagnoseAmbiguousLookup(LookupResult &Result);
1504  //@}
1505
1506  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
1507                                          SourceLocation IdLoc,
1508                                          bool TypoCorrection = false);
1509  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1510                                 Scope *S, bool ForRedeclaration,
1511                                 SourceLocation Loc);
1512  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
1513                                      Scope *S);
1514  void AddKnownFunctionAttributes(FunctionDecl *FD);
1515
1516  // More parsing and symbol table subroutines.
1517
1518  // Decl attributes - this routine is the top level dispatcher.
1519  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
1520                           bool NonInheritable = true, bool Inheritable = true);
1521  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
1522                           bool NonInheritable = true, bool Inheritable = true);
1523
1524  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
1525  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC);
1526  bool CheckNoReturnAttr(const AttributeList &attr);
1527
1528  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1529                           bool &IncompleteImpl, unsigned DiagID);
1530  void WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethod,
1531                                   ObjCMethodDecl *MethodDecl,
1532                                   bool IsProtocolMethodDecl);
1533
1534  bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
1535                          ObjCInterfaceDecl *IDecl);
1536
1537  typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet;
1538
1539  /// CheckProtocolMethodDefs - This routine checks unimplemented
1540  /// methods declared in protocol, and those referenced by it.
1541  /// \param IDecl - Used for checking for methods which may have been
1542  /// inherited.
1543  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
1544                               ObjCProtocolDecl *PDecl,
1545                               bool& IncompleteImpl,
1546                               const SelectorSet &InsMap,
1547                               const SelectorSet &ClsMap,
1548                               ObjCContainerDecl *CDecl);
1549
1550  /// CheckImplementationIvars - This routine checks if the instance variables
1551  /// listed in the implelementation match those listed in the interface.
1552  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1553                                ObjCIvarDecl **Fields, unsigned nIvars,
1554                                SourceLocation Loc);
1555
1556  /// \brief Determine whether we can synthesize a provisional ivar for the
1557  /// given name.
1558  ObjCPropertyDecl *canSynthesizeProvisionalIvar(IdentifierInfo *II);
1559
1560  /// \brief Determine whether we can synthesize a provisional ivar for the
1561  /// given property.
1562  bool canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property);
1563
1564  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
1565  /// remains unimplemented in the class or category @implementation.
1566  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1567                                 ObjCContainerDecl* IDecl,
1568                                 bool IncompleteImpl = false);
1569
1570  /// DiagnoseUnimplementedProperties - This routine warns on those properties
1571  /// which must be implemented by this implementation.
1572  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1573                                       ObjCContainerDecl *CDecl,
1574                                       const SelectorSet &InsMap);
1575
1576  /// DefaultSynthesizeProperties - This routine default synthesizes all
1577  /// properties which must be synthesized in class's @implementation.
1578  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
1579                                    ObjCInterfaceDecl *IDecl);
1580
1581  /// CollectImmediateProperties - This routine collects all properties in
1582  /// the class and its conforming protocols; but not those it its super class.
1583  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
1584            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
1585            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
1586
1587
1588  /// LookupPropertyDecl - Looks up a property in the current class and all
1589  /// its protocols.
1590  ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl,
1591                                       IdentifierInfo *II);
1592
1593  /// Called by ActOnProperty to handle @property declarations in
1594  ////  class extensions.
1595  Decl *HandlePropertyInClassExtension(Scope *S,
1596                                       ObjCCategoryDecl *CDecl,
1597                                       SourceLocation AtLoc,
1598                                       FieldDeclarator &FD,
1599                                       Selector GetterSel,
1600                                       Selector SetterSel,
1601                                       const bool isAssign,
1602                                       const bool isReadWrite,
1603                                       const unsigned Attributes,
1604                                       bool *isOverridingProperty,
1605                                       TypeSourceInfo *T,
1606                                       tok::ObjCKeywordKind MethodImplKind);
1607
1608  /// Called by ActOnProperty and HandlePropertyInClassExtension to
1609  ///  handle creating the ObjcPropertyDecl for a category or @interface.
1610  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
1611                                       ObjCContainerDecl *CDecl,
1612                                       SourceLocation AtLoc,
1613                                       FieldDeclarator &FD,
1614                                       Selector GetterSel,
1615                                       Selector SetterSel,
1616                                       const bool isAssign,
1617                                       const bool isReadWrite,
1618                                       const unsigned Attributes,
1619                                       TypeSourceInfo *T,
1620                                       tok::ObjCKeywordKind MethodImplKind,
1621                                       DeclContext *lexicalDC = 0);
1622
1623  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
1624  /// warning) when atomic property has one but not the other user-declared
1625  /// setter or getter.
1626  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
1627                                       ObjCContainerDecl* IDecl);
1628
1629  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
1630
1631  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
1632  /// true, or false, accordingly.
1633  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1634                                  const ObjCMethodDecl *PrevMethod,
1635                                  bool matchBasedOnSizeAndAlignment = false,
1636                                  bool matchBasedOnStrictEqulity = false);
1637
1638  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
1639  /// or protocol against those declared in their implementations.
1640  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
1641                                  const SelectorSet &ClsMap,
1642                                  SelectorSet &InsMapSeen,
1643                                  SelectorSet &ClsMapSeen,
1644                                  ObjCImplDecl* IMPDecl,
1645                                  ObjCContainerDecl* IDecl,
1646                                  bool &IncompleteImpl,
1647                                  bool ImmediateClass);
1648
1649private:
1650  /// AddMethodToGlobalPool - Add an instance or factory method to the global
1651  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
1652  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
1653
1654  /// LookupMethodInGlobalPool - Returns the instance or factory method and
1655  /// optionally warns if there are multiple signatures.
1656  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1657                                           bool receiverIdOrClass,
1658                                           bool warn, bool instance);
1659
1660public:
1661  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
1662  /// unit are added to a global pool. This allows us to efficiently associate
1663  /// a selector with a method declaraation for purposes of typechecking
1664  /// messages sent to "id" (where the class of the object is unknown).
1665  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
1666    AddMethodToGlobalPool(Method, impl, /*instance*/true);
1667  }
1668
1669  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
1670  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
1671    AddMethodToGlobalPool(Method, impl, /*instance*/false);
1672  }
1673
1674  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
1675  /// there are multiple signatures.
1676  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
1677                                                   bool receiverIdOrClass=false,
1678                                                   bool warn=true) {
1679    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
1680                                    warn, /*instance*/true);
1681  }
1682
1683  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
1684  /// there are multiple signatures.
1685  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
1686                                                  bool receiverIdOrClass=false,
1687                                                  bool warn=true) {
1688    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
1689                                    warn, /*instance*/false);
1690  }
1691
1692  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
1693  /// implementation.
1694  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
1695
1696  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
1697  /// initialization.
1698  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
1699                                  llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1700  //===--------------------------------------------------------------------===//
1701  // Statement Parsing Callbacks: SemaStmt.cpp.
1702public:
1703  class FullExprArg {
1704  public:
1705    FullExprArg(Sema &actions) : E(0) { }
1706
1707    // FIXME: The const_cast here is ugly. RValue references would make this
1708    // much nicer (or we could duplicate a bunch of the move semantics
1709    // emulation code from Ownership.h).
1710    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
1711
1712    ExprResult release() {
1713      return move(E);
1714    }
1715
1716    Expr *get() const { return E; }
1717
1718    Expr *operator->() {
1719      return E;
1720    }
1721
1722  private:
1723    // FIXME: No need to make the entire Sema class a friend when it's just
1724    // Sema::MakeFullExpr that needs access to the constructor below.
1725    friend class Sema;
1726
1727    explicit FullExprArg(Expr *expr) : E(expr) {}
1728
1729    Expr *E;
1730  };
1731
1732  FullExprArg MakeFullExpr(Expr *Arg) {
1733    return FullExprArg(ActOnFinishFullExpr(Arg).release());
1734  }
1735
1736  StmtResult ActOnExprStmt(FullExprArg Expr);
1737
1738  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
1739                           bool LeadingEmptyMacro = false);
1740  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
1741                                       MultiStmtArg Elts,
1742                                       bool isStmtExpr);
1743  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
1744                                   SourceLocation StartLoc,
1745                                   SourceLocation EndLoc);
1746  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
1747  StmtResult ActOnForEachLValueExpr(Expr *E);
1748  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
1749                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
1750                                   SourceLocation ColonLoc);
1751  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
1752
1753  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
1754                                      SourceLocation ColonLoc,
1755                                      Stmt *SubStmt, Scope *CurScope);
1756  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
1757                            SourceLocation ColonLoc, Stmt *SubStmt);
1758
1759  StmtResult ActOnIfStmt(SourceLocation IfLoc,
1760                         FullExprArg CondVal, Decl *CondVar,
1761                         Stmt *ThenVal,
1762                         SourceLocation ElseLoc, Stmt *ElseVal);
1763  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1764                                            Expr *Cond,
1765                                            Decl *CondVar);
1766  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
1767                                           Stmt *Switch, Stmt *Body);
1768  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
1769                            FullExprArg Cond,
1770                            Decl *CondVar, Stmt *Body);
1771  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1772                                 SourceLocation WhileLoc,
1773                                 SourceLocation CondLParen, Expr *Cond,
1774                                 SourceLocation CondRParen);
1775
1776  StmtResult ActOnForStmt(SourceLocation ForLoc,
1777                          SourceLocation LParenLoc,
1778                          Stmt *First, FullExprArg Second,
1779                          Decl *SecondVar,
1780                          FullExprArg Third,
1781                          SourceLocation RParenLoc,
1782                          Stmt *Body);
1783  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
1784                                        SourceLocation LParenLoc,
1785                                        Stmt *First, Expr *Second,
1786                                        SourceLocation RParenLoc, Stmt *Body);
1787
1788  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
1789                           SourceLocation LabelLoc,
1790                           LabelDecl *TheDecl);
1791  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
1792                                   SourceLocation StarLoc,
1793                                   Expr *DestExp);
1794  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
1795  StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
1796
1797  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
1798                                         bool AllowFunctionParameters);
1799
1800  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
1801  StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
1802
1803  StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
1804                          bool IsSimple, bool IsVolatile,
1805                          unsigned NumOutputs, unsigned NumInputs,
1806                          IdentifierInfo **Names,
1807                          MultiExprArg Constraints,
1808                          MultiExprArg Exprs,
1809                          Expr *AsmString,
1810                          MultiExprArg Clobbers,
1811                          SourceLocation RParenLoc,
1812                          bool MSAsm = false);
1813
1814
1815  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
1816                                  IdentifierInfo *Name, SourceLocation NameLoc,
1817                                  bool Invalid = false);
1818
1819  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
1820
1821  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
1822                                  Decl *Parm, Stmt *Body);
1823
1824  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
1825
1826  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1827                                MultiStmtArg Catch, Stmt *Finally);
1828
1829  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
1830  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
1831                                  Scope *CurScope);
1832  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
1833                                         Expr *SynchExpr,
1834                                         Stmt *SynchBody);
1835
1836  VarDecl *BuildExceptionDeclaration(Scope *S,
1837                                     TypeSourceInfo *TInfo,
1838                                     IdentifierInfo *Name,
1839                                     SourceLocation Loc);
1840  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
1841
1842  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
1843                                Decl *ExDecl, Stmt *HandlerBlock);
1844  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
1845                              MultiStmtArg Handlers);
1846  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
1847
1848  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
1849
1850  /// \brief If it's a file scoped decl that must warn if not used, keep track
1851  /// of it.
1852  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
1853
1854  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
1855  /// whose result is unused, warn.
1856  void DiagnoseUnusedExprResult(const Stmt *S);
1857  void DiagnoseUnusedDecl(const NamedDecl *ND);
1858
1859  ParsingDeclState PushParsingDeclaration() {
1860    return DelayedDiagnostics.pushParsingDecl();
1861  }
1862  void PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
1863    DelayedDiagnostics::popParsingDecl(*this, state, decl);
1864  }
1865
1866  typedef ProcessingContextState ParsingClassState;
1867  ParsingClassState PushParsingClass() {
1868    return DelayedDiagnostics.pushContext();
1869  }
1870  void PopParsingClass(ParsingClassState state) {
1871    DelayedDiagnostics.popContext(state);
1872  }
1873
1874  void EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
1875                              SourceLocation Loc, bool UnknownObjCClass=false);
1876
1877  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1878
1879  //===--------------------------------------------------------------------===//
1880  // Expression Parsing Callbacks: SemaExpr.cpp.
1881
1882  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
1883                         bool UnknownObjCClass=false);
1884  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
1885                                        ObjCMethodDecl *Getter,
1886                                        SourceLocation Loc);
1887  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
1888                             Expr **Args, unsigned NumArgs);
1889
1890  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext);
1891
1892  void PopExpressionEvaluationContext();
1893
1894  void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
1895  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
1896  void MarkDeclarationsReferencedInExpr(Expr *E);
1897
1898  /// \brief Conditionally issue a diagnostic based on the current
1899  /// evaluation context.
1900  ///
1901  /// \param stmt - If stmt is non-null, delay reporting the diagnostic until
1902  ///  the function body is parsed, and then do a basic reachability analysis to
1903  ///  determine if the statement is reachable.  If it is unreachable, the
1904  ///  diagnostic will not be emitted.
1905  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
1906                           const PartialDiagnostic &PD);
1907
1908  // Primary Expressions.
1909  SourceRange getExprRange(Expr *E) const;
1910
1911  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Name,
1912                               bool HasTrailingLParen, bool IsAddressOfOperand);
1913
1914  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1915                           CorrectTypoContext CTC = CTC_Unknown);
1916
1917  ExprResult LookupInObjCMethod(LookupResult &R, Scope *S, IdentifierInfo *II,
1918                                bool AllowBuiltinCreation=false);
1919
1920  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
1921                                        const DeclarationNameInfo &NameInfo,
1922                                        bool isAddressOfOperand,
1923                                const TemplateArgumentListInfo *TemplateArgs);
1924
1925  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
1926                              ExprValueKind VK,
1927                              SourceLocation Loc,
1928                              const CXXScopeSpec *SS = 0);
1929  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
1930                              ExprValueKind VK,
1931                              const DeclarationNameInfo &NameInfo,
1932                              const CXXScopeSpec *SS = 0);
1933  ExprResult
1934  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1935                                           SourceLocation nameLoc,
1936                                           IndirectFieldDecl *indirectField,
1937                                           Expr *baseObjectExpr = 0,
1938                                      SourceLocation opLoc = SourceLocation());
1939  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1940                                             LookupResult &R,
1941                                const TemplateArgumentListInfo *TemplateArgs);
1942  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1943                                     LookupResult &R,
1944                                const TemplateArgumentListInfo *TemplateArgs,
1945                                     bool IsDefiniteInstance);
1946  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
1947                                  const LookupResult &R,
1948                                  bool HasTrailingLParen);
1949
1950  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1951                                         const DeclarationNameInfo &NameInfo);
1952  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
1953                                const DeclarationNameInfo &NameInfo,
1954                                const TemplateArgumentListInfo *TemplateArgs);
1955
1956  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1957                                      LookupResult &R,
1958                                      bool ADL);
1959  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1960                                      const DeclarationNameInfo &NameInfo,
1961                                      NamedDecl *D);
1962
1963  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
1964  ExprResult ActOnNumericConstant(const Token &);
1965  ExprResult ActOnCharacterConstant(const Token &);
1966  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *Val);
1967  ExprResult ActOnParenOrParenListExpr(SourceLocation L,
1968                                       SourceLocation R,
1969                                       MultiExprArg Val,
1970                                       ParsedType TypeOfCast = ParsedType());
1971
1972  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1973  /// fragments (e.g. "foo" "bar" L"baz").
1974  ExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks);
1975
1976  // Binary/Unary Operators.  'Tok' is the token for the operator.
1977  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
1978                                  Expr *InputArg);
1979  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
1980                          UnaryOperatorKind Opc, Expr *input);
1981  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
1982                          tok::TokenKind Op, Expr *Input);
1983
1984  ExprResult CreateSizeOfAlignOfExpr(TypeSourceInfo *T,
1985                                     SourceLocation OpLoc,
1986                                     bool isSizeOf, SourceRange R);
1987  ExprResult CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1988                                     bool isSizeOf, SourceRange R);
1989  ExprResult
1990    ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1991                           void *TyOrEx, const SourceRange &ArgRange);
1992
1993  ExprResult CheckPlaceholderExpr(Expr *E, SourceLocation Loc);
1994
1995  bool CheckSizeOfAlignOfOperand(QualType type, SourceLocation OpLoc,
1996                                 SourceRange R, bool isSizeof);
1997  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
1998                                          SourceLocation OpLoc,
1999                                          IdentifierInfo &Name,
2000                                          SourceLocation NameLoc,
2001                                          SourceLocation RParenLoc);
2002  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2003                                 tok::TokenKind Kind, Expr *Input);
2004
2005  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2006                                     Expr *Idx, SourceLocation RLoc);
2007  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2008                                             Expr *Idx, SourceLocation RLoc);
2009
2010  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2011                                      SourceLocation OpLoc, bool IsArrow,
2012                                      CXXScopeSpec &SS,
2013                                      NamedDecl *FirstQualifierInScope,
2014                                const DeclarationNameInfo &NameInfo,
2015                                const TemplateArgumentListInfo *TemplateArgs);
2016
2017  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2018                                      SourceLocation OpLoc, bool IsArrow,
2019                                      const CXXScopeSpec &SS,
2020                                      NamedDecl *FirstQualifierInScope,
2021                                      LookupResult &R,
2022                                 const TemplateArgumentListInfo *TemplateArgs,
2023                                      bool SuppressQualifierCheck = false);
2024
2025  ExprResult LookupMemberExpr(LookupResult &R, Expr *&Base,
2026                              bool &IsArrow, SourceLocation OpLoc,
2027                              CXXScopeSpec &SS,
2028                              Decl *ObjCImpDecl,
2029                              bool HasTemplateArgs);
2030
2031  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
2032                                     const CXXScopeSpec &SS,
2033                                     const LookupResult &R);
2034
2035  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
2036                                      bool IsArrow, SourceLocation OpLoc,
2037                                      const CXXScopeSpec &SS,
2038                                      NamedDecl *FirstQualifierInScope,
2039                               const DeclarationNameInfo &NameInfo,
2040                               const TemplateArgumentListInfo *TemplateArgs);
2041
2042  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
2043                                   SourceLocation OpLoc,
2044                                   tok::TokenKind OpKind,
2045                                   CXXScopeSpec &SS,
2046                                   UnqualifiedId &Member,
2047                                   Decl *ObjCImpDecl,
2048                                   bool HasTrailingLParen);
2049
2050  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
2051  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2052                               FunctionDecl *FDecl,
2053                               const FunctionProtoType *Proto,
2054                               Expr **Args, unsigned NumArgs,
2055                               SourceLocation RParenLoc);
2056
2057  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2058  /// This provides the location of the left/right parens and a list of comma
2059  /// locations.
2060  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
2061                           MultiExprArg Args, SourceLocation RParenLoc,
2062                           Expr *ExecConfig = 0);
2063  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
2064                                   SourceLocation LParenLoc,
2065                                   Expr **Args, unsigned NumArgs,
2066                                   SourceLocation RParenLoc,
2067                                   Expr *ExecConfig = 0);
2068
2069  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
2070                                MultiExprArg ExecConfig, SourceLocation GGGLoc);
2071
2072  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
2073                           ParsedType Ty, SourceLocation RParenLoc,
2074                           Expr *Op);
2075  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
2076                                 TypeSourceInfo *Ty,
2077                                 SourceLocation RParenLoc,
2078                                 Expr *Op);
2079
2080  bool TypeIsVectorType(ParsedType Ty) {
2081    return GetTypeFromParser(Ty)->isVectorType();
2082  }
2083
2084  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
2085  ExprResult ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
2086                                      SourceLocation RParenLoc, Expr *E,
2087                                      TypeSourceInfo *TInfo);
2088
2089  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
2090                                  ParsedType Ty,
2091                                  SourceLocation RParenLoc,
2092                                  Expr *Op);
2093
2094  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
2095                                      TypeSourceInfo *TInfo,
2096                                      SourceLocation RParenLoc,
2097                                      Expr *InitExpr);
2098
2099  ExprResult ActOnInitList(SourceLocation LParenLoc,
2100                           MultiExprArg InitList,
2101                           SourceLocation RParenLoc);
2102
2103  ExprResult ActOnDesignatedInitializer(Designation &Desig,
2104                                        SourceLocation Loc,
2105                                        bool GNUSyntax,
2106                                        ExprResult Init);
2107
2108  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
2109                        tok::TokenKind Kind, Expr *LHS, Expr *RHS);
2110  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
2111                        BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2112  ExprResult CreateBuiltinBinOp(SourceLocation TokLoc,
2113                                BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2114
2115  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2116  /// in the case of a the GNU conditional expr extension.
2117  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
2118                                SourceLocation ColonLoc,
2119                                Expr *Cond, Expr *LHS, Expr *RHS);
2120
2121  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2122  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
2123                            LabelDecl *LD);
2124
2125  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
2126                           SourceLocation RPLoc); // "({..})"
2127
2128  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2129  struct OffsetOfComponent {
2130    SourceLocation LocStart, LocEnd;
2131    bool isBrackets;  // true if [expr], false if .ident
2132    union {
2133      IdentifierInfo *IdentInfo;
2134      ExprTy *E;
2135    } U;
2136  };
2137
2138  /// __builtin_offsetof(type, a.b[123][456].c)
2139  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
2140                                  TypeSourceInfo *TInfo,
2141                                  OffsetOfComponent *CompPtr,
2142                                  unsigned NumComponents,
2143                                  SourceLocation RParenLoc);
2144  ExprResult ActOnBuiltinOffsetOf(Scope *S,
2145                                  SourceLocation BuiltinLoc,
2146                                  SourceLocation TypeLoc,
2147                                  ParsedType Arg1,
2148                                  OffsetOfComponent *CompPtr,
2149                                  unsigned NumComponents,
2150                                  SourceLocation RParenLoc);
2151
2152  // __builtin_choose_expr(constExpr, expr1, expr2)
2153  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
2154                             Expr *cond, Expr *expr1,
2155                             Expr *expr2, SourceLocation RPLoc);
2156
2157  // __builtin_va_arg(expr, type)
2158  ExprResult ActOnVAArg(SourceLocation BuiltinLoc,
2159                        Expr *expr, ParsedType type,
2160                        SourceLocation RPLoc);
2161  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc,
2162                            Expr *expr, TypeSourceInfo *TInfo,
2163                            SourceLocation RPLoc);
2164
2165  // __null
2166  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
2167
2168  //===------------------------- "Block" Extension ------------------------===//
2169
2170  /// ActOnBlockStart - This callback is invoked when a block literal is
2171  /// started.
2172  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
2173
2174  /// ActOnBlockArguments - This callback allows processing of block arguments.
2175  /// If there are no arguments, this is still invoked.
2176  void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
2177
2178  /// ActOnBlockError - If there is an error parsing a block, this callback
2179  /// is invoked to pop the information about the block from the action impl.
2180  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
2181
2182  /// ActOnBlockStmtExpr - This is called when the body of a block statement
2183  /// literal was successfully completed.  ^(int x){...}
2184  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc,
2185                                        Stmt *Body, Scope *CurScope);
2186
2187  //===---------------------------- C++ Features --------------------------===//
2188
2189  // Act on C++ namespaces
2190  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
2191                               SourceLocation IdentLoc,
2192                               IdentifierInfo *Ident,
2193                               SourceLocation LBrace,
2194                               AttributeList *AttrList);
2195  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
2196
2197  NamespaceDecl *getStdNamespace() const;
2198  NamespaceDecl *getOrCreateStdNamespace();
2199
2200  CXXRecordDecl *getStdBadAlloc() const;
2201
2202  Decl *ActOnUsingDirective(Scope *CurScope,
2203                            SourceLocation UsingLoc,
2204                            SourceLocation NamespcLoc,
2205                            CXXScopeSpec &SS,
2206                            SourceLocation IdentLoc,
2207                            IdentifierInfo *NamespcName,
2208                            AttributeList *AttrList);
2209
2210  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
2211
2212  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
2213                               SourceLocation NamespaceLoc,
2214                               SourceLocation AliasLoc,
2215                               IdentifierInfo *Alias,
2216                               CXXScopeSpec &SS,
2217                               SourceLocation IdentLoc,
2218                               IdentifierInfo *Ident);
2219
2220  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
2221  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
2222                            const LookupResult &PreviousDecls);
2223  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
2224                                        NamedDecl *Target);
2225
2226  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
2227                                   bool isTypeName,
2228                                   const CXXScopeSpec &SS,
2229                                   SourceLocation NameLoc,
2230                                   const LookupResult &Previous);
2231  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
2232                               const CXXScopeSpec &SS,
2233                               SourceLocation NameLoc);
2234
2235  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2236                                   SourceLocation UsingLoc,
2237                                   CXXScopeSpec &SS,
2238                                   const DeclarationNameInfo &NameInfo,
2239                                   AttributeList *AttrList,
2240                                   bool IsInstantiation,
2241                                   bool IsTypeName,
2242                                   SourceLocation TypenameLoc);
2243
2244  bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
2245
2246  Decl *ActOnUsingDeclaration(Scope *CurScope,
2247                              AccessSpecifier AS,
2248                              bool HasUsingKeyword,
2249                              SourceLocation UsingLoc,
2250                              CXXScopeSpec &SS,
2251                              UnqualifiedId &Name,
2252                              AttributeList *AttrList,
2253                              bool IsTypeName,
2254                              SourceLocation TypenameLoc);
2255
2256  /// AddCXXDirectInitializerToDecl - This action is called immediately after
2257  /// ActOnDeclarator, when a C++ direct initializer is present.
2258  /// e.g: "int x(1);"
2259  void AddCXXDirectInitializerToDecl(Decl *Dcl,
2260                                     SourceLocation LParenLoc,
2261                                     MultiExprArg Exprs,
2262                                     SourceLocation RParenLoc,
2263                                     bool TypeMayContainAuto);
2264
2265  /// InitializeVarWithConstructor - Creates an CXXConstructExpr
2266  /// and sets it as the initializer for the the passed in VarDecl.
2267  bool InitializeVarWithConstructor(VarDecl *VD,
2268                                    CXXConstructorDecl *Constructor,
2269                                    MultiExprArg Exprs);
2270
2271  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
2272  /// including handling of its default argument expressions.
2273  ///
2274  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
2275  ExprResult
2276  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2277                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
2278                        bool RequiresZeroInit, unsigned ConstructKind,
2279                        SourceRange ParenRange);
2280
2281  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
2282  // the constructor can be elidable?
2283  ExprResult
2284  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2285                        CXXConstructorDecl *Constructor, bool Elidable,
2286                        MultiExprArg Exprs, bool RequiresZeroInit,
2287                        unsigned ConstructKind,
2288                        SourceRange ParenRange);
2289
2290  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
2291  /// the default expr if needed.
2292  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2293                                    FunctionDecl *FD,
2294                                    ParmVarDecl *Param);
2295
2296  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
2297  /// constructed variable.
2298  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
2299
2300  /// \brief Declare the implicit default constructor for the given class.
2301  ///
2302  /// \param ClassDecl The class declaration into which the implicit
2303  /// default constructor will be added.
2304  ///
2305  /// \returns The implicitly-declared default constructor.
2306  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
2307                                                     CXXRecordDecl *ClassDecl);
2308
2309  /// DefineImplicitDefaultConstructor - Checks for feasibility of
2310  /// defining this constructor as the default constructor.
2311  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2312                                        CXXConstructorDecl *Constructor);
2313
2314  /// \brief Declare the implicit destructor for the given class.
2315  ///
2316  /// \param ClassDecl The class declaration into which the implicit
2317  /// destructor will be added.
2318  ///
2319  /// \returns The implicitly-declared destructor.
2320  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
2321
2322  /// DefineImplicitDestructor - Checks for feasibility of
2323  /// defining this destructor as the default destructor.
2324  void DefineImplicitDestructor(SourceLocation CurrentLocation,
2325                                CXXDestructorDecl *Destructor);
2326
2327  /// \brief Declare all inherited constructors for the given class.
2328  ///
2329  /// \param ClassDecl The class declaration into which the inherited
2330  /// constructors will be added.
2331  void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
2332
2333  /// \brief Declare the implicit copy constructor for the given class.
2334  ///
2335  /// \param S The scope of the class, which may be NULL if this is a
2336  /// template instantiation.
2337  ///
2338  /// \param ClassDecl The class declaration into which the implicit
2339  /// copy constructor will be added.
2340  ///
2341  /// \returns The implicitly-declared copy constructor.
2342  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
2343
2344  /// DefineImplicitCopyConstructor - Checks for feasibility of
2345  /// defining this constructor as the copy constructor.
2346  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2347                                     CXXConstructorDecl *Constructor,
2348                                     unsigned TypeQuals);
2349
2350  /// \brief Declare the implicit copy assignment operator for the given class.
2351  ///
2352  /// \param S The scope of the class, which may be NULL if this is a
2353  /// template instantiation.
2354  ///
2355  /// \param ClassDecl The class declaration into which the implicit
2356  /// copy-assignment operator will be added.
2357  ///
2358  /// \returns The implicitly-declared copy assignment operator.
2359  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
2360
2361  /// \brief Defined an implicitly-declared copy assignment operator.
2362  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
2363                                    CXXMethodDecl *MethodDecl);
2364
2365  /// \brief Force the declaration of any implicitly-declared members of this
2366  /// class.
2367  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
2368
2369  /// MaybeBindToTemporary - If the passed in expression has a record type with
2370  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
2371  /// it simply returns the passed in expression.
2372  ExprResult MaybeBindToTemporary(Expr *E);
2373
2374  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
2375                               MultiExprArg ArgsPtr,
2376                               SourceLocation Loc,
2377                               ASTOwningVector<Expr*> &ConvertedArgs);
2378
2379  ParsedType getDestructorName(SourceLocation TildeLoc,
2380                               IdentifierInfo &II, SourceLocation NameLoc,
2381                               Scope *S, CXXScopeSpec &SS,
2382                               ParsedType ObjectType,
2383                               bool EnteringContext);
2384
2385  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
2386  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
2387                               tok::TokenKind Kind,
2388                               SourceLocation LAngleBracketLoc,
2389                               ParsedType Ty,
2390                               SourceLocation RAngleBracketLoc,
2391                               SourceLocation LParenLoc,
2392                               Expr *E,
2393                               SourceLocation RParenLoc);
2394
2395  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
2396                               tok::TokenKind Kind,
2397                               TypeSourceInfo *Ty,
2398                               Expr *E,
2399                               SourceRange AngleBrackets,
2400                               SourceRange Parens);
2401
2402  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2403                            SourceLocation TypeidLoc,
2404                            TypeSourceInfo *Operand,
2405                            SourceLocation RParenLoc);
2406  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2407                            SourceLocation TypeidLoc,
2408                            Expr *Operand,
2409                            SourceLocation RParenLoc);
2410
2411  /// ActOnCXXTypeid - Parse typeid( something ).
2412  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
2413                            SourceLocation LParenLoc, bool isType,
2414                            void *TyOrExpr,
2415                            SourceLocation RParenLoc);
2416
2417  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2418                            SourceLocation TypeidLoc,
2419                            TypeSourceInfo *Operand,
2420                            SourceLocation RParenLoc);
2421  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2422                            SourceLocation TypeidLoc,
2423                            Expr *Operand,
2424                            SourceLocation RParenLoc);
2425
2426  /// ActOnCXXUuidof - Parse __uuidof( something ).
2427  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
2428                            SourceLocation LParenLoc, bool isType,
2429                            void *TyOrExpr,
2430                            SourceLocation RParenLoc);
2431
2432
2433  //// ActOnCXXThis -  Parse 'this' pointer.
2434  ExprResult ActOnCXXThis(SourceLocation loc);
2435
2436  /// tryCaptureCXXThis - Try to capture a 'this' pointer.  Returns a
2437  /// pointer to an instance method whose 'this' pointer is
2438  /// capturable, or null if this is not possible.
2439  CXXMethodDecl *tryCaptureCXXThis();
2440
2441  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
2442  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
2443
2444  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
2445  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
2446
2447  //// ActOnCXXThrow -  Parse throw expressions.
2448  ExprResult ActOnCXXThrow(SourceLocation OpLoc, Expr *expr);
2449  bool CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E);
2450
2451  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
2452  /// Can be interpreted either as function-style casting ("int(x)")
2453  /// or class type construction ("ClassType(x,y,z)")
2454  /// or creation of a value-initialized type ("int()").
2455  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
2456                                       SourceLocation LParenLoc,
2457                                       MultiExprArg Exprs,
2458                                       SourceLocation RParenLoc);
2459
2460  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
2461                                       SourceLocation LParenLoc,
2462                                       MultiExprArg Exprs,
2463                                       SourceLocation RParenLoc);
2464
2465  /// ActOnCXXNew - Parsed a C++ 'new' expression.
2466  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2467                         SourceLocation PlacementLParen,
2468                         MultiExprArg PlacementArgs,
2469                         SourceLocation PlacementRParen,
2470                         SourceRange TypeIdParens, Declarator &D,
2471                         SourceLocation ConstructorLParen,
2472                         MultiExprArg ConstructorArgs,
2473                         SourceLocation ConstructorRParen);
2474  ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
2475                         SourceLocation PlacementLParen,
2476                         MultiExprArg PlacementArgs,
2477                         SourceLocation PlacementRParen,
2478                         SourceRange TypeIdParens,
2479                         QualType AllocType,
2480                         TypeSourceInfo *AllocTypeInfo,
2481                         Expr *ArraySize,
2482                         SourceLocation ConstructorLParen,
2483                         MultiExprArg ConstructorArgs,
2484                         SourceLocation ConstructorRParen,
2485                         bool TypeMayContainAuto = true);
2486
2487  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2488                          SourceRange R);
2489  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2490                               bool UseGlobal, QualType AllocType, bool IsArray,
2491                               Expr **PlaceArgs, unsigned NumPlaceArgs,
2492                               FunctionDecl *&OperatorNew,
2493                               FunctionDecl *&OperatorDelete);
2494  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
2495                              DeclarationName Name, Expr** Args,
2496                              unsigned NumArgs, DeclContext *Ctx,
2497                              bool AllowMissing, FunctionDecl *&Operator);
2498  void DeclareGlobalNewDelete();
2499  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
2500                                       QualType Argument,
2501                                       bool addMallocAttr = false);
2502
2503  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2504                                DeclarationName Name, FunctionDecl* &Operator);
2505
2506  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
2507  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
2508                            bool UseGlobal, bool ArrayForm,
2509                            Expr *Operand);
2510
2511  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
2512  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
2513                                    SourceLocation StmtLoc,
2514                                    bool ConvertToBoolean);
2515
2516  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
2517                               Expr *Operand, SourceLocation RParen);
2518  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
2519                                  SourceLocation RParen);
2520
2521  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
2522  /// pseudo-functions.
2523  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
2524                                 SourceLocation KWLoc,
2525                                 ParsedType Ty,
2526                                 SourceLocation RParen);
2527
2528  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
2529                                 SourceLocation KWLoc,
2530                                 TypeSourceInfo *T,
2531                                 SourceLocation RParen);
2532
2533  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
2534  /// pseudo-functions.
2535  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
2536                                  SourceLocation KWLoc,
2537                                  ParsedType LhsTy,
2538                                  ParsedType RhsTy,
2539                                  SourceLocation RParen);
2540
2541  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2542                                  SourceLocation KWLoc,
2543                                  TypeSourceInfo *LhsT,
2544                                  TypeSourceInfo *RhsT,
2545                                  SourceLocation RParen);
2546
2547  ExprResult ActOnStartCXXMemberReference(Scope *S,
2548                                          Expr *Base,
2549                                          SourceLocation OpLoc,
2550                                          tok::TokenKind OpKind,
2551                                          ParsedType &ObjectType,
2552                                          bool &MayBePseudoDestructor);
2553
2554  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
2555
2556  ExprResult BuildPseudoDestructorExpr(Expr *Base,
2557                                       SourceLocation OpLoc,
2558                                       tok::TokenKind OpKind,
2559                                       const CXXScopeSpec &SS,
2560                                       TypeSourceInfo *ScopeType,
2561                                       SourceLocation CCLoc,
2562                                       SourceLocation TildeLoc,
2563                                     PseudoDestructorTypeStorage DestroyedType,
2564                                       bool HasTrailingLParen);
2565
2566  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
2567                                       SourceLocation OpLoc,
2568                                       tok::TokenKind OpKind,
2569                                       CXXScopeSpec &SS,
2570                                       UnqualifiedId &FirstTypeName,
2571                                       SourceLocation CCLoc,
2572                                       SourceLocation TildeLoc,
2573                                       UnqualifiedId &SecondTypeName,
2574                                       bool HasTrailingLParen);
2575
2576  /// MaybeCreateExprWithCleanups - If the current full-expression
2577  /// requires any cleanups, surround it with a ExprWithCleanups node.
2578  /// Otherwise, just returns the passed-in expression.
2579  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
2580  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
2581  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
2582
2583  ExprResult ActOnFinishFullExpr(Expr *Expr);
2584  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
2585
2586  // Marks SS invalid if it represents an incomplete type.
2587  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
2588
2589  DeclContext *computeDeclContext(QualType T);
2590  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
2591                                  bool EnteringContext = false);
2592  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
2593  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
2594  bool isUnknownSpecialization(const CXXScopeSpec &SS);
2595
2596  /// \brief The parser has parsed a global nested-name-specifier '::'.
2597  ///
2598  /// \param S The scope in which this nested-name-specifier occurs.
2599  ///
2600  /// \param CCLoc The location of the '::'.
2601  ///
2602  /// \param SS The nested-name-specifier, which will be updated in-place
2603  /// to reflect the parsed nested-name-specifier.
2604  ///
2605  /// \returns true if an error occurred, false otherwise.
2606  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
2607                                    CXXScopeSpec &SS);
2608
2609  bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
2610  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
2611
2612  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
2613                                    SourceLocation IdLoc,
2614                                    IdentifierInfo &II,
2615                                    ParsedType ObjectType);
2616
2617  bool BuildCXXNestedNameSpecifier(Scope *S,
2618                                   IdentifierInfo &Identifier,
2619                                   SourceLocation IdentifierLoc,
2620                                   SourceLocation CCLoc,
2621                                   QualType ObjectType,
2622                                   bool EnteringContext,
2623                                   CXXScopeSpec &SS,
2624                                   NamedDecl *ScopeLookupResult,
2625                                   bool ErrorRecoveryLookup);
2626
2627  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
2628  ///
2629  /// \param S The scope in which this nested-name-specifier occurs.
2630  ///
2631  /// \param Identifier The identifier preceding the '::'.
2632  ///
2633  /// \param IdentifierLoc The location of the identifier.
2634  ///
2635  /// \param CCLoc The location of the '::'.
2636  ///
2637  /// \param ObjectType The type of the object, if we're parsing
2638  /// nested-name-specifier in a member access expression.
2639  ///
2640  /// \param EnteringContext Whether we're entering the context nominated by
2641  /// this nested-name-specifier.
2642  ///
2643  /// \param SS The nested-name-specifier, which is both an input
2644  /// parameter (the nested-name-specifier before this type) and an
2645  /// output parameter (containing the full nested-name-specifier,
2646  /// including this new type).
2647  ///
2648  /// \returns true if an error occurred, false otherwise.
2649  bool ActOnCXXNestedNameSpecifier(Scope *S,
2650                                   IdentifierInfo &Identifier,
2651                                   SourceLocation IdentifierLoc,
2652                                   SourceLocation CCLoc,
2653                                   ParsedType ObjectType,
2654                                   bool EnteringContext,
2655                                   CXXScopeSpec &SS);
2656
2657  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
2658                                 IdentifierInfo &Identifier,
2659                                 SourceLocation IdentifierLoc,
2660                                 SourceLocation ColonLoc,
2661                                 ParsedType ObjectType,
2662                                 bool EnteringContext);
2663
2664  /// \brief The parser has parsed a nested-name-specifier
2665  /// 'template[opt] template-name < template-args >::'.
2666  ///
2667  /// \param S The scope in which this nested-name-specifier occurs.
2668  ///
2669  /// \param TemplateLoc The location of the 'template' keyword, if any.
2670  ///
2671  /// \param SS The nested-name-specifier, which is both an input
2672  /// parameter (the nested-name-specifier before this type) and an
2673  /// output parameter (containing the full nested-name-specifier,
2674  /// including this new type).
2675  ///
2676  /// \param TemplateLoc the location of the 'template' keyword, if any.
2677  /// \param TemplateName The template name.
2678  /// \param TemplateNameLoc The location of the template name.
2679  /// \param LAngleLoc The location of the opening angle bracket  ('<').
2680  /// \param TemplateArgs The template arguments.
2681  /// \param RAngleLoc The location of the closing angle bracket  ('>').
2682  /// \param CCLoc The location of the '::'.
2683
2684  /// \param EnteringContext Whether we're entering the context of the
2685  /// nested-name-specifier.
2686  ///
2687  ///
2688  /// \returns true if an error occurred, false otherwise.
2689  bool ActOnCXXNestedNameSpecifier(Scope *S,
2690                                   SourceLocation TemplateLoc,
2691                                   CXXScopeSpec &SS,
2692                                   TemplateTy Template,
2693                                   SourceLocation TemplateNameLoc,
2694                                   SourceLocation LAngleLoc,
2695                                   ASTTemplateArgsPtr TemplateArgs,
2696                                   SourceLocation RAngleLoc,
2697                                   SourceLocation CCLoc,
2698                                   bool EnteringContext);
2699
2700  /// \brief Given a C++ nested-name-specifier, produce an annotation value
2701  /// that the parser can use later to reconstruct the given
2702  /// nested-name-specifier.
2703  ///
2704  /// \param SS A nested-name-specifier.
2705  ///
2706  /// \returns A pointer containing all of the information in the
2707  /// nested-name-specifier \p SS.
2708  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
2709
2710  /// \brief Given an annotation pointer for a nested-name-specifier, restore
2711  /// the nested-name-specifier structure.
2712  ///
2713  /// \param Annotation The annotation pointer, produced by
2714  /// \c SaveNestedNameSpecifierAnnotation().
2715  ///
2716  /// \param AnnotationRange The source range corresponding to the annotation.
2717  ///
2718  /// \param SS The nested-name-specifier that will be updated with the contents
2719  /// of the annotation pointer.
2720  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
2721                                            SourceRange AnnotationRange,
2722                                            CXXScopeSpec &SS);
2723
2724  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2725
2726  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
2727  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
2728  /// After this method is called, according to [C++ 3.4.3p3], names should be
2729  /// looked up in the declarator-id's scope, until the declarator is parsed and
2730  /// ActOnCXXExitDeclaratorScope is called.
2731  /// The 'SS' should be a non-empty valid CXXScopeSpec.
2732  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
2733
2734  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
2735  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
2736  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
2737  /// Used to indicate that names should revert to being looked up in the
2738  /// defining scope.
2739  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2740
2741  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
2742  /// initializer for the declaration 'Dcl'.
2743  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
2744  /// static data member of class X, names should be looked up in the scope of
2745  /// class X.
2746  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
2747
2748  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
2749  /// initializer for the declaration 'Dcl'.
2750  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
2751
2752  // ParseObjCStringLiteral - Parse Objective-C string literals.
2753  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
2754                                    Expr **Strings,
2755                                    unsigned NumStrings);
2756
2757  Expr *BuildObjCEncodeExpression(SourceLocation AtLoc,
2758                                  TypeSourceInfo *EncodedTypeInfo,
2759                                  SourceLocation RParenLoc);
2760  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
2761                                    CXXMethodDecl *Method);
2762
2763  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
2764                                       SourceLocation EncodeLoc,
2765                                       SourceLocation LParenLoc,
2766                                       ParsedType Ty,
2767                                       SourceLocation RParenLoc);
2768
2769  // ParseObjCSelectorExpression - Build selector expression for @selector
2770  ExprResult ParseObjCSelectorExpression(Selector Sel,
2771                                         SourceLocation AtLoc,
2772                                         SourceLocation SelLoc,
2773                                         SourceLocation LParenLoc,
2774                                         SourceLocation RParenLoc);
2775
2776  // ParseObjCProtocolExpression - Build protocol expression for @protocol
2777  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
2778                                         SourceLocation AtLoc,
2779                                         SourceLocation ProtoLoc,
2780                                         SourceLocation LParenLoc,
2781                                         SourceLocation RParenLoc);
2782
2783  //===--------------------------------------------------------------------===//
2784  // C++ Declarations
2785  //
2786  Decl *ActOnStartLinkageSpecification(Scope *S,
2787                                       SourceLocation ExternLoc,
2788                                       SourceLocation LangLoc,
2789                                       llvm::StringRef Lang,
2790                                       SourceLocation LBraceLoc);
2791  Decl *ActOnFinishLinkageSpecification(Scope *S,
2792                                        Decl *LinkageSpec,
2793                                        SourceLocation RBraceLoc);
2794
2795
2796  //===--------------------------------------------------------------------===//
2797  // C++ Classes
2798  //
2799  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
2800                          const CXXScopeSpec *SS = 0);
2801
2802  Decl *ActOnAccessSpecifier(AccessSpecifier Access,
2803                             SourceLocation ASLoc,
2804                             SourceLocation ColonLoc);
2805
2806  Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
2807                                 Declarator &D,
2808                                 MultiTemplateParamsArg TemplateParameterLists,
2809                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
2810                                 Expr *Init, bool IsDefinition,
2811                                 bool Deleted = false);
2812
2813  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
2814                                    Scope *S,
2815                                    CXXScopeSpec &SS,
2816                                    IdentifierInfo *MemberOrBase,
2817                                    ParsedType TemplateTypeTy,
2818                                    SourceLocation IdLoc,
2819                                    SourceLocation LParenLoc,
2820                                    Expr **Args, unsigned NumArgs,
2821                                    SourceLocation RParenLoc,
2822                                    SourceLocation EllipsisLoc);
2823
2824  MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr **Args,
2825                                       unsigned NumArgs, SourceLocation IdLoc,
2826                                       SourceLocation LParenLoc,
2827                                       SourceLocation RParenLoc);
2828
2829  MemInitResult BuildBaseInitializer(QualType BaseType,
2830                                     TypeSourceInfo *BaseTInfo,
2831                                     Expr **Args, unsigned NumArgs,
2832                                     SourceLocation LParenLoc,
2833                                     SourceLocation RParenLoc,
2834                                     CXXRecordDecl *ClassDecl,
2835                                     SourceLocation EllipsisLoc);
2836
2837  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
2838                                           Expr **Args, unsigned NumArgs,
2839                                           SourceLocation BaseLoc,
2840                                           SourceLocation RParenLoc,
2841                                           SourceLocation LParenLoc,
2842                                           CXXRecordDecl *ClassDecl);
2843
2844  bool SetCtorInitializers(CXXConstructorDecl *Constructor,
2845                           CXXCtorInitializer **Initializers,
2846                           unsigned NumInitializers, bool AnyErrors);
2847
2848  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
2849
2850
2851  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
2852  /// mark all the non-trivial destructors of its members and bases as
2853  /// referenced.
2854  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
2855                                              CXXRecordDecl *Record);
2856
2857  /// \brief The list of classes whose vtables have been used within
2858  /// this translation unit, and the source locations at which the
2859  /// first use occurred.
2860  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
2861
2862  /// \brief The list of vtables that are required but have not yet been
2863  /// materialized.
2864  llvm::SmallVector<VTableUse, 16> VTableUses;
2865
2866  /// \brief The set of classes whose vtables have been used within
2867  /// this translation unit, and a bit that will be true if the vtable is
2868  /// required to be emitted (otherwise, it should be emitted only if needed
2869  /// by code generation).
2870  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
2871
2872  /// \brief A list of all of the dynamic classes in this translation
2873  /// unit.
2874  llvm::SmallVector<CXXRecordDecl *, 16> DynamicClasses;
2875
2876  /// \brief Note that the vtable for the given class was used at the
2877  /// given location.
2878  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
2879                      bool DefinitionRequired = false);
2880
2881  /// MarkVirtualMembersReferenced - Will mark all members of the given
2882  /// CXXRecordDecl referenced.
2883  void MarkVirtualMembersReferenced(SourceLocation Loc,
2884                                    const CXXRecordDecl *RD);
2885
2886  /// \brief Define all of the vtables that have been used in this
2887  /// translation unit and reference any virtual members used by those
2888  /// vtables.
2889  ///
2890  /// \returns true if any work was done, false otherwise.
2891  bool DefineUsedVTables();
2892
2893  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
2894
2895  void ActOnMemInitializers(Decl *ConstructorDecl,
2896                            SourceLocation ColonLoc,
2897                            MemInitTy **MemInits, unsigned NumMemInits,
2898                            bool AnyErrors);
2899
2900  void CheckCompletedCXXClass(CXXRecordDecl *Record);
2901  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2902                                         Decl *TagDecl,
2903                                         SourceLocation LBrac,
2904                                         SourceLocation RBrac,
2905                                         AttributeList *AttrList);
2906
2907  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
2908  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
2909  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
2910  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
2911  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
2912  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
2913
2914  Decl *ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2915                                     Expr *AssertExpr,
2916                                     Expr *AssertMessageExpr);
2917
2918  FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
2919                                  TypeSourceInfo *TSInfo);
2920  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
2921                                MultiTemplateParamsArg TemplateParams);
2922  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
2923                                    MultiTemplateParamsArg TemplateParams);
2924
2925  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
2926                                      StorageClass& SC);
2927  void CheckConstructor(CXXConstructorDecl *Constructor);
2928  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
2929                                     StorageClass& SC);
2930  bool CheckDestructor(CXXDestructorDecl *Destructor);
2931  void CheckConversionDeclarator(Declarator &D, QualType &R,
2932                                 StorageClass& SC);
2933  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
2934
2935  //===--------------------------------------------------------------------===//
2936  // C++ Derived Classes
2937  //
2938
2939  /// ActOnBaseSpecifier - Parsed a base specifier
2940  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
2941                                       SourceRange SpecifierRange,
2942                                       bool Virtual, AccessSpecifier Access,
2943                                       TypeSourceInfo *TInfo,
2944                                       SourceLocation EllipsisLoc);
2945
2946  BaseResult ActOnBaseSpecifier(Decl *classdecl,
2947                                SourceRange SpecifierRange,
2948                                bool Virtual, AccessSpecifier Access,
2949                                ParsedType basetype,
2950                                SourceLocation BaseLoc,
2951                                SourceLocation EllipsisLoc);
2952
2953  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
2954                            unsigned NumBases);
2955  void ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, unsigned NumBases);
2956
2957  bool IsDerivedFrom(QualType Derived, QualType Base);
2958  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
2959
2960  // FIXME: I don't like this name.
2961  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
2962
2963  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
2964
2965  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2966                                    SourceLocation Loc, SourceRange Range,
2967                                    CXXCastPath *BasePath = 0,
2968                                    bool IgnoreAccess = false);
2969  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2970                                    unsigned InaccessibleBaseID,
2971                                    unsigned AmbigiousBaseConvID,
2972                                    SourceLocation Loc, SourceRange Range,
2973                                    DeclarationName Name,
2974                                    CXXCastPath *BasePath);
2975
2976  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
2977
2978  /// CheckOverridingFunctionReturnType - Checks whether the return types are
2979  /// covariant, according to C++ [class.virtual]p5.
2980  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
2981                                         const CXXMethodDecl *Old);
2982
2983  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
2984  /// spec is a subset of base spec.
2985  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
2986                                            const CXXMethodDecl *Old);
2987
2988  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
2989
2990  /// CheckOverrideControl - Check C++0x override control semantics.
2991  void CheckOverrideControl(const Decl *D);
2992
2993  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
2994  /// overrides a virtual member function marked 'final', according to
2995  /// C++0x [class.virtual]p3.
2996  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2997                                              const CXXMethodDecl *Old);
2998
2999
3000  //===--------------------------------------------------------------------===//
3001  // C++ Access Control
3002  //
3003
3004  enum AccessResult {
3005    AR_accessible,
3006    AR_inaccessible,
3007    AR_dependent,
3008    AR_delayed
3009  };
3010
3011  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
3012                                NamedDecl *PrevMemberDecl,
3013                                AccessSpecifier LexicalAS);
3014
3015  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
3016                                           DeclAccessPair FoundDecl);
3017  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
3018                                           DeclAccessPair FoundDecl);
3019  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
3020                                     SourceRange PlacementRange,
3021                                     CXXRecordDecl *NamingClass,
3022                                     DeclAccessPair FoundDecl);
3023  AccessResult CheckConstructorAccess(SourceLocation Loc,
3024                                      CXXConstructorDecl *D,
3025                                      const InitializedEntity &Entity,
3026                                      AccessSpecifier Access,
3027                                      bool IsCopyBindingRefToTemp = false);
3028  AccessResult CheckDestructorAccess(SourceLocation Loc,
3029                                     CXXDestructorDecl *Dtor,
3030                                     const PartialDiagnostic &PDiag);
3031  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
3032                                       NamedDecl *D,
3033                                       const PartialDiagnostic &PDiag);
3034  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
3035                                         Expr *ObjectExpr,
3036                                         Expr *ArgExpr,
3037                                         DeclAccessPair FoundDecl);
3038  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
3039                                          DeclAccessPair FoundDecl);
3040  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
3041                                    QualType Base, QualType Derived,
3042                                    const CXXBasePath &Path,
3043                                    unsigned DiagID,
3044                                    bool ForceCheck = false,
3045                                    bool ForceUnprivileged = false);
3046  void CheckLookupAccess(const LookupResult &R);
3047
3048  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
3049                         const MultiLevelTemplateArgumentList &TemplateArgs);
3050  void PerformDependentDiagnostics(const DeclContext *Pattern,
3051                        const MultiLevelTemplateArgumentList &TemplateArgs);
3052
3053  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3054
3055  /// A flag to suppress access checking.
3056  bool SuppressAccessChecking;
3057
3058  /// \brief When true, access checking violations are treated as SFINAE
3059  /// failures rather than hard errors.
3060  bool AccessCheckingSFINAE;
3061
3062  void ActOnStartSuppressingAccessChecks();
3063  void ActOnStopSuppressingAccessChecks();
3064
3065  enum AbstractDiagSelID {
3066    AbstractNone = -1,
3067    AbstractReturnType,
3068    AbstractParamType,
3069    AbstractVariableType,
3070    AbstractFieldType,
3071    AbstractArrayType
3072  };
3073
3074  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
3075                              const PartialDiagnostic &PD);
3076  void DiagnoseAbstractType(const CXXRecordDecl *RD);
3077
3078  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
3079                              AbstractDiagSelID SelID = AbstractNone);
3080
3081  //===--------------------------------------------------------------------===//
3082  // C++ Overloaded Operators [C++ 13.5]
3083  //
3084
3085  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
3086
3087  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
3088
3089  //===--------------------------------------------------------------------===//
3090  // C++ Templates [C++ 14]
3091  //
3092  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
3093                          QualType ObjectType, bool EnteringContext,
3094                          bool &MemberOfUnknownSpecialization);
3095
3096  TemplateNameKind isTemplateName(Scope *S,
3097                                          CXXScopeSpec &SS,
3098                                          bool hasTemplateKeyword,
3099                                          UnqualifiedId &Name,
3100                                          ParsedType ObjectType,
3101                                          bool EnteringContext,
3102                                          TemplateTy &Template,
3103                                          bool &MemberOfUnknownSpecialization);
3104
3105  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
3106                                   SourceLocation IILoc,
3107                                   Scope *S,
3108                                   const CXXScopeSpec *SS,
3109                                   TemplateTy &SuggestedTemplate,
3110                                   TemplateNameKind &SuggestedKind);
3111
3112  bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
3113  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
3114
3115  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
3116                           SourceLocation EllipsisLoc,
3117                           SourceLocation KeyLoc,
3118                           IdentifierInfo *ParamName,
3119                           SourceLocation ParamNameLoc,
3120                           unsigned Depth, unsigned Position,
3121                           SourceLocation EqualLoc,
3122                           ParsedType DefaultArg);
3123
3124  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
3125  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
3126                                      unsigned Depth,
3127                                      unsigned Position,
3128                                      SourceLocation EqualLoc,
3129                                      Expr *DefaultArg);
3130  Decl *ActOnTemplateTemplateParameter(Scope *S,
3131                                       SourceLocation TmpLoc,
3132                                       TemplateParamsTy *Params,
3133                                       SourceLocation EllipsisLoc,
3134                                       IdentifierInfo *ParamName,
3135                                       SourceLocation ParamNameLoc,
3136                                       unsigned Depth,
3137                                       unsigned Position,
3138                                       SourceLocation EqualLoc,
3139                                       ParsedTemplateArgument DefaultArg);
3140
3141  TemplateParamsTy *
3142  ActOnTemplateParameterList(unsigned Depth,
3143                             SourceLocation ExportLoc,
3144                             SourceLocation TemplateLoc,
3145                             SourceLocation LAngleLoc,
3146                             Decl **Params, unsigned NumParams,
3147                             SourceLocation RAngleLoc);
3148
3149  /// \brief The context in which we are checking a template parameter
3150  /// list.
3151  enum TemplateParamListContext {
3152    TPC_ClassTemplate,
3153    TPC_FunctionTemplate,
3154    TPC_ClassTemplateMember,
3155    TPC_FriendFunctionTemplate,
3156    TPC_FriendFunctionTemplateDefinition
3157  };
3158
3159  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
3160                                  TemplateParameterList *OldParams,
3161                                  TemplateParamListContext TPC);
3162  TemplateParameterList *
3163  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
3164                                          const CXXScopeSpec &SS,
3165                                          TemplateParameterList **ParamLists,
3166                                          unsigned NumParamLists,
3167                                          bool IsFriend,
3168                                          bool &IsExplicitSpecialization,
3169                                          bool &Invalid);
3170
3171  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
3172                                SourceLocation KWLoc, CXXScopeSpec &SS,
3173                                IdentifierInfo *Name, SourceLocation NameLoc,
3174                                AttributeList *Attr,
3175                                TemplateParameterList *TemplateParams,
3176                                AccessSpecifier AS);
3177
3178  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
3179                                  TemplateArgumentListInfo &Out);
3180
3181  QualType CheckTemplateIdType(TemplateName Template,
3182                               SourceLocation TemplateLoc,
3183                               const TemplateArgumentListInfo &TemplateArgs);
3184
3185  TypeResult
3186  ActOnTemplateIdType(CXXScopeSpec &SS,
3187                      TemplateTy Template, SourceLocation TemplateLoc,
3188                      SourceLocation LAngleLoc,
3189                      ASTTemplateArgsPtr TemplateArgs,
3190                      SourceLocation RAngleLoc);
3191
3192  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
3193  /// such as \c class T::template apply<U>.
3194  ///
3195  /// \param TUK
3196  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
3197                                    TypeSpecifierType TagSpec,
3198                                    SourceLocation TagLoc,
3199                                    CXXScopeSpec &SS,
3200                                    TemplateTy TemplateD,
3201                                    SourceLocation TemplateLoc,
3202                                    SourceLocation LAngleLoc,
3203                                    ASTTemplateArgsPtr TemplateArgsIn,
3204                                    SourceLocation RAngleLoc);
3205
3206
3207  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
3208                                 LookupResult &R,
3209                                 bool RequiresADL,
3210                               const TemplateArgumentListInfo &TemplateArgs);
3211  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3212                               const DeclarationNameInfo &NameInfo,
3213                               const TemplateArgumentListInfo &TemplateArgs);
3214
3215  TemplateNameKind ActOnDependentTemplateName(Scope *S,
3216                                              SourceLocation TemplateKWLoc,
3217                                              CXXScopeSpec &SS,
3218                                              UnqualifiedId &Name,
3219                                              ParsedType ObjectType,
3220                                              bool EnteringContext,
3221                                              TemplateTy &Template);
3222
3223  DeclResult
3224  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
3225                                   SourceLocation KWLoc,
3226                                   CXXScopeSpec &SS,
3227                                   TemplateTy Template,
3228                                   SourceLocation TemplateNameLoc,
3229                                   SourceLocation LAngleLoc,
3230                                   ASTTemplateArgsPtr TemplateArgs,
3231                                   SourceLocation RAngleLoc,
3232                                   AttributeList *Attr,
3233                                 MultiTemplateParamsArg TemplateParameterLists);
3234
3235  Decl *ActOnTemplateDeclarator(Scope *S,
3236                                MultiTemplateParamsArg TemplateParameterLists,
3237                                Declarator &D);
3238
3239  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3240                                  MultiTemplateParamsArg TemplateParameterLists,
3241                                        Declarator &D);
3242
3243  bool
3244  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3245                                         TemplateSpecializationKind NewTSK,
3246                                         NamedDecl *PrevDecl,
3247                                         TemplateSpecializationKind PrevTSK,
3248                                         SourceLocation PrevPtOfInstantiation,
3249                                         bool &SuppressNew);
3250
3251  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
3252                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
3253                                                    LookupResult &Previous);
3254
3255  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3256                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3257                                           LookupResult &Previous);
3258  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
3259
3260  DeclResult
3261  ActOnExplicitInstantiation(Scope *S,
3262                             SourceLocation ExternLoc,
3263                             SourceLocation TemplateLoc,
3264                             unsigned TagSpec,
3265                             SourceLocation KWLoc,
3266                             const CXXScopeSpec &SS,
3267                             TemplateTy Template,
3268                             SourceLocation TemplateNameLoc,
3269                             SourceLocation LAngleLoc,
3270                             ASTTemplateArgsPtr TemplateArgs,
3271                             SourceLocation RAngleLoc,
3272                             AttributeList *Attr);
3273
3274  DeclResult
3275  ActOnExplicitInstantiation(Scope *S,
3276                             SourceLocation ExternLoc,
3277                             SourceLocation TemplateLoc,
3278                             unsigned TagSpec,
3279                             SourceLocation KWLoc,
3280                             CXXScopeSpec &SS,
3281                             IdentifierInfo *Name,
3282                             SourceLocation NameLoc,
3283                             AttributeList *Attr);
3284
3285  DeclResult ActOnExplicitInstantiation(Scope *S,
3286                                        SourceLocation ExternLoc,
3287                                        SourceLocation TemplateLoc,
3288                                        Declarator &D);
3289
3290  TemplateArgumentLoc
3291  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3292                                          SourceLocation TemplateLoc,
3293                                          SourceLocation RAngleLoc,
3294                                          Decl *Param,
3295                          llvm::SmallVectorImpl<TemplateArgument> &Converted);
3296
3297  /// \brief Specifies the context in which a particular template
3298  /// argument is being checked.
3299  enum CheckTemplateArgumentKind {
3300    /// \brief The template argument was specified in the code or was
3301    /// instantiated with some deduced template arguments.
3302    CTAK_Specified,
3303
3304    /// \brief The template argument was deduced via template argument
3305    /// deduction.
3306    CTAK_Deduced,
3307
3308    /// \brief The template argument was deduced from an array bound
3309    /// via template argument deduction.
3310    CTAK_DeducedFromArrayBound
3311  };
3312
3313  bool CheckTemplateArgument(NamedDecl *Param,
3314                             const TemplateArgumentLoc &Arg,
3315                             NamedDecl *Template,
3316                             SourceLocation TemplateLoc,
3317                             SourceLocation RAngleLoc,
3318                             unsigned ArgumentPackIndex,
3319                           llvm::SmallVectorImpl<TemplateArgument> &Converted,
3320                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
3321
3322  bool CheckTemplateArgumentList(TemplateDecl *Template,
3323                                 SourceLocation TemplateLoc,
3324                                 const TemplateArgumentListInfo &TemplateArgs,
3325                                 bool PartialTemplateArgs,
3326                           llvm::SmallVectorImpl<TemplateArgument> &Converted);
3327
3328  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3329                                 const TemplateArgumentLoc &Arg,
3330                           llvm::SmallVectorImpl<TemplateArgument> &Converted);
3331
3332  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
3333                             TypeSourceInfo *Arg);
3334  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
3335                                            TemplateArgument &Converted);
3336  bool CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3337                             QualType InstantiatedParamType, Expr *&Arg,
3338                             TemplateArgument &Converted,
3339                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
3340  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3341                             const TemplateArgumentLoc &Arg);
3342
3343  ExprResult
3344  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3345                                          QualType ParamType,
3346                                          SourceLocation Loc);
3347  ExprResult
3348  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3349                                              SourceLocation Loc);
3350
3351  /// \brief Enumeration describing how template parameter lists are compared
3352  /// for equality.
3353  enum TemplateParameterListEqualKind {
3354    /// \brief We are matching the template parameter lists of two templates
3355    /// that might be redeclarations.
3356    ///
3357    /// \code
3358    /// template<typename T> struct X;
3359    /// template<typename T> struct X;
3360    /// \endcode
3361    TPL_TemplateMatch,
3362
3363    /// \brief We are matching the template parameter lists of two template
3364    /// template parameters as part of matching the template parameter lists
3365    /// of two templates that might be redeclarations.
3366    ///
3367    /// \code
3368    /// template<template<int I> class TT> struct X;
3369    /// template<template<int Value> class Other> struct X;
3370    /// \endcode
3371    TPL_TemplateTemplateParmMatch,
3372
3373    /// \brief We are matching the template parameter lists of a template
3374    /// template argument against the template parameter lists of a template
3375    /// template parameter.
3376    ///
3377    /// \code
3378    /// template<template<int Value> class Metafun> struct X;
3379    /// template<int Value> struct integer_c;
3380    /// X<integer_c> xic;
3381    /// \endcode
3382    TPL_TemplateTemplateArgumentMatch
3383  };
3384
3385  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
3386                                      TemplateParameterList *Old,
3387                                      bool Complain,
3388                                      TemplateParameterListEqualKind Kind,
3389                                      SourceLocation TemplateArgLoc
3390                                        = SourceLocation());
3391
3392  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
3393
3394  /// \brief Called when the parser has parsed a C++ typename
3395  /// specifier, e.g., "typename T::type".
3396  ///
3397  /// \param S The scope in which this typename type occurs.
3398  /// \param TypenameLoc the location of the 'typename' keyword
3399  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3400  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
3401  /// \param IdLoc the location of the identifier.
3402  TypeResult
3403  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3404                    const CXXScopeSpec &SS, const IdentifierInfo &II,
3405                    SourceLocation IdLoc);
3406
3407  /// \brief Called when the parser has parsed a C++ typename
3408  /// specifier that ends in a template-id, e.g.,
3409  /// "typename MetaFun::template apply<T1, T2>".
3410  ///
3411  /// \param S The scope in which this typename type occurs.
3412  /// \param TypenameLoc the location of the 'typename' keyword
3413  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3414  /// \param TemplateLoc the location of the 'template' keyword, if any.
3415  /// \param TemplateName The template name.
3416  /// \param TemplateNameLoc The location of the template name.
3417  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3418  /// \param TemplateArgs The template arguments.
3419  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3420  TypeResult
3421  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3422                    const CXXScopeSpec &SS,
3423                    SourceLocation TemplateLoc,
3424                    TemplateTy Template,
3425                    SourceLocation TemplateNameLoc,
3426                    SourceLocation LAngleLoc,
3427                    ASTTemplateArgsPtr TemplateArgs,
3428                    SourceLocation RAngleLoc);
3429
3430  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
3431                             SourceLocation KeywordLoc,
3432                             NestedNameSpecifierLoc QualifierLoc,
3433                             const IdentifierInfo &II,
3434                             SourceLocation IILoc);
3435
3436  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
3437                                                    SourceLocation Loc,
3438                                                    DeclarationName Name);
3439  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
3440
3441  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
3442
3443  std::string
3444  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3445                                  const TemplateArgumentList &Args);
3446
3447  std::string
3448  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3449                                  const TemplateArgument *Args,
3450                                  unsigned NumArgs);
3451
3452  //===--------------------------------------------------------------------===//
3453  // C++ Variadic Templates (C++0x [temp.variadic])
3454  //===--------------------------------------------------------------------===//
3455
3456  /// \brief The context in which an unexpanded parameter pack is
3457  /// being diagnosed.
3458  ///
3459  /// Note that the values of this enumeration line up with the first
3460  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
3461  enum UnexpandedParameterPackContext {
3462    /// \brief An arbitrary expression.
3463    UPPC_Expression = 0,
3464
3465    /// \brief The base type of a class type.
3466    UPPC_BaseType,
3467
3468    /// \brief The type of an arbitrary declaration.
3469    UPPC_DeclarationType,
3470
3471    /// \brief The type of a data member.
3472    UPPC_DataMemberType,
3473
3474    /// \brief The size of a bit-field.
3475    UPPC_BitFieldWidth,
3476
3477    /// \brief The expression in a static assertion.
3478    UPPC_StaticAssertExpression,
3479
3480    /// \brief The fixed underlying type of an enumeration.
3481    UPPC_FixedUnderlyingType,
3482
3483    /// \brief The enumerator value.
3484    UPPC_EnumeratorValue,
3485
3486    /// \brief A using declaration.
3487    UPPC_UsingDeclaration,
3488
3489    /// \brief A friend declaration.
3490    UPPC_FriendDeclaration,
3491
3492    /// \brief A declaration qualifier.
3493    UPPC_DeclarationQualifier,
3494
3495    /// \brief An initializer.
3496    UPPC_Initializer,
3497
3498    /// \brief A default argument.
3499    UPPC_DefaultArgument,
3500
3501    /// \brief The type of a non-type template parameter.
3502    UPPC_NonTypeTemplateParameterType,
3503
3504    /// \brief The type of an exception.
3505    UPPC_ExceptionType,
3506
3507    /// \brief Partial specialization.
3508    UPPC_PartialSpecialization
3509  };
3510
3511  /// \brief If the given type contains an unexpanded parameter pack,
3512  /// diagnose the error.
3513  ///
3514  /// \param Loc The source location where a diagnostc should be emitted.
3515  ///
3516  /// \param T The type that is being checked for unexpanded parameter
3517  /// packs.
3518  ///
3519  /// \returns true if an error ocurred, false otherwise.
3520  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
3521                                       UnexpandedParameterPackContext UPPC);
3522
3523  /// \brief If the given expression contains an unexpanded parameter
3524  /// pack, diagnose the error.
3525  ///
3526  /// \param E The expression that is being checked for unexpanded
3527  /// parameter packs.
3528  ///
3529  /// \returns true if an error ocurred, false otherwise.
3530  bool DiagnoseUnexpandedParameterPack(Expr *E,
3531                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
3532
3533  /// \brief If the given nested-name-specifier contains an unexpanded
3534  /// parameter pack, diagnose the error.
3535  ///
3536  /// \param SS The nested-name-specifier that is being checked for
3537  /// unexpanded parameter packs.
3538  ///
3539  /// \returns true if an error ocurred, false otherwise.
3540  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
3541                                       UnexpandedParameterPackContext UPPC);
3542
3543  /// \brief If the given name contains an unexpanded parameter pack,
3544  /// diagnose the error.
3545  ///
3546  /// \param NameInfo The name (with source location information) that
3547  /// is being checked for unexpanded parameter packs.
3548  ///
3549  /// \returns true if an error ocurred, false otherwise.
3550  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
3551                                       UnexpandedParameterPackContext UPPC);
3552
3553  /// \brief If the given template name contains an unexpanded parameter pack,
3554  /// diagnose the error.
3555  ///
3556  /// \param Loc The location of the template name.
3557  ///
3558  /// \param Template The template name that is being checked for unexpanded
3559  /// parameter packs.
3560  ///
3561  /// \returns true if an error ocurred, false otherwise.
3562  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
3563                                       TemplateName Template,
3564                                       UnexpandedParameterPackContext UPPC);
3565
3566  /// \brief If the given template argument contains an unexpanded parameter
3567  /// pack, diagnose the error.
3568  ///
3569  /// \param Arg The template argument that is being checked for unexpanded
3570  /// parameter packs.
3571  ///
3572  /// \returns true if an error ocurred, false otherwise.
3573  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
3574                                       UnexpandedParameterPackContext UPPC);
3575
3576  /// \brief Collect the set of unexpanded parameter packs within the given
3577  /// template argument.
3578  ///
3579  /// \param Arg The template argument that will be traversed to find
3580  /// unexpanded parameter packs.
3581  void collectUnexpandedParameterPacks(TemplateArgument Arg,
3582                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3583
3584  /// \brief Collect the set of unexpanded parameter packs within the given
3585  /// template argument.
3586  ///
3587  /// \param Arg The template argument that will be traversed to find
3588  /// unexpanded parameter packs.
3589  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
3590                    llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3591
3592  /// \brief Collect the set of unexpanded parameter packs within the given
3593  /// type.
3594  ///
3595  /// \param T The type that will be traversed to find
3596  /// unexpanded parameter packs.
3597  void collectUnexpandedParameterPacks(QualType T,
3598                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3599
3600  /// \brief Collect the set of unexpanded parameter packs within the given
3601  /// type.
3602  ///
3603  /// \param TL The type that will be traversed to find
3604  /// unexpanded parameter packs.
3605  void collectUnexpandedParameterPacks(TypeLoc TL,
3606                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3607
3608  /// \brief Invoked when parsing a template argument followed by an
3609  /// ellipsis, which creates a pack expansion.
3610  ///
3611  /// \param Arg The template argument preceding the ellipsis, which
3612  /// may already be invalid.
3613  ///
3614  /// \param EllipsisLoc The location of the ellipsis.
3615  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
3616                                            SourceLocation EllipsisLoc);
3617
3618  /// \brief Invoked when parsing a type followed by an ellipsis, which
3619  /// creates a pack expansion.
3620  ///
3621  /// \param Type The type preceding the ellipsis, which will become
3622  /// the pattern of the pack expansion.
3623  ///
3624  /// \param EllipsisLoc The location of the ellipsis.
3625  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
3626
3627  /// \brief Construct a pack expansion type from the pattern of the pack
3628  /// expansion.
3629  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
3630                                     SourceLocation EllipsisLoc,
3631                                     llvm::Optional<unsigned> NumExpansions);
3632
3633  /// \brief Construct a pack expansion type from the pattern of the pack
3634  /// expansion.
3635  QualType CheckPackExpansion(QualType Pattern,
3636                              SourceRange PatternRange,
3637                              SourceLocation EllipsisLoc,
3638                              llvm::Optional<unsigned> NumExpansions);
3639
3640  /// \brief Invoked when parsing an expression followed by an ellipsis, which
3641  /// creates a pack expansion.
3642  ///
3643  /// \param Pattern The expression preceding the ellipsis, which will become
3644  /// the pattern of the pack expansion.
3645  ///
3646  /// \param EllipsisLoc The location of the ellipsis.
3647  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
3648
3649  /// \brief Invoked when parsing an expression followed by an ellipsis, which
3650  /// creates a pack expansion.
3651  ///
3652  /// \param Pattern The expression preceding the ellipsis, which will become
3653  /// the pattern of the pack expansion.
3654  ///
3655  /// \param EllipsisLoc The location of the ellipsis.
3656  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3657                                llvm::Optional<unsigned> NumExpansions);
3658
3659  /// \brief Determine whether we could expand a pack expansion with the
3660  /// given set of parameter packs into separate arguments by repeatedly
3661  /// transforming the pattern.
3662  ///
3663  /// \param EllipsisLoc The location of the ellipsis that identifies the
3664  /// pack expansion.
3665  ///
3666  /// \param PatternRange The source range that covers the entire pattern of
3667  /// the pack expansion.
3668  ///
3669  /// \param Unexpanded The set of unexpanded parameter packs within the
3670  /// pattern.
3671  ///
3672  /// \param NumUnexpanded The number of unexpanded parameter packs in
3673  /// \p Unexpanded.
3674  ///
3675  /// \param ShouldExpand Will be set to \c true if the transformer should
3676  /// expand the corresponding pack expansions into separate arguments. When
3677  /// set, \c NumExpansions must also be set.
3678  ///
3679  /// \param RetainExpansion Whether the caller should add an unexpanded
3680  /// pack expansion after all of the expanded arguments. This is used
3681  /// when extending explicitly-specified template argument packs per
3682  /// C++0x [temp.arg.explicit]p9.
3683  ///
3684  /// \param NumExpansions The number of separate arguments that will be in
3685  /// the expanded form of the corresponding pack expansion. This is both an
3686  /// input and an output parameter, which can be set by the caller if the
3687  /// number of expansions is known a priori (e.g., due to a prior substitution)
3688  /// and will be set by the callee when the number of expansions is known.
3689  /// The callee must set this value when \c ShouldExpand is \c true; it may
3690  /// set this value in other cases.
3691  ///
3692  /// \returns true if an error occurred (e.g., because the parameter packs
3693  /// are to be instantiated with arguments of different lengths), false
3694  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
3695  /// must be set.
3696  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
3697                                       SourceRange PatternRange,
3698                                     const UnexpandedParameterPack *Unexpanded,
3699                                       unsigned NumUnexpanded,
3700                             const MultiLevelTemplateArgumentList &TemplateArgs,
3701                                       bool &ShouldExpand,
3702                                       bool &RetainExpansion,
3703                                       llvm::Optional<unsigned> &NumExpansions);
3704
3705  /// \brief Determine the number of arguments in the given pack expansion
3706  /// type.
3707  ///
3708  /// This routine already assumes that the pack expansion type can be
3709  /// expanded and that the number of arguments in the expansion is
3710  /// consistent across all of the unexpanded parameter packs in its pattern.
3711  unsigned getNumArgumentsInExpansion(QualType T,
3712                            const MultiLevelTemplateArgumentList &TemplateArgs);
3713
3714  /// \brief Determine whether the given declarator contains any unexpanded
3715  /// parameter packs.
3716  ///
3717  /// This routine is used by the parser to disambiguate function declarators
3718  /// with an ellipsis prior to the ')', e.g.,
3719  ///
3720  /// \code
3721  ///   void f(T...);
3722  /// \endcode
3723  ///
3724  /// To determine whether we have an (unnamed) function parameter pack or
3725  /// a variadic function.
3726  ///
3727  /// \returns true if the declarator contains any unexpanded parameter packs,
3728  /// false otherwise.
3729  bool containsUnexpandedParameterPacks(Declarator &D);
3730
3731  //===--------------------------------------------------------------------===//
3732  // C++ Template Argument Deduction (C++ [temp.deduct])
3733  //===--------------------------------------------------------------------===//
3734
3735  /// \brief Describes the result of template argument deduction.
3736  ///
3737  /// The TemplateDeductionResult enumeration describes the result of
3738  /// template argument deduction, as returned from
3739  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
3740  /// structure provides additional information about the results of
3741  /// template argument deduction, e.g., the deduced template argument
3742  /// list (if successful) or the specific template parameters or
3743  /// deduced arguments that were involved in the failure.
3744  enum TemplateDeductionResult {
3745    /// \brief Template argument deduction was successful.
3746    TDK_Success = 0,
3747    /// \brief Template argument deduction exceeded the maximum template
3748    /// instantiation depth (which has already been diagnosed).
3749    TDK_InstantiationDepth,
3750    /// \brief Template argument deduction did not deduce a value
3751    /// for every template parameter.
3752    TDK_Incomplete,
3753    /// \brief Template argument deduction produced inconsistent
3754    /// deduced values for the given template parameter.
3755    TDK_Inconsistent,
3756    /// \brief Template argument deduction failed due to inconsistent
3757    /// cv-qualifiers on a template parameter type that would
3758    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
3759    /// but were given a non-const "X".
3760    TDK_Underqualified,
3761    /// \brief Substitution of the deduced template argument values
3762    /// resulted in an error.
3763    TDK_SubstitutionFailure,
3764    /// \brief Substitution of the deduced template argument values
3765    /// into a non-deduced context produced a type or value that
3766    /// produces a type that does not match the original template
3767    /// arguments provided.
3768    TDK_NonDeducedMismatch,
3769    /// \brief When performing template argument deduction for a function
3770    /// template, there were too many call arguments.
3771    TDK_TooManyArguments,
3772    /// \brief When performing template argument deduction for a function
3773    /// template, there were too few call arguments.
3774    TDK_TooFewArguments,
3775    /// \brief The explicitly-specified template arguments were not valid
3776    /// template arguments for the given template.
3777    TDK_InvalidExplicitArguments,
3778    /// \brief The arguments included an overloaded function name that could
3779    /// not be resolved to a suitable function.
3780    TDK_FailedOverloadResolution
3781  };
3782
3783  TemplateDeductionResult
3784  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
3785                          const TemplateArgumentList &TemplateArgs,
3786                          sema::TemplateDeductionInfo &Info);
3787
3788  TemplateDeductionResult
3789  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3790                        const TemplateArgumentListInfo &ExplicitTemplateArgs,
3791                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3792                                 llvm::SmallVectorImpl<QualType> &ParamTypes,
3793                                      QualType *FunctionType,
3794                                      sema::TemplateDeductionInfo &Info);
3795
3796  TemplateDeductionResult
3797  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
3798                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3799                                  unsigned NumExplicitlySpecified,
3800                                  FunctionDecl *&Specialization,
3801                                  sema::TemplateDeductionInfo &Info);
3802
3803  TemplateDeductionResult
3804  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3805                          const TemplateArgumentListInfo *ExplicitTemplateArgs,
3806                          Expr **Args, unsigned NumArgs,
3807                          FunctionDecl *&Specialization,
3808                          sema::TemplateDeductionInfo &Info);
3809
3810  TemplateDeductionResult
3811  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3812                          const TemplateArgumentListInfo *ExplicitTemplateArgs,
3813                          QualType ArgFunctionType,
3814                          FunctionDecl *&Specialization,
3815                          sema::TemplateDeductionInfo &Info);
3816
3817  TemplateDeductionResult
3818  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3819                          QualType ToType,
3820                          CXXConversionDecl *&Specialization,
3821                          sema::TemplateDeductionInfo &Info);
3822
3823  TemplateDeductionResult
3824  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3825                          const TemplateArgumentListInfo *ExplicitTemplateArgs,
3826                          FunctionDecl *&Specialization,
3827                          sema::TemplateDeductionInfo &Info);
3828
3829  bool DeduceAutoType(QualType AutoType, Expr *Initializer, QualType &Result);
3830
3831  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3832                                                   FunctionTemplateDecl *FT2,
3833                                                   SourceLocation Loc,
3834                                           TemplatePartialOrderingContext TPOC,
3835                                                   unsigned NumCallArguments);
3836  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
3837                                           UnresolvedSetIterator SEnd,
3838                                           TemplatePartialOrderingContext TPOC,
3839                                           unsigned NumCallArguments,
3840                                           SourceLocation Loc,
3841                                           const PartialDiagnostic &NoneDiag,
3842                                           const PartialDiagnostic &AmbigDiag,
3843                                        const PartialDiagnostic &CandidateDiag,
3844                                        bool Complain = true);
3845
3846  ClassTemplatePartialSpecializationDecl *
3847  getMoreSpecializedPartialSpecialization(
3848                                  ClassTemplatePartialSpecializationDecl *PS1,
3849                                  ClassTemplatePartialSpecializationDecl *PS2,
3850                                  SourceLocation Loc);
3851
3852  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
3853                                  bool OnlyDeduced,
3854                                  unsigned Depth,
3855                                  llvm::SmallVectorImpl<bool> &Used);
3856  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3857                                     llvm::SmallVectorImpl<bool> &Deduced);
3858
3859  //===--------------------------------------------------------------------===//
3860  // C++ Template Instantiation
3861  //
3862
3863  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
3864                                     const TemplateArgumentList *Innermost = 0,
3865                                                bool RelativeToPrimary = false,
3866                                               const FunctionDecl *Pattern = 0);
3867
3868  /// \brief A template instantiation that is currently in progress.
3869  struct ActiveTemplateInstantiation {
3870    /// \brief The kind of template instantiation we are performing
3871    enum InstantiationKind {
3872      /// We are instantiating a template declaration. The entity is
3873      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
3874      TemplateInstantiation,
3875
3876      /// We are instantiating a default argument for a template
3877      /// parameter. The Entity is the template, and
3878      /// TemplateArgs/NumTemplateArguments provides the template
3879      /// arguments as specified.
3880      /// FIXME: Use a TemplateArgumentList
3881      DefaultTemplateArgumentInstantiation,
3882
3883      /// We are instantiating a default argument for a function.
3884      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
3885      /// provides the template arguments as specified.
3886      DefaultFunctionArgumentInstantiation,
3887
3888      /// We are substituting explicit template arguments provided for
3889      /// a function template. The entity is a FunctionTemplateDecl.
3890      ExplicitTemplateArgumentSubstitution,
3891
3892      /// We are substituting template argument determined as part of
3893      /// template argument deduction for either a class template
3894      /// partial specialization or a function template. The
3895      /// Entity is either a ClassTemplatePartialSpecializationDecl or
3896      /// a FunctionTemplateDecl.
3897      DeducedTemplateArgumentSubstitution,
3898
3899      /// We are substituting prior template arguments into a new
3900      /// template parameter. The template parameter itself is either a
3901      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
3902      PriorTemplateArgumentSubstitution,
3903
3904      /// We are checking the validity of a default template argument that
3905      /// has been used when naming a template-id.
3906      DefaultTemplateArgumentChecking
3907    } Kind;
3908
3909    /// \brief The point of instantiation within the source code.
3910    SourceLocation PointOfInstantiation;
3911
3912    /// \brief The template (or partial specialization) in which we are
3913    /// performing the instantiation, for substitutions of prior template
3914    /// arguments.
3915    NamedDecl *Template;
3916
3917    /// \brief The entity that is being instantiated.
3918    uintptr_t Entity;
3919
3920    /// \brief The list of template arguments we are substituting, if they
3921    /// are not part of the entity.
3922    const TemplateArgument *TemplateArgs;
3923
3924    /// \brief The number of template arguments in TemplateArgs.
3925    unsigned NumTemplateArgs;
3926
3927    /// \brief The template deduction info object associated with the
3928    /// substitution or checking of explicit or deduced template arguments.
3929    sema::TemplateDeductionInfo *DeductionInfo;
3930
3931    /// \brief The source range that covers the construct that cause
3932    /// the instantiation, e.g., the template-id that causes a class
3933    /// template instantiation.
3934    SourceRange InstantiationRange;
3935
3936    ActiveTemplateInstantiation()
3937      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
3938        NumTemplateArgs(0), DeductionInfo(0) {}
3939
3940    /// \brief Determines whether this template is an actual instantiation
3941    /// that should be counted toward the maximum instantiation depth.
3942    bool isInstantiationRecord() const;
3943
3944    friend bool operator==(const ActiveTemplateInstantiation &X,
3945                           const ActiveTemplateInstantiation &Y) {
3946      if (X.Kind != Y.Kind)
3947        return false;
3948
3949      if (X.Entity != Y.Entity)
3950        return false;
3951
3952      switch (X.Kind) {
3953      case TemplateInstantiation:
3954        return true;
3955
3956      case PriorTemplateArgumentSubstitution:
3957      case DefaultTemplateArgumentChecking:
3958        if (X.Template != Y.Template)
3959          return false;
3960
3961        // Fall through
3962
3963      case DefaultTemplateArgumentInstantiation:
3964      case ExplicitTemplateArgumentSubstitution:
3965      case DeducedTemplateArgumentSubstitution:
3966      case DefaultFunctionArgumentInstantiation:
3967        return X.TemplateArgs == Y.TemplateArgs;
3968
3969      }
3970
3971      return true;
3972    }
3973
3974    friend bool operator!=(const ActiveTemplateInstantiation &X,
3975                           const ActiveTemplateInstantiation &Y) {
3976      return !(X == Y);
3977    }
3978  };
3979
3980  /// \brief List of active template instantiations.
3981  ///
3982  /// This vector is treated as a stack. As one template instantiation
3983  /// requires another template instantiation, additional
3984  /// instantiations are pushed onto the stack up to a
3985  /// user-configurable limit LangOptions::InstantiationDepth.
3986  llvm::SmallVector<ActiveTemplateInstantiation, 16>
3987    ActiveTemplateInstantiations;
3988
3989  /// \brief Whether we are in a SFINAE context that is not associated with
3990  /// template instantiation.
3991  ///
3992  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
3993  /// of a template instantiation or template argument deduction.
3994  bool InNonInstantiationSFINAEContext;
3995
3996  /// \brief The number of ActiveTemplateInstantiation entries in
3997  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
3998  /// therefore, should not be counted as part of the instantiation depth.
3999  unsigned NonInstantiationEntries;
4000
4001  /// \brief The last template from which a template instantiation
4002  /// error or warning was produced.
4003  ///
4004  /// This value is used to suppress printing of redundant template
4005  /// instantiation backtraces when there are multiple errors in the
4006  /// same instantiation. FIXME: Does this belong in Sema? It's tough
4007  /// to implement it anywhere else.
4008  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
4009
4010  /// \brief The current index into pack expansion arguments that will be
4011  /// used for substitution of parameter packs.
4012  ///
4013  /// The pack expansion index will be -1 to indicate that parameter packs
4014  /// should be instantiated as themselves. Otherwise, the index specifies
4015  /// which argument within the parameter pack will be used for substitution.
4016  int ArgumentPackSubstitutionIndex;
4017
4018  /// \brief RAII object used to change the argument pack substitution index
4019  /// within a \c Sema object.
4020  ///
4021  /// See \c ArgumentPackSubstitutionIndex for more information.
4022  class ArgumentPackSubstitutionIndexRAII {
4023    Sema &Self;
4024    int OldSubstitutionIndex;
4025
4026  public:
4027    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
4028      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
4029      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
4030    }
4031
4032    ~ArgumentPackSubstitutionIndexRAII() {
4033      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
4034    }
4035  };
4036
4037  friend class ArgumentPackSubstitutionRAII;
4038
4039  /// \brief The stack of calls expression undergoing template instantiation.
4040  ///
4041  /// The top of this stack is used by a fixit instantiating unresolved
4042  /// function calls to fix the AST to match the textual change it prints.
4043  llvm::SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
4044
4045  /// \brief For each declaration that involved template argument deduction, the
4046  /// set of diagnostics that were suppressed during that template argument
4047  /// deduction.
4048  ///
4049  /// FIXME: Serialize this structure to the AST file.
4050  llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >
4051    SuppressedDiagnostics;
4052
4053  /// \brief A stack object to be created when performing template
4054  /// instantiation.
4055  ///
4056  /// Construction of an object of type \c InstantiatingTemplate
4057  /// pushes the current instantiation onto the stack of active
4058  /// instantiations. If the size of this stack exceeds the maximum
4059  /// number of recursive template instantiations, construction
4060  /// produces an error and evaluates true.
4061  ///
4062  /// Destruction of this object will pop the named instantiation off
4063  /// the stack.
4064  struct InstantiatingTemplate {
4065    /// \brief Note that we are instantiating a class template,
4066    /// function template, or a member thereof.
4067    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4068                          Decl *Entity,
4069                          SourceRange InstantiationRange = SourceRange());
4070
4071    /// \brief Note that we are instantiating a default argument in a
4072    /// template-id.
4073    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4074                          TemplateDecl *Template,
4075                          const TemplateArgument *TemplateArgs,
4076                          unsigned NumTemplateArgs,
4077                          SourceRange InstantiationRange = SourceRange());
4078
4079    /// \brief Note that we are instantiating a default argument in a
4080    /// template-id.
4081    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4082                          FunctionTemplateDecl *FunctionTemplate,
4083                          const TemplateArgument *TemplateArgs,
4084                          unsigned NumTemplateArgs,
4085                          ActiveTemplateInstantiation::InstantiationKind Kind,
4086                          sema::TemplateDeductionInfo &DeductionInfo,
4087                          SourceRange InstantiationRange = SourceRange());
4088
4089    /// \brief Note that we are instantiating as part of template
4090    /// argument deduction for a class template partial
4091    /// specialization.
4092    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4093                          ClassTemplatePartialSpecializationDecl *PartialSpec,
4094                          const TemplateArgument *TemplateArgs,
4095                          unsigned NumTemplateArgs,
4096                          sema::TemplateDeductionInfo &DeductionInfo,
4097                          SourceRange InstantiationRange = SourceRange());
4098
4099    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4100                          ParmVarDecl *Param,
4101                          const TemplateArgument *TemplateArgs,
4102                          unsigned NumTemplateArgs,
4103                          SourceRange InstantiationRange = SourceRange());
4104
4105    /// \brief Note that we are substituting prior template arguments into a
4106    /// non-type or template template parameter.
4107    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4108                          NamedDecl *Template,
4109                          NonTypeTemplateParmDecl *Param,
4110                          const TemplateArgument *TemplateArgs,
4111                          unsigned NumTemplateArgs,
4112                          SourceRange InstantiationRange);
4113
4114    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4115                          NamedDecl *Template,
4116                          TemplateTemplateParmDecl *Param,
4117                          const TemplateArgument *TemplateArgs,
4118                          unsigned NumTemplateArgs,
4119                          SourceRange InstantiationRange);
4120
4121    /// \brief Note that we are checking the default template argument
4122    /// against the template parameter for a given template-id.
4123    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4124                          TemplateDecl *Template,
4125                          NamedDecl *Param,
4126                          const TemplateArgument *TemplateArgs,
4127                          unsigned NumTemplateArgs,
4128                          SourceRange InstantiationRange);
4129
4130
4131    /// \brief Note that we have finished instantiating this template.
4132    void Clear();
4133
4134    ~InstantiatingTemplate() { Clear(); }
4135
4136    /// \brief Determines whether we have exceeded the maximum
4137    /// recursive template instantiations.
4138    operator bool() const { return Invalid; }
4139
4140  private:
4141    Sema &SemaRef;
4142    bool Invalid;
4143    bool SavedInNonInstantiationSFINAEContext;
4144    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
4145                                 SourceRange InstantiationRange);
4146
4147    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
4148
4149    InstantiatingTemplate&
4150    operator=(const InstantiatingTemplate&); // not implemented
4151  };
4152
4153  void PrintInstantiationStack();
4154
4155  /// \brief Determines whether we are currently in a context where
4156  /// template argument substitution failures are not considered
4157  /// errors.
4158  ///
4159  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
4160  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
4161  /// template-deduction context object, which can be used to capture
4162  /// diagnostics that will be suppressed.
4163  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
4164
4165  /// \brief RAII class used to determine whether SFINAE has
4166  /// trapped any errors that occur during template argument
4167  /// deduction.`
4168  class SFINAETrap {
4169    Sema &SemaRef;
4170    unsigned PrevSFINAEErrors;
4171    bool PrevInNonInstantiationSFINAEContext;
4172    bool PrevAccessCheckingSFINAE;
4173
4174  public:
4175    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
4176      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
4177        PrevInNonInstantiationSFINAEContext(
4178                                      SemaRef.InNonInstantiationSFINAEContext),
4179        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
4180    {
4181      if (!SemaRef.isSFINAEContext())
4182        SemaRef.InNonInstantiationSFINAEContext = true;
4183      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
4184    }
4185
4186    ~SFINAETrap() {
4187      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
4188      SemaRef.InNonInstantiationSFINAEContext
4189        = PrevInNonInstantiationSFINAEContext;
4190      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
4191    }
4192
4193    /// \brief Determine whether any SFINAE errors have been trapped.
4194    bool hasErrorOccurred() const {
4195      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
4196    }
4197  };
4198
4199  /// \brief The current instantiation scope used to store local
4200  /// variables.
4201  LocalInstantiationScope *CurrentInstantiationScope;
4202
4203  /// \brief The number of typos corrected by CorrectTypo.
4204  unsigned TyposCorrected;
4205
4206  typedef llvm::DenseMap<IdentifierInfo *, std::pair<llvm::StringRef, bool> >
4207    UnqualifiedTyposCorrectedMap;
4208
4209  /// \brief A cache containing the results of typo correction for unqualified
4210  /// name lookup.
4211  ///
4212  /// The string is the string that we corrected to (which may be empty, if
4213  /// there was no correction), while the boolean will be true when the
4214  /// string represents a keyword.
4215  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
4216
4217  /// \brief Worker object for performing CFG-based warnings.
4218  sema::AnalysisBasedWarnings AnalysisWarnings;
4219
4220  /// \brief An entity for which implicit template instantiation is required.
4221  ///
4222  /// The source location associated with the declaration is the first place in
4223  /// the source code where the declaration was "used". It is not necessarily
4224  /// the point of instantiation (which will be either before or after the
4225  /// namespace-scope declaration that triggered this implicit instantiation),
4226  /// However, it is the location that diagnostics should generally refer to,
4227  /// because users will need to know what code triggered the instantiation.
4228  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
4229
4230  /// \brief The queue of implicit template instantiations that are required
4231  /// but have not yet been performed.
4232  std::deque<PendingImplicitInstantiation> PendingInstantiations;
4233
4234  /// \brief The queue of implicit template instantiations that are required
4235  /// and must be performed within the current local scope.
4236  ///
4237  /// This queue is only used for member functions of local classes in
4238  /// templates, which must be instantiated in the same scope as their
4239  /// enclosing function, so that they can reference function-local
4240  /// types, static variables, enumerators, etc.
4241  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
4242
4243  void PerformPendingInstantiations(bool LocalOnly = false);
4244
4245  TypeSourceInfo *SubstType(TypeSourceInfo *T,
4246                            const MultiLevelTemplateArgumentList &TemplateArgs,
4247                            SourceLocation Loc, DeclarationName Entity);
4248
4249  QualType SubstType(QualType T,
4250                     const MultiLevelTemplateArgumentList &TemplateArgs,
4251                     SourceLocation Loc, DeclarationName Entity);
4252
4253  TypeSourceInfo *SubstType(TypeLoc TL,
4254                            const MultiLevelTemplateArgumentList &TemplateArgs,
4255                            SourceLocation Loc, DeclarationName Entity);
4256
4257  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
4258                            const MultiLevelTemplateArgumentList &TemplateArgs,
4259                                        SourceLocation Loc,
4260                                        DeclarationName Entity);
4261  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
4262                            const MultiLevelTemplateArgumentList &TemplateArgs,
4263                                llvm::Optional<unsigned> NumExpansions);
4264  bool SubstParmTypes(SourceLocation Loc,
4265                      ParmVarDecl **Params, unsigned NumParams,
4266                      const MultiLevelTemplateArgumentList &TemplateArgs,
4267                      llvm::SmallVectorImpl<QualType> &ParamTypes,
4268                      llvm::SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
4269  ExprResult SubstExpr(Expr *E,
4270                       const MultiLevelTemplateArgumentList &TemplateArgs);
4271
4272  /// \brief Substitute the given template arguments into a list of
4273  /// expressions, expanding pack expansions if required.
4274  ///
4275  /// \param Exprs The list of expressions to substitute into.
4276  ///
4277  /// \param NumExprs The number of expressions in \p Exprs.
4278  ///
4279  /// \param IsCall Whether this is some form of call, in which case
4280  /// default arguments will be dropped.
4281  ///
4282  /// \param TemplateArgs The set of template arguments to substitute.
4283  ///
4284  /// \param Outputs Will receive all of the substituted arguments.
4285  ///
4286  /// \returns true if an error occurred, false otherwise.
4287  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
4288                  const MultiLevelTemplateArgumentList &TemplateArgs,
4289                  llvm::SmallVectorImpl<Expr *> &Outputs);
4290
4291  StmtResult SubstStmt(Stmt *S,
4292                       const MultiLevelTemplateArgumentList &TemplateArgs);
4293
4294  Decl *SubstDecl(Decl *D, DeclContext *Owner,
4295                  const MultiLevelTemplateArgumentList &TemplateArgs);
4296
4297  bool
4298  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
4299                      CXXRecordDecl *Pattern,
4300                      const MultiLevelTemplateArgumentList &TemplateArgs);
4301
4302  bool
4303  InstantiateClass(SourceLocation PointOfInstantiation,
4304                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
4305                   const MultiLevelTemplateArgumentList &TemplateArgs,
4306                   TemplateSpecializationKind TSK,
4307                   bool Complain = true);
4308
4309  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
4310                        Decl *Pattern, Decl *Inst);
4311
4312  bool
4313  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
4314                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4315                           TemplateSpecializationKind TSK,
4316                           bool Complain = true);
4317
4318  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
4319                               CXXRecordDecl *Instantiation,
4320                            const MultiLevelTemplateArgumentList &TemplateArgs,
4321                               TemplateSpecializationKind TSK);
4322
4323  void InstantiateClassTemplateSpecializationMembers(
4324                                          SourceLocation PointOfInstantiation,
4325                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4326                                                TemplateSpecializationKind TSK);
4327
4328  NestedNameSpecifier *
4329  SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
4330                           SourceRange Range,
4331                           const MultiLevelTemplateArgumentList &TemplateArgs);
4332
4333  NestedNameSpecifierLoc
4334  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4335                           const MultiLevelTemplateArgumentList &TemplateArgs);
4336
4337  DeclarationNameInfo
4338  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4339                           const MultiLevelTemplateArgumentList &TemplateArgs);
4340  TemplateName
4341  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
4342                    SourceLocation Loc,
4343                    const MultiLevelTemplateArgumentList &TemplateArgs);
4344  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
4345             TemplateArgumentListInfo &Result,
4346             const MultiLevelTemplateArgumentList &TemplateArgs);
4347
4348  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4349                                     FunctionDecl *Function,
4350                                     bool Recursive = false,
4351                                     bool DefinitionRequired = false);
4352  void InstantiateStaticDataMemberDefinition(
4353                                     SourceLocation PointOfInstantiation,
4354                                     VarDecl *Var,
4355                                     bool Recursive = false,
4356                                     bool DefinitionRequired = false);
4357
4358  void InstantiateMemInitializers(CXXConstructorDecl *New,
4359                                  const CXXConstructorDecl *Tmpl,
4360                            const MultiLevelTemplateArgumentList &TemplateArgs);
4361
4362  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4363                          const MultiLevelTemplateArgumentList &TemplateArgs);
4364  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
4365                          const MultiLevelTemplateArgumentList &TemplateArgs);
4366
4367  // Objective-C declarations.
4368  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
4369                                 IdentifierInfo *ClassName,
4370                                 SourceLocation ClassLoc,
4371                                 IdentifierInfo *SuperName,
4372                                 SourceLocation SuperLoc,
4373                                 Decl * const *ProtoRefs,
4374                                 unsigned NumProtoRefs,
4375                                 const SourceLocation *ProtoLocs,
4376                                 SourceLocation EndProtoLoc,
4377                                 AttributeList *AttrList);
4378
4379  Decl *ActOnCompatiblityAlias(
4380                    SourceLocation AtCompatibilityAliasLoc,
4381                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
4382                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
4383
4384  void CheckForwardProtocolDeclarationForCircularDependency(
4385    IdentifierInfo *PName,
4386    SourceLocation &PLoc, SourceLocation PrevLoc,
4387    const ObjCList<ObjCProtocolDecl> &PList);
4388
4389  Decl *ActOnStartProtocolInterface(
4390                    SourceLocation AtProtoInterfaceLoc,
4391                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
4392                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
4393                    const SourceLocation *ProtoLocs,
4394                    SourceLocation EndProtoLoc,
4395                    AttributeList *AttrList);
4396
4397  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
4398                                    IdentifierInfo *ClassName,
4399                                    SourceLocation ClassLoc,
4400                                    IdentifierInfo *CategoryName,
4401                                    SourceLocation CategoryLoc,
4402                                    Decl * const *ProtoRefs,
4403                                    unsigned NumProtoRefs,
4404                                    const SourceLocation *ProtoLocs,
4405                                    SourceLocation EndProtoLoc);
4406
4407  Decl *ActOnStartClassImplementation(
4408                    SourceLocation AtClassImplLoc,
4409                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
4410                    IdentifierInfo *SuperClassname,
4411                    SourceLocation SuperClassLoc);
4412
4413  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
4414                                         IdentifierInfo *ClassName,
4415                                         SourceLocation ClassLoc,
4416                                         IdentifierInfo *CatName,
4417                                         SourceLocation CatLoc);
4418
4419  Decl *ActOnForwardClassDeclaration(SourceLocation Loc,
4420                                     IdentifierInfo **IdentList,
4421                                     SourceLocation *IdentLocs,
4422                                     unsigned NumElts);
4423
4424  Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
4425                                        const IdentifierLocPair *IdentList,
4426                                        unsigned NumElts,
4427                                        AttributeList *attrList);
4428
4429  void FindProtocolDeclaration(bool WarnOnDeclarations,
4430                               const IdentifierLocPair *ProtocolId,
4431                               unsigned NumProtocols,
4432                               llvm::SmallVectorImpl<Decl *> &Protocols);
4433
4434  /// Ensure attributes are consistent with type.
4435  /// \param [in, out] Attributes The attributes to check; they will
4436  /// be modified to be consistent with \arg PropertyTy.
4437  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
4438                                   SourceLocation Loc,
4439                                   unsigned &Attributes);
4440
4441  /// Process the specified property declaration and create decls for the
4442  /// setters and getters as needed.
4443  /// \param property The property declaration being processed
4444  /// \param DC The semantic container for the property
4445  /// \param redeclaredProperty Declaration for property if redeclared
4446  ///        in class extension.
4447  /// \param lexicalDC Container for redeclaredProperty.
4448  void ProcessPropertyDecl(ObjCPropertyDecl *property,
4449                           ObjCContainerDecl *DC,
4450                           ObjCPropertyDecl *redeclaredProperty = 0,
4451                           ObjCContainerDecl *lexicalDC = 0);
4452
4453  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
4454                                ObjCPropertyDecl *SuperProperty,
4455                                const IdentifierInfo *Name);
4456  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
4457
4458  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
4459                                         ObjCMethodDecl *MethodDecl,
4460                                         bool IsInstance);
4461
4462  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
4463
4464  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
4465                                        ObjCInterfaceDecl *ID);
4466
4467  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
4468                                         ObjCProtocolDecl *PDecl);
4469
4470  void ActOnAtEnd(Scope *S, SourceRange AtEnd, Decl *classDecl,
4471                  Decl **allMethods = 0, unsigned allNum = 0,
4472                  Decl **allProperties = 0, unsigned pNum = 0,
4473                  DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
4474
4475  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
4476                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
4477                      Selector GetterSel, Selector SetterSel,
4478                      Decl *ClassCategory,
4479                      bool *OverridingProperty,
4480                      tok::ObjCKeywordKind MethodImplKind,
4481                      DeclContext *lexicalDC = 0);
4482
4483  Decl *ActOnPropertyImplDecl(Scope *S,
4484                              SourceLocation AtLoc,
4485                              SourceLocation PropertyLoc,
4486                              bool ImplKind,Decl *ClassImplDecl,
4487                              IdentifierInfo *PropertyId,
4488                              IdentifierInfo *PropertyIvar,
4489                              SourceLocation PropertyIvarLoc);
4490
4491  struct ObjCArgInfo {
4492    IdentifierInfo *Name;
4493    SourceLocation NameLoc;
4494    // The Type is null if no type was specified, and the DeclSpec is invalid
4495    // in this case.
4496    ParsedType Type;
4497    ObjCDeclSpec DeclSpec;
4498
4499    /// ArgAttrs - Attribute list for this argument.
4500    AttributeList *ArgAttrs;
4501  };
4502
4503  Decl *ActOnMethodDeclaration(
4504    Scope *S,
4505    SourceLocation BeginLoc, // location of the + or -.
4506    SourceLocation EndLoc,   // location of the ; or {.
4507    tok::TokenKind MethodType,
4508    Decl *ClassDecl, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4509    Selector Sel,
4510    // optional arguments. The number of types/arguments is obtained
4511    // from the Sel.getNumArgs().
4512    ObjCArgInfo *ArgInfo,
4513    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
4514    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
4515    bool isVariadic = false);
4516
4517  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
4518  // Will search "local" class/category implementations for a method decl.
4519  // Will also search in class's root looking for instance method.
4520  // Returns 0 if no method is found.
4521  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
4522                                           ObjCInterfaceDecl *CDecl);
4523  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
4524                                              ObjCInterfaceDecl *ClassDecl);
4525
4526  ExprResult
4527  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
4528                            Expr *BaseExpr,
4529                            DeclarationName MemberName,
4530                            SourceLocation MemberLoc,
4531                            SourceLocation SuperLoc, QualType SuperType,
4532                            bool Super);
4533
4534  ExprResult
4535  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
4536                            IdentifierInfo &propertyName,
4537                            SourceLocation receiverNameLoc,
4538                            SourceLocation propertyNameLoc);
4539
4540  ObjCMethodDecl *tryCaptureObjCSelf();
4541
4542  /// \brief Describes the kind of message expression indicated by a message
4543  /// send that starts with an identifier.
4544  enum ObjCMessageKind {
4545    /// \brief The message is sent to 'super'.
4546    ObjCSuperMessage,
4547    /// \brief The message is an instance message.
4548    ObjCInstanceMessage,
4549    /// \brief The message is a class message, and the identifier is a type
4550    /// name.
4551    ObjCClassMessage
4552  };
4553
4554  ObjCMessageKind getObjCMessageKind(Scope *S,
4555                                     IdentifierInfo *Name,
4556                                     SourceLocation NameLoc,
4557                                     bool IsSuper,
4558                                     bool HasTrailingDot,
4559                                     ParsedType &ReceiverType);
4560
4561  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
4562                               Selector Sel,
4563                               SourceLocation LBracLoc,
4564                               SourceLocation SelectorLoc,
4565                               SourceLocation RBracLoc,
4566                               MultiExprArg Args);
4567
4568  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
4569                               QualType ReceiverType,
4570                               SourceLocation SuperLoc,
4571                               Selector Sel,
4572                               ObjCMethodDecl *Method,
4573                               SourceLocation LBracLoc,
4574                               SourceLocation SelectorLoc,
4575                               SourceLocation RBracLoc,
4576                               MultiExprArg Args);
4577
4578  ExprResult ActOnClassMessage(Scope *S,
4579                               ParsedType Receiver,
4580                               Selector Sel,
4581                               SourceLocation LBracLoc,
4582                               SourceLocation SelectorLoc,
4583                               SourceLocation RBracLoc,
4584                               MultiExprArg Args);
4585
4586  ExprResult BuildInstanceMessage(Expr *Receiver,
4587                                  QualType ReceiverType,
4588                                  SourceLocation SuperLoc,
4589                                  Selector Sel,
4590                                  ObjCMethodDecl *Method,
4591                                  SourceLocation LBracLoc,
4592                                  SourceLocation SelectorLoc,
4593                                  SourceLocation RBracLoc,
4594                                  MultiExprArg Args);
4595
4596  ExprResult ActOnInstanceMessage(Scope *S,
4597                                  Expr *Receiver,
4598                                  Selector Sel,
4599                                  SourceLocation LBracLoc,
4600                                  SourceLocation SelectorLoc,
4601                                  SourceLocation RBracLoc,
4602                                  MultiExprArg Args);
4603
4604
4605  enum PragmaOptionsAlignKind {
4606    POAK_Native,  // #pragma options align=native
4607    POAK_Natural, // #pragma options align=natural
4608    POAK_Packed,  // #pragma options align=packed
4609    POAK_Power,   // #pragma options align=power
4610    POAK_Mac68k,  // #pragma options align=mac68k
4611    POAK_Reset    // #pragma options align=reset
4612  };
4613
4614  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
4615  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
4616                               SourceLocation PragmaLoc,
4617                               SourceLocation KindLoc);
4618
4619  enum PragmaPackKind {
4620    PPK_Default, // #pragma pack([n])
4621    PPK_Show,    // #pragma pack(show), only supported by MSVC.
4622    PPK_Push,    // #pragma pack(push, [identifier], [n])
4623    PPK_Pop      // #pragma pack(pop, [identifier], [n])
4624  };
4625
4626  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
4627  void ActOnPragmaPack(PragmaPackKind Kind,
4628                       IdentifierInfo *Name,
4629                       Expr *Alignment,
4630                       SourceLocation PragmaLoc,
4631                       SourceLocation LParenLoc,
4632                       SourceLocation RParenLoc);
4633
4634  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
4635  void ActOnPragmaUnused(const Token &Identifier,
4636                         Scope *curScope,
4637                         SourceLocation PragmaLoc);
4638
4639  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
4640  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
4641                             SourceLocation PragmaLoc);
4642
4643  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II);
4644  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
4645
4646  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
4647  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
4648                         SourceLocation PragmaLoc,
4649                         SourceLocation WeakNameLoc);
4650
4651  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
4652  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
4653                            IdentifierInfo* AliasName,
4654                            SourceLocation PragmaLoc,
4655                            SourceLocation WeakNameLoc,
4656                            SourceLocation AliasNameLoc);
4657
4658  /// ActOnPragmaFPContract - Called on well formed
4659  /// #pragma {STDC,OPENCL} FP_CONTRACT
4660  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
4661
4662  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
4663  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
4664  void AddAlignmentAttributesForRecord(RecordDecl *RD);
4665
4666  /// FreePackedContext - Deallocate and null out PackContext.
4667  void FreePackedContext();
4668
4669  /// PushNamespaceVisibilityAttr - Note that we've entered a
4670  /// namespace with a visibility attribute.
4671  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
4672
4673  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
4674  /// add an appropriate visibility attribute.
4675  void AddPushedVisibilityAttribute(Decl *RD);
4676
4677  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
4678  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
4679  void PopPragmaVisibility();
4680
4681  /// FreeVisContext - Deallocate and null out VisContext.
4682  void FreeVisContext();
4683
4684  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
4685  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E);
4686  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T);
4687
4688  /// CastCategory - Get the correct forwarded implicit cast result category
4689  /// from the inner expression.
4690  ExprValueKind CastCategory(Expr *E);
4691
4692  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
4693  /// cast.  If there is already an implicit cast, merge into the existing one.
4694  /// If isLvalue, the result of the cast is an lvalue.
4695  void ImpCastExprToType(Expr *&Expr, QualType Type, CastKind CK,
4696                         ExprValueKind VK = VK_RValue,
4697                         const CXXCastPath *BasePath = 0);
4698
4699  /// IgnoredValueConversions - Given that an expression's result is
4700  /// syntactically ignored, perform any conversions that are
4701  /// required.
4702  void IgnoredValueConversions(Expr *&expr);
4703
4704  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
4705  // functions and arrays to their respective pointers (C99 6.3.2.1).
4706  Expr *UsualUnaryConversions(Expr *&expr);
4707
4708  // DefaultFunctionArrayConversion - converts functions and arrays
4709  // to their respective pointers (C99 6.3.2.1).
4710  void DefaultFunctionArrayConversion(Expr *&expr);
4711
4712  // DefaultFunctionArrayLvalueConversion - converts functions and
4713  // arrays to their respective pointers and performs the
4714  // lvalue-to-rvalue conversion.
4715  void DefaultFunctionArrayLvalueConversion(Expr *&expr);
4716
4717  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
4718  // the operand.  This is DefaultFunctionArrayLvalueConversion,
4719  // except that it assumes the operand isn't of function or array
4720  // type.
4721  void DefaultLvalueConversion(Expr *&expr);
4722
4723  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
4724  // do not have a prototype. Integer promotions are performed on each
4725  // argument, and arguments that have type float are promoted to double.
4726  void DefaultArgumentPromotion(Expr *&Expr);
4727
4728  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
4729  enum VariadicCallType {
4730    VariadicFunction,
4731    VariadicBlock,
4732    VariadicMethod,
4733    VariadicConstructor,
4734    VariadicDoesNotApply
4735  };
4736
4737  /// GatherArgumentsForCall - Collector argument expressions for various
4738  /// form of call prototypes.
4739  bool GatherArgumentsForCall(SourceLocation CallLoc,
4740                              FunctionDecl *FDecl,
4741                              const FunctionProtoType *Proto,
4742                              unsigned FirstProtoArg,
4743                              Expr **Args, unsigned NumArgs,
4744                              llvm::SmallVector<Expr *, 8> &AllArgs,
4745                              VariadicCallType CallType = VariadicDoesNotApply);
4746
4747  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
4748  // will warn if the resulting type is not a POD type.
4749  bool DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
4750                                        FunctionDecl *FDecl);
4751
4752  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
4753  // operands and then handles various conversions that are common to binary
4754  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
4755  // routine returns the first non-arithmetic type found. The client is
4756  // responsible for emitting appropriate error diagnostics.
4757  QualType UsualArithmeticConversions(Expr *&lExpr, Expr *&rExpr,
4758                                      bool isCompAssign = false);
4759
4760  /// AssignConvertType - All of the 'assignment' semantic checks return this
4761  /// enum to indicate whether the assignment was allowed.  These checks are
4762  /// done for simple assignments, as well as initialization, return from
4763  /// function, argument passing, etc.  The query is phrased in terms of a
4764  /// source and destination type.
4765  enum AssignConvertType {
4766    /// Compatible - the types are compatible according to the standard.
4767    Compatible,
4768
4769    /// PointerToInt - The assignment converts a pointer to an int, which we
4770    /// accept as an extension.
4771    PointerToInt,
4772
4773    /// IntToPointer - The assignment converts an int to a pointer, which we
4774    /// accept as an extension.
4775    IntToPointer,
4776
4777    /// FunctionVoidPointer - The assignment is between a function pointer and
4778    /// void*, which the standard doesn't allow, but we accept as an extension.
4779    FunctionVoidPointer,
4780
4781    /// IncompatiblePointer - The assignment is between two pointers types that
4782    /// are not compatible, but we accept them as an extension.
4783    IncompatiblePointer,
4784
4785    /// IncompatiblePointer - The assignment is between two pointers types which
4786    /// point to integers which have a different sign, but are otherwise identical.
4787    /// This is a subset of the above, but broken out because it's by far the most
4788    /// common case of incompatible pointers.
4789    IncompatiblePointerSign,
4790
4791    /// CompatiblePointerDiscardsQualifiers - The assignment discards
4792    /// c/v/r qualifiers, which we accept as an extension.
4793    CompatiblePointerDiscardsQualifiers,
4794
4795    /// IncompatiblePointerDiscardsQualifiers - The assignment
4796    /// discards qualifiers that we don't permit to be discarded,
4797    /// like address spaces.
4798    IncompatiblePointerDiscardsQualifiers,
4799
4800    /// IncompatibleNestedPointerQualifiers - The assignment is between two
4801    /// nested pointer types, and the qualifiers other than the first two
4802    /// levels differ e.g. char ** -> const char **, but we accept them as an
4803    /// extension.
4804    IncompatibleNestedPointerQualifiers,
4805
4806    /// IncompatibleVectors - The assignment is between two vector types that
4807    /// have the same size, which we accept as an extension.
4808    IncompatibleVectors,
4809
4810    /// IntToBlockPointer - The assignment converts an int to a block
4811    /// pointer. We disallow this.
4812    IntToBlockPointer,
4813
4814    /// IncompatibleBlockPointer - The assignment is between two block
4815    /// pointers types that are not compatible.
4816    IncompatibleBlockPointer,
4817
4818    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
4819    /// id type and something else (that is incompatible with it). For example,
4820    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
4821    IncompatibleObjCQualifiedId,
4822
4823    /// Incompatible - We reject this conversion outright, it is invalid to
4824    /// represent it in the AST.
4825    Incompatible
4826  };
4827
4828  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
4829  /// assignment conversion type specified by ConvTy.  This returns true if the
4830  /// conversion was invalid or false if the conversion was accepted.
4831  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
4832                                SourceLocation Loc,
4833                                QualType DstType, QualType SrcType,
4834                                Expr *SrcExpr, AssignmentAction Action,
4835                                bool *Complained = 0);
4836
4837  /// CheckAssignmentConstraints - Perform type checking for assignment,
4838  /// argument passing, variable initialization, and function return values.
4839  /// C99 6.5.16.
4840  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
4841                                               QualType lhs, QualType rhs);
4842
4843  /// Check assignment constraints and prepare for a conversion of the
4844  /// RHS to the LHS type.
4845  AssignConvertType CheckAssignmentConstraints(QualType lhs, Expr *&rhs,
4846                                               CastKind &Kind);
4847
4848  // CheckSingleAssignmentConstraints - Currently used by
4849  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
4850  // this routine performs the default function/array converions.
4851  AssignConvertType CheckSingleAssignmentConstraints(QualType lhs,
4852                                                     Expr *&rExpr);
4853
4854  // \brief If the lhs type is a transparent union, check whether we
4855  // can initialize the transparent union with the given expression.
4856  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType lhs,
4857                                                             Expr *&rExpr);
4858
4859  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
4860
4861  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
4862
4863  bool PerformImplicitConversion(Expr *&From, QualType ToType,
4864                                 AssignmentAction Action,
4865                                 bool AllowExplicit = false);
4866  bool PerformImplicitConversion(Expr *&From, QualType ToType,
4867                                 AssignmentAction Action,
4868                                 bool AllowExplicit,
4869                                 ImplicitConversionSequence& ICS);
4870  bool PerformImplicitConversion(Expr *&From, QualType ToType,
4871                                 const ImplicitConversionSequence& ICS,
4872                                 AssignmentAction Action,
4873                                 bool CStyle = false);
4874  bool PerformImplicitConversion(Expr *&From, QualType ToType,
4875                                 const StandardConversionSequence& SCS,
4876                                 AssignmentAction Action,
4877                                 bool CStyle);
4878
4879  /// the following "Check" methods will return a valid/converted QualType
4880  /// or a null QualType (indicating an error diagnostic was issued).
4881
4882  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
4883  QualType InvalidOperands(SourceLocation l, Expr *&lex, Expr *&rex);
4884  QualType CheckPointerToMemberOperands( // C++ 5.5
4885    Expr *&lex, Expr *&rex, ExprValueKind &VK,
4886    SourceLocation OpLoc, bool isIndirect);
4887  QualType CheckMultiplyDivideOperands( // C99 6.5.5
4888    Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign,
4889                                       bool isDivide);
4890  QualType CheckRemainderOperands( // C99 6.5.5
4891    Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
4892  QualType CheckAdditionOperands( // C99 6.5.6
4893    Expr *&lex, Expr *&rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
4894  QualType CheckSubtractionOperands( // C99 6.5.6
4895    Expr *&lex, Expr *&rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
4896  QualType CheckShiftOperands( // C99 6.5.7
4897    Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc,
4898    bool isCompAssign = false);
4899  QualType CheckCompareOperands( // C99 6.5.8/9
4900    Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc,
4901                                bool isRelational);
4902  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
4903    Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
4904  QualType CheckLogicalOperands( // C99 6.5.[13,14]
4905    Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc);
4906  // CheckAssignmentOperands is used for both simple and compound assignment.
4907  // For simple assignment, pass both expressions and a null converted type.
4908  // For compound assignment, pass both expressions and the converted type.
4909  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
4910    Expr *lex, Expr *&rex, SourceLocation OpLoc, QualType convertedType);
4911
4912  void ConvertPropertyForRValue(Expr *&E);
4913  void ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType& LHSTy);
4914
4915  QualType CheckConditionalOperands( // C99 6.5.15
4916    Expr *&cond, Expr *&lhs, Expr *&rhs,
4917    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
4918  QualType CXXCheckConditionalOperands( // C++ 5.16
4919    Expr *&cond, Expr *&lhs, Expr *&rhs,
4920    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
4921  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
4922                                    bool *NonStandardCompositeType = 0);
4923
4924  QualType FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4925                                        SourceLocation questionLoc);
4926
4927  bool DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4928                                  SourceLocation QuestionLoc);
4929
4930  /// type checking for vector binary operators.
4931  QualType CheckVectorOperands(SourceLocation l, Expr *&lex, Expr *&rex);
4932  QualType CheckVectorCompareOperands(Expr *&lex, Expr *&rx,
4933                                      SourceLocation l, bool isRel);
4934
4935  /// type checking declaration initializers (C99 6.7.8)
4936  bool CheckInitList(const InitializedEntity &Entity,
4937                     InitListExpr *&InitList, QualType &DeclType);
4938  bool CheckForConstantInitializer(Expr *e, QualType t);
4939
4940  // type checking C++ declaration initializers (C++ [dcl.init]).
4941
4942  /// ReferenceCompareResult - Expresses the result of comparing two
4943  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
4944  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
4945  enum ReferenceCompareResult {
4946    /// Ref_Incompatible - The two types are incompatible, so direct
4947    /// reference binding is not possible.
4948    Ref_Incompatible = 0,
4949    /// Ref_Related - The two types are reference-related, which means
4950    /// that their unqualified forms (T1 and T2) are either the same
4951    /// or T1 is a base class of T2.
4952    Ref_Related,
4953    /// Ref_Compatible_With_Added_Qualification - The two types are
4954    /// reference-compatible with added qualification, meaning that
4955    /// they are reference-compatible and the qualifiers on T1 (cv1)
4956    /// are greater than the qualifiers on T2 (cv2).
4957    Ref_Compatible_With_Added_Qualification,
4958    /// Ref_Compatible - The two types are reference-compatible and
4959    /// have equivalent qualifiers (cv1 == cv2).
4960    Ref_Compatible
4961  };
4962
4963  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
4964                                                      QualType T1, QualType T2,
4965                                                      bool &DerivedToBase,
4966                                                      bool &ObjCConversion);
4967
4968  /// CheckCastTypes - Check type constraints for casting between types under
4969  /// C semantics, or forward to CXXCheckCStyleCast in C++.
4970  bool CheckCastTypes(SourceRange TyRange, QualType CastTy, Expr *&CastExpr,
4971                      CastKind &Kind, ExprValueKind &VK, CXXCastPath &BasePath,
4972                      bool FunctionalStyle = false);
4973
4974  // CheckVectorCast - check type constraints for vectors.
4975  // Since vectors are an extension, there are no C standard reference for this.
4976  // We allow casting between vectors and integer datatypes of the same size.
4977  // returns true if the cast is invalid
4978  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4979                       CastKind &Kind);
4980
4981  // CheckExtVectorCast - check type constraints for extended vectors.
4982  // Since vectors are an extension, there are no C standard reference for this.
4983  // We allow casting between vectors and integer datatypes of the same size,
4984  // or vectors and the element type of that vector.
4985  // returns true if the cast is invalid
4986  bool CheckExtVectorCast(SourceRange R, QualType VectorTy, Expr *&CastExpr,
4987                          CastKind &Kind);
4988
4989  /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
4990  /// cast under C++ semantics.
4991  bool CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
4992                          Expr *&CastExpr, CastKind &Kind,
4993                          CXXCastPath &BasePath, bool FunctionalStyle);
4994
4995  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
4996  /// \param Method - May be null.
4997  /// \param [out] ReturnType - The return type of the send.
4998  /// \return true iff there were any incompatible types.
4999  bool CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, Selector Sel,
5000                                 ObjCMethodDecl *Method, bool isClassMessage,
5001                                 SourceLocation lbrac, SourceLocation rbrac,
5002                                 QualType &ReturnType, ExprValueKind &VK);
5003
5004  /// CheckBooleanCondition - Diagnose problems involving the use of
5005  /// the given expression as a boolean condition (e.g. in an if
5006  /// statement).  Also performs the standard function and array
5007  /// decays, possibly changing the input variable.
5008  ///
5009  /// \param Loc - A location associated with the condition, e.g. the
5010  /// 'if' keyword.
5011  /// \return true iff there were any errors
5012  bool CheckBooleanCondition(Expr *&CondExpr, SourceLocation Loc);
5013
5014  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
5015                                           Expr *SubExpr);
5016
5017  /// DiagnoseAssignmentAsCondition - Given that an expression is
5018  /// being used as a boolean condition, warn if it's an assignment.
5019  void DiagnoseAssignmentAsCondition(Expr *E);
5020
5021  /// \brief Redundant parentheses over an equality comparison can indicate
5022  /// that the user intended an assignment used as condition.
5023  void DiagnoseEqualityWithExtraParens(ParenExpr *parenE);
5024
5025  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
5026  bool CheckCXXBooleanCondition(Expr *&CondExpr);
5027
5028  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
5029  /// the specified width and sign.  If an overflow occurs, detect it and emit
5030  /// the specified diagnostic.
5031  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
5032                                          unsigned NewWidth, bool NewSign,
5033                                          SourceLocation Loc, unsigned DiagID);
5034
5035  /// Checks that the Objective-C declaration is declared in the global scope.
5036  /// Emits an error and marks the declaration as invalid if it's not declared
5037  /// in the global scope.
5038  bool CheckObjCDeclScope(Decl *D);
5039
5040  /// VerifyIntegerConstantExpression - verifies that an expression is an ICE,
5041  /// and reports the appropriate diagnostics. Returns false on success.
5042  /// Can optionally return the value of the expression.
5043  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0);
5044
5045  /// VerifyBitField - verifies that a bit field expression is an ICE and has
5046  /// the correct width, and that the field type is valid.
5047  /// Returns false on success.
5048  /// Can optionally return whether the bit-field is of width 0
5049  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5050                      QualType FieldTy, const Expr *BitWidth,
5051                      bool *ZeroWidth = 0);
5052
5053  /// \name Code completion
5054  //@{
5055  /// \brief Describes the context in which code completion occurs.
5056  enum ParserCompletionContext {
5057    /// \brief Code completion occurs at top-level or namespace context.
5058    PCC_Namespace,
5059    /// \brief Code completion occurs within a class, struct, or union.
5060    PCC_Class,
5061    /// \brief Code completion occurs within an Objective-C interface, protocol,
5062    /// or category.
5063    PCC_ObjCInterface,
5064    /// \brief Code completion occurs within an Objective-C implementation or
5065    /// category implementation
5066    PCC_ObjCImplementation,
5067    /// \brief Code completion occurs within the list of instance variables
5068    /// in an Objective-C interface, protocol, category, or implementation.
5069    PCC_ObjCInstanceVariableList,
5070    /// \brief Code completion occurs following one or more template
5071    /// headers.
5072    PCC_Template,
5073    /// \brief Code completion occurs following one or more template
5074    /// headers within a class.
5075    PCC_MemberTemplate,
5076    /// \brief Code completion occurs within an expression.
5077    PCC_Expression,
5078    /// \brief Code completion occurs within a statement, which may
5079    /// also be an expression or a declaration.
5080    PCC_Statement,
5081    /// \brief Code completion occurs at the beginning of the
5082    /// initialization statement (or expression) in a for loop.
5083    PCC_ForInit,
5084    /// \brief Code completion occurs within the condition of an if,
5085    /// while, switch, or for statement.
5086    PCC_Condition,
5087    /// \brief Code completion occurs within the body of a function on a
5088    /// recovery path, where we do not have a specific handle on our position
5089    /// in the grammar.
5090    PCC_RecoveryInFunction,
5091    /// \brief Code completion occurs where only a type is permitted.
5092    PCC_Type,
5093    /// \brief Code completion occurs in a parenthesized expression, which
5094    /// might also be a type cast.
5095    PCC_ParenthesizedExpression,
5096    /// \brief Code completion occurs within a sequence of declaration
5097    /// specifiers within a function, method, or block.
5098    PCC_LocalDeclarationSpecifiers
5099  };
5100
5101  void CodeCompleteOrdinaryName(Scope *S,
5102                                ParserCompletionContext CompletionContext);
5103  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
5104                            bool AllowNonIdentifiers,
5105                            bool AllowNestedNameSpecifiers);
5106
5107  struct CodeCompleteExpressionData;
5108  void CodeCompleteExpression(Scope *S,
5109                              const CodeCompleteExpressionData &Data);
5110  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5111                                       SourceLocation OpLoc,
5112                                       bool IsArrow);
5113  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
5114  void CodeCompleteTag(Scope *S, unsigned TagSpec);
5115  void CodeCompleteTypeQualifiers(DeclSpec &DS);
5116  void CodeCompleteCase(Scope *S);
5117  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
5118  void CodeCompleteInitializer(Scope *S, Decl *D);
5119  void CodeCompleteReturn(Scope *S);
5120  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
5121
5122  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
5123                               bool EnteringContext);
5124  void CodeCompleteUsing(Scope *S);
5125  void CodeCompleteUsingDirective(Scope *S);
5126  void CodeCompleteNamespaceDecl(Scope *S);
5127  void CodeCompleteNamespaceAliasDecl(Scope *S);
5128  void CodeCompleteOperatorName(Scope *S);
5129  void CodeCompleteConstructorInitializer(Decl *Constructor,
5130                                          CXXCtorInitializer** Initializers,
5131                                          unsigned NumInitializers);
5132
5133  void CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
5134                                   bool InInterface);
5135  void CodeCompleteObjCAtVisibility(Scope *S);
5136  void CodeCompleteObjCAtStatement(Scope *S);
5137  void CodeCompleteObjCAtExpression(Scope *S);
5138  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
5139  void CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl);
5140  void CodeCompleteObjCPropertySetter(Scope *S, Decl *ClassDecl);
5141  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5142                                   bool IsParameter);
5143  void CodeCompleteObjCMessageReceiver(Scope *S);
5144  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5145                                    IdentifierInfo **SelIdents,
5146                                    unsigned NumSelIdents,
5147                                    bool AtArgumentExpression);
5148  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5149                                    IdentifierInfo **SelIdents,
5150                                    unsigned NumSelIdents,
5151                                    bool AtArgumentExpression,
5152                                    bool IsSuper = false);
5153  void CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
5154                                       IdentifierInfo **SelIdents,
5155                                       unsigned NumSelIdents,
5156                                       bool AtArgumentExpression,
5157                                       ObjCInterfaceDecl *Super = 0);
5158  void CodeCompleteObjCForCollection(Scope *S,
5159                                     DeclGroupPtrTy IterationVar);
5160  void CodeCompleteObjCSelector(Scope *S,
5161                                IdentifierInfo **SelIdents,
5162                                unsigned NumSelIdents);
5163  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5164                                          unsigned NumProtocols);
5165  void CodeCompleteObjCProtocolDecl(Scope *S);
5166  void CodeCompleteObjCInterfaceDecl(Scope *S);
5167  void CodeCompleteObjCSuperclass(Scope *S,
5168                                  IdentifierInfo *ClassName,
5169                                  SourceLocation ClassNameLoc);
5170  void CodeCompleteObjCImplementationDecl(Scope *S);
5171  void CodeCompleteObjCInterfaceCategory(Scope *S,
5172                                         IdentifierInfo *ClassName,
5173                                         SourceLocation ClassNameLoc);
5174  void CodeCompleteObjCImplementationCategory(Scope *S,
5175                                              IdentifierInfo *ClassName,
5176                                              SourceLocation ClassNameLoc);
5177  void CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl);
5178  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5179                                              IdentifierInfo *PropertyName,
5180                                              Decl *ObjCImpDecl);
5181  void CodeCompleteObjCMethodDecl(Scope *S,
5182                                  bool IsInstanceMethod,
5183                                  ParsedType ReturnType,
5184                                  Decl *IDecl);
5185  void CodeCompleteObjCMethodDeclSelector(Scope *S,
5186                                          bool IsInstanceMethod,
5187                                          bool AtParameterName,
5188                                          ParsedType ReturnType,
5189                                          IdentifierInfo **SelIdents,
5190                                          unsigned NumSelIdents);
5191  void CodeCompletePreprocessorDirective(bool InConditional);
5192  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
5193  void CodeCompletePreprocessorMacroName(bool IsDefinition);
5194  void CodeCompletePreprocessorExpression();
5195  void CodeCompletePreprocessorMacroArgument(Scope *S,
5196                                             IdentifierInfo *Macro,
5197                                             MacroInfo *MacroInfo,
5198                                             unsigned Argument);
5199  void CodeCompleteNaturalLanguage();
5200  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
5201                  llvm::SmallVectorImpl<CodeCompletionResult> &Results);
5202  //@}
5203
5204  void PrintStats() const {}
5205
5206  //===--------------------------------------------------------------------===//
5207  // Extra semantic analysis beyond the C type system
5208
5209public:
5210  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
5211                                                unsigned ByteNo) const;
5212
5213private:
5214  void CheckArrayAccess(const Expr *E);
5215  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
5216  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
5217
5218  bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
5219  bool CheckObjCString(Expr *Arg);
5220
5221  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5222  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5223
5224  bool SemaBuiltinVAStart(CallExpr *TheCall);
5225  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
5226  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
5227
5228public:
5229  // Used by C++ template instantiation.
5230  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
5231
5232private:
5233  bool SemaBuiltinPrefetch(CallExpr *TheCall);
5234  bool SemaBuiltinObjectSize(CallExpr *TheCall);
5235  bool SemaBuiltinLongjmp(CallExpr *TheCall);
5236  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
5237  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5238                              llvm::APSInt &Result);
5239
5240  bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
5241                              bool HasVAListArg, unsigned format_idx,
5242                              unsigned firstDataArg, bool isPrintf);
5243
5244  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
5245                         const CallExpr *TheCall, bool HasVAListArg,
5246                         unsigned format_idx, unsigned firstDataArg,
5247                         bool isPrintf);
5248
5249  void CheckNonNullArguments(const NonNullAttr *NonNull,
5250                             const CallExpr *TheCall);
5251
5252  void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
5253                                 unsigned format_idx, unsigned firstDataArg,
5254                                 bool isPrintf);
5255
5256  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
5257                            SourceLocation ReturnLoc);
5258  void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex);
5259  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
5260
5261  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
5262                                   Expr *Init);
5263
5264  /// \brief The parser's current scope.
5265  ///
5266  /// The parser maintains this state here.
5267  Scope *CurScope;
5268
5269protected:
5270  friend class Parser;
5271  friend class InitializationSequence;
5272
5273  /// \brief Retrieve the parser's current scope.
5274  Scope *getCurScope() const { return CurScope; }
5275};
5276
5277/// \brief RAII object that enters a new expression evaluation context.
5278class EnterExpressionEvaluationContext {
5279  Sema &Actions;
5280
5281public:
5282  EnterExpressionEvaluationContext(Sema &Actions,
5283                                   Sema::ExpressionEvaluationContext NewContext)
5284    : Actions(Actions) {
5285    Actions.PushExpressionEvaluationContext(NewContext);
5286  }
5287
5288  ~EnterExpressionEvaluationContext() {
5289    Actions.PopExpressionEvaluationContext();
5290  }
5291};
5292
5293}  // end namespace clang
5294
5295#endif
5296