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