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