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