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