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