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