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