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