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