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