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