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