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