Sema.h revision bcdd7d92883d771106e54357245733358eac9672
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  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
1837                             Sema::LookupNameKind LookupKind,
1838                             Scope *S, CXXScopeSpec *SS,
1839                             CorrectionCandidateCallback *CCC,
1840                             DeclContext *MemberContext = 0,
1841                             bool EnteringContext = false,
1842                             const ObjCObjectPointerType *OPT = 0);
1843
1844  void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1845                                   AssociatedNamespaceSet &AssociatedNamespaces,
1846                                   AssociatedClassSet &AssociatedClasses);
1847
1848  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1849                            bool ConsiderLinkage,
1850                            bool ExplicitInstantiationOrSpecialization);
1851
1852  bool DiagnoseAmbiguousLookup(LookupResult &Result);
1853  //@}
1854
1855  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
1856                                          SourceLocation IdLoc,
1857                                          bool TypoCorrection = false);
1858  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1859                                 Scope *S, bool ForRedeclaration,
1860                                 SourceLocation Loc);
1861  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
1862                                      Scope *S);
1863  void AddKnownFunctionAttributes(FunctionDecl *FD);
1864
1865  // More parsing and symbol table subroutines.
1866
1867  // Decl attributes - this routine is the top level dispatcher.
1868  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
1869                           bool NonInheritable = true, bool Inheritable = true);
1870  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
1871                           bool NonInheritable = true, bool Inheritable = true);
1872  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
1873                                      const AttributeList *AttrList);
1874
1875  void checkUnusedDeclAttributes(Declarator &D);
1876
1877  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
1878  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC);
1879  bool CheckNoReturnAttr(const AttributeList &attr);
1880
1881  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1882                           bool &IncompleteImpl, unsigned DiagID);
1883  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
1884                                   ObjCMethodDecl *MethodDecl,
1885                                   bool IsProtocolMethodDecl);
1886
1887  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1888                                   ObjCMethodDecl *Overridden,
1889                                   bool IsProtocolMethodDecl);
1890
1891  /// WarnExactTypedMethods - This routine issues a warning if method
1892  /// implementation declaration matches exactly that of its declaration.
1893  void WarnExactTypedMethods(ObjCMethodDecl *Method,
1894                             ObjCMethodDecl *MethodDecl,
1895                             bool IsProtocolMethodDecl);
1896
1897  bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
1898                          ObjCInterfaceDecl *IDecl);
1899
1900  typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet;
1901  typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
1902
1903  /// CheckProtocolMethodDefs - This routine checks unimplemented
1904  /// methods declared in protocol, and those referenced by it.
1905  /// \param IDecl - Used for checking for methods which may have been
1906  /// inherited.
1907  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
1908                               ObjCProtocolDecl *PDecl,
1909                               bool& IncompleteImpl,
1910                               const SelectorSet &InsMap,
1911                               const SelectorSet &ClsMap,
1912                               ObjCContainerDecl *CDecl);
1913
1914  /// CheckImplementationIvars - This routine checks if the instance variables
1915  /// listed in the implelementation match those listed in the interface.
1916  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1917                                ObjCIvarDecl **Fields, unsigned nIvars,
1918                                SourceLocation Loc);
1919
1920  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
1921  /// remains unimplemented in the class or category @implementation.
1922  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1923                                 ObjCContainerDecl* IDecl,
1924                                 bool IncompleteImpl = false);
1925
1926  /// DiagnoseUnimplementedProperties - This routine warns on those properties
1927  /// which must be implemented by this implementation.
1928  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1929                                       ObjCContainerDecl *CDecl,
1930                                       const SelectorSet &InsMap);
1931
1932  /// DefaultSynthesizeProperties - This routine default synthesizes all
1933  /// properties which must be synthesized in class's @implementation.
1934  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
1935                                    ObjCInterfaceDecl *IDecl);
1936  void DefaultSynthesizeProperties(Scope *S, Decl *D);
1937
1938  /// CollectImmediateProperties - This routine collects all properties in
1939  /// the class and its conforming protocols; but not those it its super class.
1940  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
1941            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
1942            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
1943
1944
1945  /// LookupPropertyDecl - Looks up a property in the current class and all
1946  /// its protocols.
1947  ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl,
1948                                       IdentifierInfo *II);
1949
1950  /// Called by ActOnProperty to handle @property declarations in
1951  ////  class extensions.
1952  Decl *HandlePropertyInClassExtension(Scope *S,
1953                                       SourceLocation AtLoc,
1954                                       FieldDeclarator &FD,
1955                                       Selector GetterSel,
1956                                       Selector SetterSel,
1957                                       const bool isAssign,
1958                                       const bool isReadWrite,
1959                                       const unsigned Attributes,
1960                                       const unsigned AttributesAsWritten,
1961                                       bool *isOverridingProperty,
1962                                       TypeSourceInfo *T,
1963                                       tok::ObjCKeywordKind MethodImplKind);
1964
1965  /// Called by ActOnProperty and HandlePropertyInClassExtension to
1966  ///  handle creating the ObjcPropertyDecl for a category or @interface.
1967  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
1968                                       ObjCContainerDecl *CDecl,
1969                                       SourceLocation AtLoc,
1970                                       FieldDeclarator &FD,
1971                                       Selector GetterSel,
1972                                       Selector SetterSel,
1973                                       const bool isAssign,
1974                                       const bool isReadWrite,
1975                                       const unsigned Attributes,
1976                                       const unsigned AttributesAsWritten,
1977                                       TypeSourceInfo *T,
1978                                       tok::ObjCKeywordKind MethodImplKind,
1979                                       DeclContext *lexicalDC = 0);
1980
1981  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
1982  /// warning) when atomic property has one but not the other user-declared
1983  /// setter or getter.
1984  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
1985                                       ObjCContainerDecl* IDecl);
1986
1987  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
1988
1989  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
1990
1991  enum MethodMatchStrategy {
1992    MMS_loose,
1993    MMS_strict
1994  };
1995
1996  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
1997  /// true, or false, accordingly.
1998  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1999                                  const ObjCMethodDecl *PrevMethod,
2000                                  MethodMatchStrategy strategy = MMS_strict);
2001
2002  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2003  /// or protocol against those declared in their implementations.
2004  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2005                                  const SelectorSet &ClsMap,
2006                                  SelectorSet &InsMapSeen,
2007                                  SelectorSet &ClsMapSeen,
2008                                  ObjCImplDecl* IMPDecl,
2009                                  ObjCContainerDecl* IDecl,
2010                                  bool &IncompleteImpl,
2011                                  bool ImmediateClass,
2012                                  bool WarnExactMatch=false);
2013
2014  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2015  /// category matches with those implemented in its primary class and
2016  /// warns each time an exact match is found.
2017  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2018
2019private:
2020  /// AddMethodToGlobalPool - Add an instance or factory method to the global
2021  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2022  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2023
2024  /// LookupMethodInGlobalPool - Returns the instance or factory method and
2025  /// optionally warns if there are multiple signatures.
2026  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2027                                           bool receiverIdOrClass,
2028                                           bool warn, bool instance);
2029
2030public:
2031  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2032  /// unit are added to a global pool. This allows us to efficiently associate
2033  /// a selector with a method declaraation for purposes of typechecking
2034  /// messages sent to "id" (where the class of the object is unknown).
2035  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2036    AddMethodToGlobalPool(Method, impl, /*instance*/true);
2037  }
2038
2039  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2040  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2041    AddMethodToGlobalPool(Method, impl, /*instance*/false);
2042  }
2043
2044  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2045  /// pool.
2046  void AddAnyMethodToGlobalPool(Decl *D);
2047
2048  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2049  /// there are multiple signatures.
2050  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2051                                                   bool receiverIdOrClass=false,
2052                                                   bool warn=true) {
2053    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2054                                    warn, /*instance*/true);
2055  }
2056
2057  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2058  /// there are multiple signatures.
2059  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2060                                                  bool receiverIdOrClass=false,
2061                                                  bool warn=true) {
2062    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2063                                    warn, /*instance*/false);
2064  }
2065
2066  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2067  /// implementation.
2068  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2069
2070  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2071  /// initialization.
2072  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2073                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2074
2075  //===--------------------------------------------------------------------===//
2076  // Statement Parsing Callbacks: SemaStmt.cpp.
2077public:
2078  class FullExprArg {
2079  public:
2080    FullExprArg(Sema &actions) : E(0) { }
2081
2082    // FIXME: The const_cast here is ugly. RValue references would make this
2083    // much nicer (or we could duplicate a bunch of the move semantics
2084    // emulation code from Ownership.h).
2085    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2086
2087    ExprResult release() {
2088      return move(E);
2089    }
2090
2091    Expr *get() const { return E; }
2092
2093    Expr *operator->() {
2094      return E;
2095    }
2096
2097  private:
2098    // FIXME: No need to make the entire Sema class a friend when it's just
2099    // Sema::MakeFullExpr that needs access to the constructor below.
2100    friend class Sema;
2101
2102    explicit FullExprArg(Expr *expr) : E(expr) {}
2103
2104    Expr *E;
2105  };
2106
2107  FullExprArg MakeFullExpr(Expr *Arg) {
2108    return FullExprArg(ActOnFinishFullExpr(Arg).release());
2109  }
2110
2111  StmtResult ActOnExprStmt(FullExprArg Expr);
2112
2113  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2114                           bool HasLeadingEmptyMacro = false);
2115  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2116                                       MultiStmtArg Elts,
2117                                       bool isStmtExpr);
2118  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2119                                   SourceLocation StartLoc,
2120                                   SourceLocation EndLoc);
2121  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2122  StmtResult ActOnForEachLValueExpr(Expr *E);
2123  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2124                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
2125                                   SourceLocation ColonLoc);
2126  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2127
2128  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2129                                      SourceLocation ColonLoc,
2130                                      Stmt *SubStmt, Scope *CurScope);
2131  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2132                            SourceLocation ColonLoc, Stmt *SubStmt);
2133
2134  StmtResult ActOnIfStmt(SourceLocation IfLoc,
2135                         FullExprArg CondVal, Decl *CondVar,
2136                         Stmt *ThenVal,
2137                         SourceLocation ElseLoc, Stmt *ElseVal);
2138  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2139                                            Expr *Cond,
2140                                            Decl *CondVar);
2141  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2142                                           Stmt *Switch, Stmt *Body);
2143  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2144                            FullExprArg Cond,
2145                            Decl *CondVar, Stmt *Body);
2146  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2147                                 SourceLocation WhileLoc,
2148                                 SourceLocation CondLParen, Expr *Cond,
2149                                 SourceLocation CondRParen);
2150
2151  StmtResult ActOnForStmt(SourceLocation ForLoc,
2152                          SourceLocation LParenLoc,
2153                          Stmt *First, FullExprArg Second,
2154                          Decl *SecondVar,
2155                          FullExprArg Third,
2156                          SourceLocation RParenLoc,
2157                          Stmt *Body);
2158  ExprResult ActOnObjCForCollectionOperand(SourceLocation forLoc,
2159                                           Expr *collection);
2160  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2161                                        SourceLocation LParenLoc,
2162                                        Stmt *First, Expr *Second,
2163                                        SourceLocation RParenLoc, Stmt *Body);
2164  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc,
2165                                  SourceLocation LParenLoc, Stmt *LoopVar,
2166                                  SourceLocation ColonLoc, Expr *Collection,
2167                                  SourceLocation RParenLoc);
2168  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2169                                  SourceLocation ColonLoc,
2170                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
2171                                  Expr *Cond, Expr *Inc,
2172                                  Stmt *LoopVarDecl,
2173                                  SourceLocation RParenLoc);
2174  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2175
2176  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2177                           SourceLocation LabelLoc,
2178                           LabelDecl *TheDecl);
2179  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2180                                   SourceLocation StarLoc,
2181                                   Expr *DestExp);
2182  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2183  StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
2184
2185  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2186                                         bool AllowFunctionParameters);
2187
2188  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2189  StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2190
2191  StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
2192                          bool IsSimple, bool IsVolatile,
2193                          unsigned NumOutputs, unsigned NumInputs,
2194                          IdentifierInfo **Names,
2195                          MultiExprArg Constraints,
2196                          MultiExprArg Exprs,
2197                          Expr *AsmString,
2198                          MultiExprArg Clobbers,
2199                          SourceLocation RParenLoc,
2200                          bool MSAsm = false);
2201
2202
2203  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2204                                  SourceLocation StartLoc,
2205                                  SourceLocation IdLoc, IdentifierInfo *Id,
2206                                  bool Invalid = false);
2207
2208  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2209
2210  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2211                                  Decl *Parm, Stmt *Body);
2212
2213  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2214
2215  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2216                                MultiStmtArg Catch, Stmt *Finally);
2217
2218  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2219  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2220                                  Scope *CurScope);
2221  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
2222                                            Expr *operand);
2223  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2224                                         Expr *SynchExpr,
2225                                         Stmt *SynchBody);
2226
2227  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2228
2229  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2230                                     SourceLocation StartLoc,
2231                                     SourceLocation IdLoc,
2232                                     IdentifierInfo *Id);
2233
2234  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2235
2236  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2237                                Decl *ExDecl, Stmt *HandlerBlock);
2238  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2239                              MultiStmtArg Handlers);
2240
2241  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2242                              SourceLocation TryLoc,
2243                              Stmt *TryBlock,
2244                              Stmt *Handler);
2245
2246  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2247                                 Expr *FilterExpr,
2248                                 Stmt *Block);
2249
2250  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2251                                  Stmt *Block);
2252
2253  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2254
2255  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2256
2257  /// \brief If it's a file scoped decl that must warn if not used, keep track
2258  /// of it.
2259  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2260
2261  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2262  /// whose result is unused, warn.
2263  void DiagnoseUnusedExprResult(const Stmt *S);
2264  void DiagnoseUnusedDecl(const NamedDecl *ND);
2265
2266  ParsingDeclState PushParsingDeclaration() {
2267    return DelayedDiagnostics.pushParsingDecl();
2268  }
2269  void PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
2270    DelayedDiagnostics::popParsingDecl(*this, state, decl);
2271  }
2272
2273  typedef ProcessingContextState ParsingClassState;
2274  ParsingClassState PushParsingClass() {
2275    return DelayedDiagnostics.pushContext();
2276  }
2277  void PopParsingClass(ParsingClassState state) {
2278    DelayedDiagnostics.popContext(state);
2279  }
2280
2281  void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
2282                              SourceLocation Loc,
2283                              const ObjCInterfaceDecl *UnknownObjCClass=0);
2284
2285  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2286
2287  bool makeUnavailableInSystemHeader(SourceLocation loc,
2288                                     StringRef message);
2289
2290  //===--------------------------------------------------------------------===//
2291  // Expression Parsing Callbacks: SemaExpr.cpp.
2292
2293  bool CanUseDecl(NamedDecl *D);
2294  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2295                         const ObjCInterfaceDecl *UnknownObjCClass=0);
2296  AvailabilityResult DiagnoseAvailabilityOfDecl(NamedDecl *D,
2297                              SourceLocation Loc,
2298                              const ObjCInterfaceDecl *UnknownObjCClass);
2299  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2300  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2301                                        ObjCMethodDecl *Getter,
2302                                        SourceLocation Loc);
2303  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2304                             Expr **Args, unsigned NumArgs);
2305
2306  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext);
2307
2308  void PopExpressionEvaluationContext();
2309
2310  void DiscardCleanupsInEvaluationContext();
2311
2312  void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
2313  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
2314  void MarkDeclarationsReferencedInExpr(Expr *E);
2315
2316  /// \brief Try to recover by turning the given expression into a
2317  /// call.  Returns true if recovery was attempted or an error was
2318  /// emitted; this may also leave the ExprResult invalid.
2319  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2320                            bool ForceComplain = false,
2321                            bool (*IsPlausibleResult)(QualType) = 0);
2322
2323  /// \brief Figure out if an expression could be turned into a call.
2324  bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
2325                      UnresolvedSetImpl &NonTemplateOverloads);
2326
2327  /// \brief Conditionally issue a diagnostic based on the current
2328  /// evaluation context.
2329  ///
2330  /// \param stmt - If stmt is non-null, delay reporting the diagnostic until
2331  ///  the function body is parsed, and then do a basic reachability analysis to
2332  ///  determine if the statement is reachable.  If it is unreachable, the
2333  ///  diagnostic will not be emitted.
2334  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
2335                           const PartialDiagnostic &PD);
2336
2337  // Primary Expressions.
2338  SourceRange getExprRange(Expr *E) const;
2339
2340  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Id,
2341                               bool HasTrailingLParen, bool IsAddressOfOperand);
2342
2343  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
2344                              TemplateArgumentListInfo &Buffer,
2345                              DeclarationNameInfo &NameInfo,
2346                              const TemplateArgumentListInfo *&TemplateArgs);
2347
2348  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2349                           CorrectionCandidateCallback &CCC,
2350                           TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
2351                           Expr **Args = 0, unsigned NumArgs = 0);
2352
2353  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
2354                                IdentifierInfo *II,
2355                                bool AllowBuiltinCreation=false);
2356
2357  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
2358                                        const DeclarationNameInfo &NameInfo,
2359                                        bool isAddressOfOperand,
2360                                const TemplateArgumentListInfo *TemplateArgs);
2361
2362  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2363                              ExprValueKind VK,
2364                              SourceLocation Loc,
2365                              const CXXScopeSpec *SS = 0);
2366  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2367                              ExprValueKind VK,
2368                              const DeclarationNameInfo &NameInfo,
2369                              const CXXScopeSpec *SS = 0);
2370  ExprResult
2371  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
2372                                           SourceLocation nameLoc,
2373                                           IndirectFieldDecl *indirectField,
2374                                           Expr *baseObjectExpr = 0,
2375                                      SourceLocation opLoc = SourceLocation());
2376  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2377                                             LookupResult &R,
2378                                const TemplateArgumentListInfo *TemplateArgs);
2379  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2380                                     LookupResult &R,
2381                                const TemplateArgumentListInfo *TemplateArgs,
2382                                     bool IsDefiniteInstance);
2383  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
2384                                  const LookupResult &R,
2385                                  bool HasTrailingLParen);
2386
2387  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2388                                         const DeclarationNameInfo &NameInfo);
2389  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
2390                                const DeclarationNameInfo &NameInfo,
2391                                const TemplateArgumentListInfo *TemplateArgs);
2392
2393  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2394                                      LookupResult &R,
2395                                      bool NeedsADL);
2396  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2397                                      const DeclarationNameInfo &NameInfo,
2398                                      NamedDecl *D);
2399
2400  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
2401  ExprResult ActOnNumericConstant(const Token &Tok);
2402  ExprResult ActOnCharacterConstant(const Token &Tok);
2403  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
2404  ExprResult ActOnParenOrParenListExpr(SourceLocation L,
2405                                       SourceLocation R,
2406                                       MultiExprArg Val);
2407
2408  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2409  /// fragments (e.g. "foo" "bar" L"baz").
2410  ExprResult ActOnStringLiteral(const Token *StringToks,
2411                                unsigned NumStringToks);
2412
2413  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
2414                                       SourceLocation DefaultLoc,
2415                                       SourceLocation RParenLoc,
2416                                       Expr *ControllingExpr,
2417                                       MultiTypeArg ArgTypes,
2418                                       MultiExprArg ArgExprs);
2419  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
2420                                        SourceLocation DefaultLoc,
2421                                        SourceLocation RParenLoc,
2422                                        Expr *ControllingExpr,
2423                                        TypeSourceInfo **Types,
2424                                        Expr **Exprs,
2425                                        unsigned NumAssocs);
2426
2427  // Binary/Unary Operators.  'Tok' is the token for the operator.
2428  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
2429                                  Expr *InputExpr);
2430  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
2431                          UnaryOperatorKind Opc, Expr *Input);
2432  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
2433                          tok::TokenKind Op, Expr *Input);
2434
2435  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2436                                            SourceLocation OpLoc,
2437                                            UnaryExprOrTypeTrait ExprKind,
2438                                            SourceRange R);
2439  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2440                                            UnaryExprOrTypeTrait ExprKind);
2441  ExprResult
2442    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2443                                  UnaryExprOrTypeTrait ExprKind,
2444                                  bool IsType, void *TyOrEx,
2445                                  const SourceRange &ArgRange);
2446
2447  ExprResult CheckPlaceholderExpr(Expr *E);
2448  bool CheckVecStepExpr(Expr *E);
2449
2450  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
2451  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
2452                                        SourceRange ExprRange,
2453                                        UnaryExprOrTypeTrait ExprKind);
2454  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
2455                                          SourceLocation OpLoc,
2456                                          IdentifierInfo &Name,
2457                                          SourceLocation NameLoc,
2458                                          SourceLocation RParenLoc);
2459  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2460                                 tok::TokenKind Kind, Expr *Input);
2461
2462  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2463                                     Expr *Idx, SourceLocation RLoc);
2464  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2465                                             Expr *Idx, SourceLocation RLoc);
2466
2467  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2468                                      SourceLocation OpLoc, bool IsArrow,
2469                                      CXXScopeSpec &SS,
2470                                      NamedDecl *FirstQualifierInScope,
2471                                const DeclarationNameInfo &NameInfo,
2472                                const TemplateArgumentListInfo *TemplateArgs);
2473
2474  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2475                                      SourceLocation OpLoc, bool IsArrow,
2476                                      const CXXScopeSpec &SS,
2477                                      NamedDecl *FirstQualifierInScope,
2478                                      LookupResult &R,
2479                                 const TemplateArgumentListInfo *TemplateArgs,
2480                                      bool SuppressQualifierCheck = false);
2481
2482  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
2483  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
2484                              bool &IsArrow, SourceLocation OpLoc,
2485                              CXXScopeSpec &SS,
2486                              Decl *ObjCImpDecl,
2487                              bool HasTemplateArgs);
2488
2489  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
2490                                     const CXXScopeSpec &SS,
2491                                     const LookupResult &R);
2492
2493  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
2494                                      bool IsArrow, SourceLocation OpLoc,
2495                                      const CXXScopeSpec &SS,
2496                                      NamedDecl *FirstQualifierInScope,
2497                               const DeclarationNameInfo &NameInfo,
2498                               const TemplateArgumentListInfo *TemplateArgs);
2499
2500  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
2501                                   SourceLocation OpLoc,
2502                                   tok::TokenKind OpKind,
2503                                   CXXScopeSpec &SS,
2504                                   UnqualifiedId &Member,
2505                                   Decl *ObjCImpDecl,
2506                                   bool HasTrailingLParen);
2507
2508  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
2509  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2510                               FunctionDecl *FDecl,
2511                               const FunctionProtoType *Proto,
2512                               Expr **Args, unsigned NumArgs,
2513                               SourceLocation RParenLoc,
2514                               bool ExecConfig = false);
2515  void CheckStaticArrayArgument(SourceLocation CallLoc,
2516                                ParmVarDecl *Param,
2517                                const Expr *ArgExpr);
2518
2519  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2520  /// This provides the location of the left/right parens and a list of comma
2521  /// locations.
2522  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
2523                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
2524                           Expr *ExecConfig = 0, bool IsExecConfig = false);
2525  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
2526                                   SourceLocation LParenLoc,
2527                                   Expr **Args, unsigned NumArgs,
2528                                   SourceLocation RParenLoc,
2529                                   Expr *Config = 0,
2530                                   bool IsExecConfig = false);
2531
2532  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
2533                                     MultiExprArg ExecConfig,
2534                                     SourceLocation GGGLoc);
2535
2536  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
2537                           Declarator &D, ParsedType &Ty,
2538                           SourceLocation RParenLoc, Expr *CastExpr);
2539  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
2540                                 TypeSourceInfo *Ty,
2541                                 SourceLocation RParenLoc,
2542                                 Expr *Op);
2543  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
2544
2545  /// \brief Build an altivec or OpenCL literal.
2546  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
2547                                SourceLocation RParenLoc, Expr *E,
2548                                TypeSourceInfo *TInfo);
2549
2550  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
2551
2552  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
2553                                  ParsedType Ty,
2554                                  SourceLocation RParenLoc,
2555                                  Expr *InitExpr);
2556
2557  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
2558                                      TypeSourceInfo *TInfo,
2559                                      SourceLocation RParenLoc,
2560                                      Expr *LiteralExpr);
2561
2562  ExprResult ActOnInitList(SourceLocation LBraceLoc,
2563                           MultiExprArg InitArgList,
2564                           SourceLocation RBraceLoc);
2565
2566  ExprResult ActOnDesignatedInitializer(Designation &Desig,
2567                                        SourceLocation Loc,
2568                                        bool GNUSyntax,
2569                                        ExprResult Init);
2570
2571  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
2572                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
2573  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
2574                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
2575  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
2576                                Expr *LHSExpr, Expr *RHSExpr);
2577
2578  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2579  /// in the case of a the GNU conditional expr extension.
2580  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
2581                                SourceLocation ColonLoc,
2582                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
2583
2584  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2585  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
2586                            LabelDecl *TheDecl);
2587
2588  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
2589                           SourceLocation RPLoc); // "({..})"
2590
2591  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2592  struct OffsetOfComponent {
2593    SourceLocation LocStart, LocEnd;
2594    bool isBrackets;  // true if [expr], false if .ident
2595    union {
2596      IdentifierInfo *IdentInfo;
2597      Expr *E;
2598    } U;
2599  };
2600
2601  /// __builtin_offsetof(type, a.b[123][456].c)
2602  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
2603                                  TypeSourceInfo *TInfo,
2604                                  OffsetOfComponent *CompPtr,
2605                                  unsigned NumComponents,
2606                                  SourceLocation RParenLoc);
2607  ExprResult ActOnBuiltinOffsetOf(Scope *S,
2608                                  SourceLocation BuiltinLoc,
2609                                  SourceLocation TypeLoc,
2610                                  ParsedType ParsedArgTy,
2611                                  OffsetOfComponent *CompPtr,
2612                                  unsigned NumComponents,
2613                                  SourceLocation RParenLoc);
2614
2615  // __builtin_choose_expr(constExpr, expr1, expr2)
2616  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
2617                             Expr *CondExpr, Expr *LHSExpr,
2618                             Expr *RHSExpr, SourceLocation RPLoc);
2619
2620  // __builtin_va_arg(expr, type)
2621  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
2622                        SourceLocation RPLoc);
2623  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
2624                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
2625
2626  // __null
2627  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
2628
2629  bool CheckCaseExpression(Expr *E);
2630
2631  /// \brief Describes the result of an "if-exists" condition check.
2632  enum IfExistsResult {
2633    /// \brief The symbol exists.
2634    IER_Exists,
2635
2636    /// \brief The symbol does not exist.
2637    IER_DoesNotExist,
2638
2639    /// \brief The name is a dependent name, so the results will differ
2640    /// from one instantiation to the next.
2641    IER_Dependent,
2642
2643    /// \brief An error occurred.
2644    IER_Error
2645  };
2646
2647  IfExistsResult
2648  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
2649                               const DeclarationNameInfo &TargetNameInfo);
2650
2651  IfExistsResult
2652  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
2653                               bool IsIfExists, CXXScopeSpec &SS,
2654                               UnqualifiedId &Name);
2655
2656  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2657                                        bool IsIfExists,
2658                                        NestedNameSpecifierLoc QualifierLoc,
2659                                        DeclarationNameInfo NameInfo,
2660                                        Stmt *Nested);
2661  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2662                                        bool IsIfExists,
2663                                        CXXScopeSpec &SS, UnqualifiedId &Name,
2664                                        Stmt *Nested);
2665
2666  //===------------------------- "Block" Extension ------------------------===//
2667
2668  /// ActOnBlockStart - This callback is invoked when a block literal is
2669  /// started.
2670  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
2671
2672  /// ActOnBlockArguments - This callback allows processing of block arguments.
2673  /// If there are no arguments, this is still invoked.
2674  void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
2675
2676  /// ActOnBlockError - If there is an error parsing a block, this callback
2677  /// is invoked to pop the information about the block from the action impl.
2678  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
2679
2680  /// ActOnBlockStmtExpr - This is called when the body of a block statement
2681  /// literal was successfully completed.  ^(int x){...}
2682  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
2683                                Scope *CurScope);
2684
2685  //===---------------------------- OpenCL Features -----------------------===//
2686
2687  /// __builtin_astype(...)
2688  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
2689                             SourceLocation BuiltinLoc,
2690                             SourceLocation RParenLoc);
2691
2692  //===---------------------------- C++ Features --------------------------===//
2693
2694  // Act on C++ namespaces
2695  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
2696                               SourceLocation NamespaceLoc,
2697                               SourceLocation IdentLoc,
2698                               IdentifierInfo *Ident,
2699                               SourceLocation LBrace,
2700                               AttributeList *AttrList);
2701  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
2702
2703  NamespaceDecl *getStdNamespace() const;
2704  NamespaceDecl *getOrCreateStdNamespace();
2705
2706  CXXRecordDecl *getStdBadAlloc() const;
2707
2708  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
2709  /// it is and Element is not NULL, assigns the element type to Element.
2710  bool isStdInitializerList(QualType Ty, QualType *Element);
2711
2712  /// \brief Looks for the std::initializer_list template and instantiates it
2713  /// with Element, or emits an error if it's not found.
2714  ///
2715  /// \returns The instantiated template, or null on error.
2716  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
2717
2718  /// \brief Determine whether Ctor is an initializer-list constructor, as
2719  /// defined in [dcl.init.list]p2.
2720  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
2721
2722  Decl *ActOnUsingDirective(Scope *CurScope,
2723                            SourceLocation UsingLoc,
2724                            SourceLocation NamespcLoc,
2725                            CXXScopeSpec &SS,
2726                            SourceLocation IdentLoc,
2727                            IdentifierInfo *NamespcName,
2728                            AttributeList *AttrList);
2729
2730  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
2731
2732  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
2733                               SourceLocation NamespaceLoc,
2734                               SourceLocation AliasLoc,
2735                               IdentifierInfo *Alias,
2736                               CXXScopeSpec &SS,
2737                               SourceLocation IdentLoc,
2738                               IdentifierInfo *Ident);
2739
2740  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
2741  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
2742                            const LookupResult &PreviousDecls);
2743  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
2744                                        NamedDecl *Target);
2745
2746  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
2747                                   bool isTypeName,
2748                                   const CXXScopeSpec &SS,
2749                                   SourceLocation NameLoc,
2750                                   const LookupResult &Previous);
2751  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
2752                               const CXXScopeSpec &SS,
2753                               SourceLocation NameLoc);
2754
2755  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2756                                   SourceLocation UsingLoc,
2757                                   CXXScopeSpec &SS,
2758                                   const DeclarationNameInfo &NameInfo,
2759                                   AttributeList *AttrList,
2760                                   bool IsInstantiation,
2761                                   bool IsTypeName,
2762                                   SourceLocation TypenameLoc);
2763
2764  bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
2765
2766  Decl *ActOnUsingDeclaration(Scope *CurScope,
2767                              AccessSpecifier AS,
2768                              bool HasUsingKeyword,
2769                              SourceLocation UsingLoc,
2770                              CXXScopeSpec &SS,
2771                              UnqualifiedId &Name,
2772                              AttributeList *AttrList,
2773                              bool IsTypeName,
2774                              SourceLocation TypenameLoc);
2775  Decl *ActOnAliasDeclaration(Scope *CurScope,
2776                              AccessSpecifier AS,
2777                              MultiTemplateParamsArg TemplateParams,
2778                              SourceLocation UsingLoc,
2779                              UnqualifiedId &Name,
2780                              TypeResult Type);
2781
2782  /// AddCXXDirectInitializerToDecl - This action is called immediately after
2783  /// ActOnDeclarator, when a C++ direct initializer is present.
2784  /// e.g: "int x(1);"
2785  void AddCXXDirectInitializerToDecl(Decl *Dcl,
2786                                     SourceLocation LParenLoc,
2787                                     MultiExprArg Exprs,
2788                                     SourceLocation RParenLoc,
2789                                     bool TypeMayContainAuto);
2790
2791  /// InitializeVarWithConstructor - Creates an CXXConstructExpr
2792  /// and sets it as the initializer for the the passed in VarDecl.
2793  bool InitializeVarWithConstructor(VarDecl *VD,
2794                                    CXXConstructorDecl *Constructor,
2795                                    MultiExprArg Exprs,
2796                                    bool HadMultipleCandidates);
2797
2798  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
2799  /// including handling of its default argument expressions.
2800  ///
2801  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
2802  ExprResult
2803  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2804                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
2805                        bool HadMultipleCandidates, bool RequiresZeroInit,
2806                        unsigned ConstructKind, SourceRange ParenRange);
2807
2808  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
2809  // the constructor can be elidable?
2810  ExprResult
2811  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2812                        CXXConstructorDecl *Constructor, bool Elidable,
2813                        MultiExprArg Exprs, bool HadMultipleCandidates,
2814                        bool RequiresZeroInit, unsigned ConstructKind,
2815                        SourceRange ParenRange);
2816
2817  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
2818  /// the default expr if needed.
2819  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2820                                    FunctionDecl *FD,
2821                                    ParmVarDecl *Param);
2822
2823  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
2824  /// constructed variable.
2825  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
2826
2827  /// \brief Helper class that collects exception specifications for
2828  /// implicitly-declared special member functions.
2829  class ImplicitExceptionSpecification {
2830    // Pointer to allow copying
2831    ASTContext *Context;
2832    // We order exception specifications thus:
2833    // noexcept is the most restrictive, but is only used in C++0x.
2834    // throw() comes next.
2835    // Then a throw(collected exceptions)
2836    // Finally no specification.
2837    // throw(...) is used instead if any called function uses it.
2838    //
2839    // If this exception specification cannot be known yet (for instance,
2840    // because this is the exception specification for a defaulted default
2841    // constructor and we haven't finished parsing the deferred parts of the
2842    // class yet), the C++0x standard does not specify how to behave. We
2843    // record this as an 'unknown' exception specification, which overrules
2844    // any other specification (even 'none', to keep this rule simple).
2845    ExceptionSpecificationType ComputedEST;
2846    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2847    SmallVector<QualType, 4> Exceptions;
2848
2849    void ClearExceptions() {
2850      ExceptionsSeen.clear();
2851      Exceptions.clear();
2852    }
2853
2854  public:
2855    explicit ImplicitExceptionSpecification(ASTContext &Context)
2856      : Context(&Context), ComputedEST(EST_BasicNoexcept) {
2857      if (!Context.getLangOptions().CPlusPlus0x)
2858        ComputedEST = EST_DynamicNone;
2859    }
2860
2861    /// \brief Get the computed exception specification type.
2862    ExceptionSpecificationType getExceptionSpecType() const {
2863      assert(ComputedEST != EST_ComputedNoexcept &&
2864             "noexcept(expr) should not be a possible result");
2865      return ComputedEST;
2866    }
2867
2868    /// \brief The number of exceptions in the exception specification.
2869    unsigned size() const { return Exceptions.size(); }
2870
2871    /// \brief The set of exceptions in the exception specification.
2872    const QualType *data() const { return Exceptions.data(); }
2873
2874    /// \brief Integrate another called method into the collected data.
2875    void CalledDecl(CXXMethodDecl *Method);
2876
2877    /// \brief Integrate an invoked expression into the collected data.
2878    void CalledExpr(Expr *E);
2879
2880    /// \brief Specify that the exception specification can't be detemined yet.
2881    void SetDelayed() {
2882      ClearExceptions();
2883      ComputedEST = EST_Delayed;
2884    }
2885
2886    FunctionProtoType::ExtProtoInfo getEPI() const {
2887      FunctionProtoType::ExtProtoInfo EPI;
2888      EPI.ExceptionSpecType = getExceptionSpecType();
2889      EPI.NumExceptions = size();
2890      EPI.Exceptions = data();
2891      return EPI;
2892    }
2893  };
2894
2895  /// \brief Determine what sort of exception specification a defaulted
2896  /// copy constructor of a class will have.
2897  ImplicitExceptionSpecification
2898  ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl);
2899
2900  /// \brief Determine what sort of exception specification a defaulted
2901  /// default constructor of a class will have, and whether the parameter
2902  /// will be const.
2903  std::pair<ImplicitExceptionSpecification, bool>
2904  ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
2905
2906  /// \brief Determine what sort of exception specification a defautled
2907  /// copy assignment operator of a class will have, and whether the
2908  /// parameter will be const.
2909  std::pair<ImplicitExceptionSpecification, bool>
2910  ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
2911
2912  /// \brief Determine what sort of exception specification a defaulted move
2913  /// constructor of a class will have.
2914  ImplicitExceptionSpecification
2915  ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl);
2916
2917  /// \brief Determine what sort of exception specification a defaulted move
2918  /// assignment operator of a class will have.
2919  ImplicitExceptionSpecification
2920  ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl);
2921
2922  /// \brief Determine what sort of exception specification a defaulted
2923  /// destructor of a class will have.
2924  ImplicitExceptionSpecification
2925  ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl);
2926
2927  /// \brief Determine if a special member function should have a deleted
2928  /// definition when it is defaulted.
2929  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM);
2930
2931  /// \brief Determine if a defaulted copy assignment operator ought to be
2932  /// deleted.
2933  bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD);
2934
2935  /// \brief Determine if a defaulted move assignment operator ought to be
2936  /// deleted.
2937  bool ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD);
2938
2939  /// \brief Determine if a defaulted destructor ought to be deleted.
2940  bool ShouldDeleteDestructor(CXXDestructorDecl *DD);
2941
2942  /// \brief Declare the implicit default constructor for the given class.
2943  ///
2944  /// \param ClassDecl The class declaration into which the implicit
2945  /// default constructor will be added.
2946  ///
2947  /// \returns The implicitly-declared default constructor.
2948  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
2949                                                     CXXRecordDecl *ClassDecl);
2950
2951  /// DefineImplicitDefaultConstructor - Checks for feasibility of
2952  /// defining this constructor as the default constructor.
2953  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2954                                        CXXConstructorDecl *Constructor);
2955
2956  /// \brief Declare the implicit destructor for the given class.
2957  ///
2958  /// \param ClassDecl The class declaration into which the implicit
2959  /// destructor will be added.
2960  ///
2961  /// \returns The implicitly-declared destructor.
2962  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
2963
2964  /// DefineImplicitDestructor - Checks for feasibility of
2965  /// defining this destructor as the default destructor.
2966  void DefineImplicitDestructor(SourceLocation CurrentLocation,
2967                                CXXDestructorDecl *Destructor);
2968
2969  /// \brief Build an exception spec for destructors that don't have one.
2970  ///
2971  /// C++11 says that user-defined destructors with no exception spec get one
2972  /// that looks as if the destructor was implicitly declared.
2973  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
2974                                     CXXDestructorDecl *Destructor);
2975
2976  /// \brief Declare all inherited constructors for the given class.
2977  ///
2978  /// \param ClassDecl The class declaration into which the inherited
2979  /// constructors will be added.
2980  void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
2981
2982  /// \brief Declare the implicit copy constructor for the given class.
2983  ///
2984  /// \param ClassDecl The class declaration into which the implicit
2985  /// copy constructor will be added.
2986  ///
2987  /// \returns The implicitly-declared copy constructor.
2988  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
2989
2990  /// DefineImplicitCopyConstructor - Checks for feasibility of
2991  /// defining this constructor as the copy constructor.
2992  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2993                                     CXXConstructorDecl *Constructor);
2994
2995  /// \brief Declare the implicit move constructor for the given class.
2996  ///
2997  /// \param ClassDecl The Class declaration into which the implicit
2998  /// move constructor will be added.
2999  ///
3000  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3001  /// declared.
3002  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3003
3004  /// DefineImplicitMoveConstructor - Checks for feasibility of
3005  /// defining this constructor as the move constructor.
3006  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3007                                     CXXConstructorDecl *Constructor);
3008
3009  /// \brief Declare the implicit copy assignment operator for the given class.
3010  ///
3011  /// \param ClassDecl The class declaration into which the implicit
3012  /// copy assignment operator will be added.
3013  ///
3014  /// \returns The implicitly-declared copy assignment operator.
3015  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3016
3017  /// \brief Defines an implicitly-declared copy assignment operator.
3018  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3019                                    CXXMethodDecl *MethodDecl);
3020
3021  /// \brief Declare the implicit move assignment operator for the given class.
3022  ///
3023  /// \param ClassDecl The Class declaration into which the implicit
3024  /// move assignment operator will be added.
3025  ///
3026  /// \returns The implicitly-declared move assignment operator, or NULL if it
3027  /// wasn't declared.
3028  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3029
3030  /// \brief Defines an implicitly-declared move assignment operator.
3031  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3032                                    CXXMethodDecl *MethodDecl);
3033
3034  /// \brief Force the declaration of any implicitly-declared members of this
3035  /// class.
3036  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3037
3038  /// MaybeBindToTemporary - If the passed in expression has a record type with
3039  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3040  /// it simply returns the passed in expression.
3041  ExprResult MaybeBindToTemporary(Expr *E);
3042
3043  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3044                               MultiExprArg ArgsPtr,
3045                               SourceLocation Loc,
3046                               ASTOwningVector<Expr*> &ConvertedArgs);
3047
3048  ParsedType getDestructorName(SourceLocation TildeLoc,
3049                               IdentifierInfo &II, SourceLocation NameLoc,
3050                               Scope *S, CXXScopeSpec &SS,
3051                               ParsedType ObjectType,
3052                               bool EnteringContext);
3053
3054  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3055
3056  // Checks that reinterpret casts don't have undefined behavior.
3057  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3058                                      bool IsDereference, SourceRange Range);
3059
3060  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3061  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3062                               tok::TokenKind Kind,
3063                               SourceLocation LAngleBracketLoc,
3064                               Declarator &D,
3065                               SourceLocation RAngleBracketLoc,
3066                               SourceLocation LParenLoc,
3067                               Expr *E,
3068                               SourceLocation RParenLoc);
3069
3070  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3071                               tok::TokenKind Kind,
3072                               TypeSourceInfo *Ty,
3073                               Expr *E,
3074                               SourceRange AngleBrackets,
3075                               SourceRange Parens);
3076
3077  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3078                            SourceLocation TypeidLoc,
3079                            TypeSourceInfo *Operand,
3080                            SourceLocation RParenLoc);
3081  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3082                            SourceLocation TypeidLoc,
3083                            Expr *Operand,
3084                            SourceLocation RParenLoc);
3085
3086  /// ActOnCXXTypeid - Parse typeid( something ).
3087  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3088                            SourceLocation LParenLoc, bool isType,
3089                            void *TyOrExpr,
3090                            SourceLocation RParenLoc);
3091
3092  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3093                            SourceLocation TypeidLoc,
3094                            TypeSourceInfo *Operand,
3095                            SourceLocation RParenLoc);
3096  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3097                            SourceLocation TypeidLoc,
3098                            Expr *Operand,
3099                            SourceLocation RParenLoc);
3100
3101  /// ActOnCXXUuidof - Parse __uuidof( something ).
3102  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3103                            SourceLocation LParenLoc, bool isType,
3104                            void *TyOrExpr,
3105                            SourceLocation RParenLoc);
3106
3107
3108  //// ActOnCXXThis -  Parse 'this' pointer.
3109  ExprResult ActOnCXXThis(SourceLocation loc);
3110
3111  /// \brief Try to retrieve the type of the 'this' pointer.
3112  ///
3113  /// \param Capture If true, capture 'this' in this context.
3114  ///
3115  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3116  QualType getCurrentThisType();
3117
3118  /// \brief Make sure the value of 'this' is actually available in the current
3119  /// context, if it is a potentially evaluated context. This check can be
3120  /// delayed in PotentiallyPotentiallyEvaluated contexts.
3121  void CheckCXXThisCapture(SourceLocation Loc);
3122
3123  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3124  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3125
3126  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
3127  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
3128
3129  //// ActOnCXXThrow -  Parse throw expressions.
3130  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
3131  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
3132                           bool IsThrownVarInScope);
3133  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
3134                                  bool IsThrownVarInScope);
3135
3136  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
3137  /// Can be interpreted either as function-style casting ("int(x)")
3138  /// or class type construction ("ClassType(x,y,z)")
3139  /// or creation of a value-initialized type ("int()").
3140  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
3141                                       SourceLocation LParenLoc,
3142                                       MultiExprArg Exprs,
3143                                       SourceLocation RParenLoc);
3144
3145  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
3146                                       SourceLocation LParenLoc,
3147                                       MultiExprArg Exprs,
3148                                       SourceLocation RParenLoc);
3149
3150  /// ActOnCXXNew - Parsed a C++ 'new' expression.
3151  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
3152                         SourceLocation PlacementLParen,
3153                         MultiExprArg PlacementArgs,
3154                         SourceLocation PlacementRParen,
3155                         SourceRange TypeIdParens, Declarator &D,
3156                         SourceLocation ConstructorLParen,
3157                         MultiExprArg ConstructorArgs,
3158                         SourceLocation ConstructorRParen);
3159  ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
3160                         SourceLocation PlacementLParen,
3161                         MultiExprArg PlacementArgs,
3162                         SourceLocation PlacementRParen,
3163                         SourceRange TypeIdParens,
3164                         QualType AllocType,
3165                         TypeSourceInfo *AllocTypeInfo,
3166                         Expr *ArraySize,
3167                         SourceLocation ConstructorLParen,
3168                         MultiExprArg ConstructorArgs,
3169                         SourceLocation ConstructorRParen,
3170                         bool TypeMayContainAuto = true);
3171
3172  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
3173                          SourceRange R);
3174  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
3175                               bool UseGlobal, QualType AllocType, bool IsArray,
3176                               Expr **PlaceArgs, unsigned NumPlaceArgs,
3177                               FunctionDecl *&OperatorNew,
3178                               FunctionDecl *&OperatorDelete);
3179  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
3180                              DeclarationName Name, Expr** Args,
3181                              unsigned NumArgs, DeclContext *Ctx,
3182                              bool AllowMissing, FunctionDecl *&Operator,
3183                              bool Diagnose = true);
3184  void DeclareGlobalNewDelete();
3185  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
3186                                       QualType Argument,
3187                                       bool addMallocAttr = false);
3188
3189  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3190                                DeclarationName Name, FunctionDecl* &Operator,
3191                                bool Diagnose = true);
3192
3193  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
3194  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
3195                            bool UseGlobal, bool ArrayForm,
3196                            Expr *Operand);
3197
3198  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
3199  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
3200                                    SourceLocation StmtLoc,
3201                                    bool ConvertToBoolean);
3202
3203  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
3204                               Expr *Operand, SourceLocation RParen);
3205  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3206                                  SourceLocation RParen);
3207
3208  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
3209  /// pseudo-functions.
3210  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
3211                                 SourceLocation KWLoc,
3212                                 ParsedType Ty,
3213                                 SourceLocation RParen);
3214
3215  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
3216                                 SourceLocation KWLoc,
3217                                 TypeSourceInfo *T,
3218                                 SourceLocation RParen);
3219
3220  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
3221  /// pseudo-functions.
3222  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
3223                                  SourceLocation KWLoc,
3224                                  ParsedType LhsTy,
3225                                  ParsedType RhsTy,
3226                                  SourceLocation RParen);
3227
3228  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3229                                  SourceLocation KWLoc,
3230                                  TypeSourceInfo *LhsT,
3231                                  TypeSourceInfo *RhsT,
3232                                  SourceLocation RParen);
3233
3234  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
3235  /// pseudo-functions.
3236  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3237                                 SourceLocation KWLoc,
3238                                 ParsedType LhsTy,
3239                                 Expr *DimExpr,
3240                                 SourceLocation RParen);
3241
3242  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
3243                                 SourceLocation KWLoc,
3244                                 TypeSourceInfo *TSInfo,
3245                                 Expr *DimExpr,
3246                                 SourceLocation RParen);
3247
3248  /// ActOnExpressionTrait - Parsed one of the unary type trait support
3249  /// pseudo-functions.
3250  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
3251                                  SourceLocation KWLoc,
3252                                  Expr *Queried,
3253                                  SourceLocation RParen);
3254
3255  ExprResult BuildExpressionTrait(ExpressionTrait OET,
3256                                  SourceLocation KWLoc,
3257                                  Expr *Queried,
3258                                  SourceLocation RParen);
3259
3260  ExprResult ActOnStartCXXMemberReference(Scope *S,
3261                                          Expr *Base,
3262                                          SourceLocation OpLoc,
3263                                          tok::TokenKind OpKind,
3264                                          ParsedType &ObjectType,
3265                                          bool &MayBePseudoDestructor);
3266
3267  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
3268
3269  ExprResult BuildPseudoDestructorExpr(Expr *Base,
3270                                       SourceLocation OpLoc,
3271                                       tok::TokenKind OpKind,
3272                                       const CXXScopeSpec &SS,
3273                                       TypeSourceInfo *ScopeType,
3274                                       SourceLocation CCLoc,
3275                                       SourceLocation TildeLoc,
3276                                     PseudoDestructorTypeStorage DestroyedType,
3277                                       bool HasTrailingLParen);
3278
3279  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3280                                       SourceLocation OpLoc,
3281                                       tok::TokenKind OpKind,
3282                                       CXXScopeSpec &SS,
3283                                       UnqualifiedId &FirstTypeName,
3284                                       SourceLocation CCLoc,
3285                                       SourceLocation TildeLoc,
3286                                       UnqualifiedId &SecondTypeName,
3287                                       bool HasTrailingLParen);
3288
3289  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3290                                       SourceLocation OpLoc,
3291                                       tok::TokenKind OpKind,
3292                                       SourceLocation TildeLoc,
3293                                       const DeclSpec& DS,
3294                                       bool HasTrailingLParen);
3295
3296  /// MaybeCreateExprWithCleanups - If the current full-expression
3297  /// requires any cleanups, surround it with a ExprWithCleanups node.
3298  /// Otherwise, just returns the passed-in expression.
3299  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
3300  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
3301  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
3302
3303  ExprResult ActOnFinishFullExpr(Expr *Expr);
3304  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
3305
3306  // Marks SS invalid if it represents an incomplete type.
3307  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3308
3309  DeclContext *computeDeclContext(QualType T);
3310  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3311                                  bool EnteringContext = false);
3312  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3313  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
3314  bool isUnknownSpecialization(const CXXScopeSpec &SS);
3315
3316  /// \brief The parser has parsed a global nested-name-specifier '::'.
3317  ///
3318  /// \param S The scope in which this nested-name-specifier occurs.
3319  ///
3320  /// \param CCLoc The location of the '::'.
3321  ///
3322  /// \param SS The nested-name-specifier, which will be updated in-place
3323  /// to reflect the parsed nested-name-specifier.
3324  ///
3325  /// \returns true if an error occurred, false otherwise.
3326  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
3327                                    CXXScopeSpec &SS);
3328
3329  bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
3330  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
3331
3332  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
3333                                    SourceLocation IdLoc,
3334                                    IdentifierInfo &II,
3335                                    ParsedType ObjectType);
3336
3337  bool BuildCXXNestedNameSpecifier(Scope *S,
3338                                   IdentifierInfo &Identifier,
3339                                   SourceLocation IdentifierLoc,
3340                                   SourceLocation CCLoc,
3341                                   QualType ObjectType,
3342                                   bool EnteringContext,
3343                                   CXXScopeSpec &SS,
3344                                   NamedDecl *ScopeLookupResult,
3345                                   bool ErrorRecoveryLookup);
3346
3347  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
3348  ///
3349  /// \param S The scope in which this nested-name-specifier occurs.
3350  ///
3351  /// \param Identifier The identifier preceding the '::'.
3352  ///
3353  /// \param IdentifierLoc The location of the identifier.
3354  ///
3355  /// \param CCLoc The location of the '::'.
3356  ///
3357  /// \param ObjectType The type of the object, if we're parsing
3358  /// nested-name-specifier in a member access expression.
3359  ///
3360  /// \param EnteringContext Whether we're entering the context nominated by
3361  /// this nested-name-specifier.
3362  ///
3363  /// \param SS The nested-name-specifier, which is both an input
3364  /// parameter (the nested-name-specifier before this type) and an
3365  /// output parameter (containing the full nested-name-specifier,
3366  /// including this new type).
3367  ///
3368  /// \returns true if an error occurred, false otherwise.
3369  bool ActOnCXXNestedNameSpecifier(Scope *S,
3370                                   IdentifierInfo &Identifier,
3371                                   SourceLocation IdentifierLoc,
3372                                   SourceLocation CCLoc,
3373                                   ParsedType ObjectType,
3374                                   bool EnteringContext,
3375                                   CXXScopeSpec &SS);
3376
3377  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
3378                                           const DeclSpec &DS,
3379                                           SourceLocation ColonColonLoc);
3380
3381  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3382                                 IdentifierInfo &Identifier,
3383                                 SourceLocation IdentifierLoc,
3384                                 SourceLocation ColonLoc,
3385                                 ParsedType ObjectType,
3386                                 bool EnteringContext);
3387
3388  /// \brief The parser has parsed a nested-name-specifier
3389  /// 'template[opt] template-name < template-args >::'.
3390  ///
3391  /// \param S The scope in which this nested-name-specifier occurs.
3392  ///
3393  /// \param TemplateLoc The location of the 'template' keyword, if any.
3394  ///
3395  /// \param SS The nested-name-specifier, which is both an input
3396  /// parameter (the nested-name-specifier before this type) and an
3397  /// output parameter (containing the full nested-name-specifier,
3398  /// including this new type).
3399  ///
3400  /// \param TemplateLoc the location of the 'template' keyword, if any.
3401  /// \param TemplateName The template name.
3402  /// \param TemplateNameLoc The location of the template name.
3403  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3404  /// \param TemplateArgs The template arguments.
3405  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3406  /// \param CCLoc The location of the '::'.
3407
3408  /// \param EnteringContext Whether we're entering the context of the
3409  /// nested-name-specifier.
3410  ///
3411  ///
3412  /// \returns true if an error occurred, false otherwise.
3413  bool ActOnCXXNestedNameSpecifier(Scope *S,
3414                                   SourceLocation TemplateLoc,
3415                                   CXXScopeSpec &SS,
3416                                   TemplateTy Template,
3417                                   SourceLocation TemplateNameLoc,
3418                                   SourceLocation LAngleLoc,
3419                                   ASTTemplateArgsPtr TemplateArgs,
3420                                   SourceLocation RAngleLoc,
3421                                   SourceLocation CCLoc,
3422                                   bool EnteringContext);
3423
3424  /// \brief Given a C++ nested-name-specifier, produce an annotation value
3425  /// that the parser can use later to reconstruct the given
3426  /// nested-name-specifier.
3427  ///
3428  /// \param SS A nested-name-specifier.
3429  ///
3430  /// \returns A pointer containing all of the information in the
3431  /// nested-name-specifier \p SS.
3432  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3433
3434  /// \brief Given an annotation pointer for a nested-name-specifier, restore
3435  /// the nested-name-specifier structure.
3436  ///
3437  /// \param Annotation The annotation pointer, produced by
3438  /// \c SaveNestedNameSpecifierAnnotation().
3439  ///
3440  /// \param AnnotationRange The source range corresponding to the annotation.
3441  ///
3442  /// \param SS The nested-name-specifier that will be updated with the contents
3443  /// of the annotation pointer.
3444  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3445                                            SourceRange AnnotationRange,
3446                                            CXXScopeSpec &SS);
3447
3448  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3449
3450  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3451  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3452  /// After this method is called, according to [C++ 3.4.3p3], names should be
3453  /// looked up in the declarator-id's scope, until the declarator is parsed and
3454  /// ActOnCXXExitDeclaratorScope is called.
3455  /// The 'SS' should be a non-empty valid CXXScopeSpec.
3456  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3457
3458  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3459  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3460  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3461  /// Used to indicate that names should revert to being looked up in the
3462  /// defining scope.
3463  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3464
3465  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3466  /// initializer for the declaration 'Dcl'.
3467  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3468  /// static data member of class X, names should be looked up in the scope of
3469  /// class X.
3470  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
3471
3472  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3473  /// initializer for the declaration 'Dcl'.
3474  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
3475
3476  /// ActOnStartOfLambdaDefinition - This is called just before we start
3477  /// parsing the body of a lambda; it analyzes the explicit captures and
3478  /// arguments, and sets up various data-structures for the body of the
3479  /// lambda.
3480  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
3481                                    Declarator &ParamInfo, Scope *CurScope);
3482
3483  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
3484  /// is invoked to pop the information about the lambda.
3485  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope);
3486
3487  /// ActOnLambdaExpr - This is called when the body of a lambda expression
3488  /// was successfully completed.
3489  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
3490                             Scope *CurScope);
3491
3492  // ParseObjCStringLiteral - Parse Objective-C string literals.
3493  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
3494                                    Expr **Strings,
3495                                    unsigned NumStrings);
3496
3497  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
3498                                  TypeSourceInfo *EncodedTypeInfo,
3499                                  SourceLocation RParenLoc);
3500  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3501                                    CXXMethodDecl *Method,
3502                                    bool HadMultipleCandidates);
3503
3504  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
3505                                       SourceLocation EncodeLoc,
3506                                       SourceLocation LParenLoc,
3507                                       ParsedType Ty,
3508                                       SourceLocation RParenLoc);
3509
3510  // ParseObjCSelectorExpression - Build selector expression for @selector
3511  ExprResult ParseObjCSelectorExpression(Selector Sel,
3512                                         SourceLocation AtLoc,
3513                                         SourceLocation SelLoc,
3514                                         SourceLocation LParenLoc,
3515                                         SourceLocation RParenLoc);
3516
3517  // ParseObjCProtocolExpression - Build protocol expression for @protocol
3518  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
3519                                         SourceLocation AtLoc,
3520                                         SourceLocation ProtoLoc,
3521                                         SourceLocation LParenLoc,
3522                                         SourceLocation RParenLoc);
3523
3524  //===--------------------------------------------------------------------===//
3525  // C++ Declarations
3526  //
3527  Decl *ActOnStartLinkageSpecification(Scope *S,
3528                                       SourceLocation ExternLoc,
3529                                       SourceLocation LangLoc,
3530                                       StringRef Lang,
3531                                       SourceLocation LBraceLoc);
3532  Decl *ActOnFinishLinkageSpecification(Scope *S,
3533                                        Decl *LinkageSpec,
3534                                        SourceLocation RBraceLoc);
3535
3536
3537  //===--------------------------------------------------------------------===//
3538  // C++ Classes
3539  //
3540  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
3541                          const CXXScopeSpec *SS = 0);
3542
3543  bool ActOnAccessSpecifier(AccessSpecifier Access,
3544                            SourceLocation ASLoc,
3545                            SourceLocation ColonLoc,
3546                            AttributeList *Attrs = 0);
3547
3548  Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
3549                                 Declarator &D,
3550                                 MultiTemplateParamsArg TemplateParameterLists,
3551                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
3552                                 bool HasDeferredInit);
3553  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
3554                                        Expr *Init);
3555
3556  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3557                                    Scope *S,
3558                                    CXXScopeSpec &SS,
3559                                    IdentifierInfo *MemberOrBase,
3560                                    ParsedType TemplateTypeTy,
3561                                    SourceLocation IdLoc,
3562                                    SourceLocation LParenLoc,
3563                                    Expr **Args, unsigned NumArgs,
3564                                    SourceLocation RParenLoc,
3565                                    SourceLocation EllipsisLoc);
3566
3567  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3568                                    Scope *S,
3569                                    CXXScopeSpec &SS,
3570                                    IdentifierInfo *MemberOrBase,
3571                                    ParsedType TemplateTypeTy,
3572                                    SourceLocation IdLoc,
3573                                    Expr *InitList,
3574                                    SourceLocation EllipsisLoc);
3575
3576  MemInitResult BuildMemInitializer(Decl *ConstructorD,
3577                                    Scope *S,
3578                                    CXXScopeSpec &SS,
3579                                    IdentifierInfo *MemberOrBase,
3580                                    ParsedType TemplateTypeTy,
3581                                    SourceLocation IdLoc,
3582                                    const MultiInitializer &Init,
3583                                    SourceLocation EllipsisLoc);
3584
3585  MemInitResult BuildMemberInitializer(ValueDecl *Member,
3586                                       const MultiInitializer &Args,
3587                                       SourceLocation IdLoc);
3588
3589  MemInitResult BuildBaseInitializer(QualType BaseType,
3590                                     TypeSourceInfo *BaseTInfo,
3591                                     const MultiInitializer &Args,
3592                                     CXXRecordDecl *ClassDecl,
3593                                     SourceLocation EllipsisLoc);
3594
3595  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
3596                                           const MultiInitializer &Args,
3597                                           CXXRecordDecl *ClassDecl);
3598
3599  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3600                                CXXCtorInitializer *Initializer);
3601
3602  bool SetCtorInitializers(CXXConstructorDecl *Constructor,
3603                           CXXCtorInitializer **Initializers,
3604                           unsigned NumInitializers, bool AnyErrors);
3605
3606  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
3607
3608
3609  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
3610  /// mark all the non-trivial destructors of its members and bases as
3611  /// referenced.
3612  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
3613                                              CXXRecordDecl *Record);
3614
3615  /// \brief The list of classes whose vtables have been used within
3616  /// this translation unit, and the source locations at which the
3617  /// first use occurred.
3618  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
3619
3620  /// \brief The list of vtables that are required but have not yet been
3621  /// materialized.
3622  SmallVector<VTableUse, 16> VTableUses;
3623
3624  /// \brief The set of classes whose vtables have been used within
3625  /// this translation unit, and a bit that will be true if the vtable is
3626  /// required to be emitted (otherwise, it should be emitted only if needed
3627  /// by code generation).
3628  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
3629
3630  /// \brief Load any externally-stored vtable uses.
3631  void LoadExternalVTableUses();
3632
3633  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
3634                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
3635    DynamicClassesType;
3636
3637  /// \brief A list of all of the dynamic classes in this translation
3638  /// unit.
3639  DynamicClassesType DynamicClasses;
3640
3641  /// \brief Note that the vtable for the given class was used at the
3642  /// given location.
3643  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
3644                      bool DefinitionRequired = false);
3645
3646  /// MarkVirtualMembersReferenced - Will mark all members of the given
3647  /// CXXRecordDecl referenced.
3648  void MarkVirtualMembersReferenced(SourceLocation Loc,
3649                                    const CXXRecordDecl *RD);
3650
3651  /// \brief Define all of the vtables that have been used in this
3652  /// translation unit and reference any virtual members used by those
3653  /// vtables.
3654  ///
3655  /// \returns true if any work was done, false otherwise.
3656  bool DefineUsedVTables();
3657
3658  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
3659
3660  void ActOnMemInitializers(Decl *ConstructorDecl,
3661                            SourceLocation ColonLoc,
3662                            CXXCtorInitializer **MemInits,
3663                            unsigned NumMemInits,
3664                            bool AnyErrors);
3665
3666  void CheckCompletedCXXClass(CXXRecordDecl *Record);
3667  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3668                                         Decl *TagDecl,
3669                                         SourceLocation LBrac,
3670                                         SourceLocation RBrac,
3671                                         AttributeList *AttrList);
3672
3673  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
3674  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
3675  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
3676  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3677  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
3678  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
3679  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3680  void ActOnFinishDelayedMemberInitializers(Decl *Record);
3681  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
3682  bool IsInsideALocalClassWithinATemplateFunction();
3683
3684  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
3685                                     Expr *AssertExpr,
3686                                     Expr *AssertMessageExpr,
3687                                     SourceLocation RParenLoc);
3688
3689  FriendDecl *CheckFriendTypeDecl(SourceLocation Loc,
3690                                  SourceLocation FriendLoc,
3691                                  TypeSourceInfo *TSInfo);
3692  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
3693                            MultiTemplateParamsArg TemplateParams);
3694  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
3695                                MultiTemplateParamsArg TemplateParams);
3696
3697  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
3698                                      StorageClass& SC);
3699  void CheckConstructor(CXXConstructorDecl *Constructor);
3700  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
3701                                     StorageClass& SC);
3702  bool CheckDestructor(CXXDestructorDecl *Destructor);
3703  void CheckConversionDeclarator(Declarator &D, QualType &R,
3704                                 StorageClass& SC);
3705  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
3706
3707  void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
3708  void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor);
3709  void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor);
3710  void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method);
3711  void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor);
3712  void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method);
3713  void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor);
3714
3715  //===--------------------------------------------------------------------===//
3716  // C++ Derived Classes
3717  //
3718
3719  /// ActOnBaseSpecifier - Parsed a base specifier
3720  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
3721                                       SourceRange SpecifierRange,
3722                                       bool Virtual, AccessSpecifier Access,
3723                                       TypeSourceInfo *TInfo,
3724                                       SourceLocation EllipsisLoc);
3725
3726  BaseResult ActOnBaseSpecifier(Decl *classdecl,
3727                                SourceRange SpecifierRange,
3728                                bool Virtual, AccessSpecifier Access,
3729                                ParsedType basetype,
3730                                SourceLocation BaseLoc,
3731                                SourceLocation EllipsisLoc);
3732
3733  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
3734                            unsigned NumBases);
3735  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
3736                           unsigned NumBases);
3737
3738  bool IsDerivedFrom(QualType Derived, QualType Base);
3739  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
3740
3741  // FIXME: I don't like this name.
3742  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
3743
3744  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
3745
3746  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3747                                    SourceLocation Loc, SourceRange Range,
3748                                    CXXCastPath *BasePath = 0,
3749                                    bool IgnoreAccess = false);
3750  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3751                                    unsigned InaccessibleBaseID,
3752                                    unsigned AmbigiousBaseConvID,
3753                                    SourceLocation Loc, SourceRange Range,
3754                                    DeclarationName Name,
3755                                    CXXCastPath *BasePath);
3756
3757  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
3758
3759  /// CheckOverridingFunctionReturnType - Checks whether the return types are
3760  /// covariant, according to C++ [class.virtual]p5.
3761  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3762                                         const CXXMethodDecl *Old);
3763
3764  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
3765  /// spec is a subset of base spec.
3766  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3767                                            const CXXMethodDecl *Old);
3768
3769  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
3770
3771  /// CheckOverrideControl - Check C++0x override control semantics.
3772  void CheckOverrideControl(const Decl *D);
3773
3774  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
3775  /// overrides a virtual member function marked 'final', according to
3776  /// C++0x [class.virtual]p3.
3777  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3778                                              const CXXMethodDecl *Old);
3779
3780
3781  //===--------------------------------------------------------------------===//
3782  // C++ Access Control
3783  //
3784
3785  enum AccessResult {
3786    AR_accessible,
3787    AR_inaccessible,
3788    AR_dependent,
3789    AR_delayed
3790  };
3791
3792  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
3793                                NamedDecl *PrevMemberDecl,
3794                                AccessSpecifier LexicalAS);
3795
3796  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
3797                                           DeclAccessPair FoundDecl);
3798  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
3799                                           DeclAccessPair FoundDecl);
3800  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
3801                                     SourceRange PlacementRange,
3802                                     CXXRecordDecl *NamingClass,
3803                                     DeclAccessPair FoundDecl,
3804                                     bool Diagnose = true);
3805  AccessResult CheckConstructorAccess(SourceLocation Loc,
3806                                      CXXConstructorDecl *D,
3807                                      const InitializedEntity &Entity,
3808                                      AccessSpecifier Access,
3809                                      bool IsCopyBindingRefToTemp = false);
3810  AccessResult CheckConstructorAccess(SourceLocation Loc,
3811                                      CXXConstructorDecl *D,
3812                                      AccessSpecifier Access,
3813                                      PartialDiagnostic PD);
3814  AccessResult CheckDestructorAccess(SourceLocation Loc,
3815                                     CXXDestructorDecl *Dtor,
3816                                     const PartialDiagnostic &PDiag);
3817  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
3818                                       NamedDecl *D,
3819                                       const PartialDiagnostic &PDiag);
3820  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
3821                                         Expr *ObjectExpr,
3822                                         Expr *ArgExpr,
3823                                         DeclAccessPair FoundDecl);
3824  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
3825                                          DeclAccessPair FoundDecl);
3826  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
3827                                    QualType Base, QualType Derived,
3828                                    const CXXBasePath &Path,
3829                                    unsigned DiagID,
3830                                    bool ForceCheck = false,
3831                                    bool ForceUnprivileged = false);
3832  void CheckLookupAccess(const LookupResult &R);
3833  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
3834
3835  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
3836                         const MultiLevelTemplateArgumentList &TemplateArgs);
3837  void PerformDependentDiagnostics(const DeclContext *Pattern,
3838                        const MultiLevelTemplateArgumentList &TemplateArgs);
3839
3840  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3841
3842  /// A flag to suppress access checking.
3843  bool SuppressAccessChecking;
3844
3845  /// \brief When true, access checking violations are treated as SFINAE
3846  /// failures rather than hard errors.
3847  bool AccessCheckingSFINAE;
3848
3849  void ActOnStartSuppressingAccessChecks();
3850  void ActOnStopSuppressingAccessChecks();
3851
3852  enum AbstractDiagSelID {
3853    AbstractNone = -1,
3854    AbstractReturnType,
3855    AbstractParamType,
3856    AbstractVariableType,
3857    AbstractFieldType,
3858    AbstractArrayType
3859  };
3860
3861  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
3862                              const PartialDiagnostic &PD);
3863  void DiagnoseAbstractType(const CXXRecordDecl *RD);
3864
3865  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
3866                              AbstractDiagSelID SelID = AbstractNone);
3867
3868  //===--------------------------------------------------------------------===//
3869  // C++ Overloaded Operators [C++ 13.5]
3870  //
3871
3872  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
3873
3874  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
3875
3876  //===--------------------------------------------------------------------===//
3877  // C++ Templates [C++ 14]
3878  //
3879  void FilterAcceptableTemplateNames(LookupResult &R);
3880  bool hasAnyAcceptableTemplateNames(LookupResult &R);
3881
3882  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
3883                          QualType ObjectType, bool EnteringContext,
3884                          bool &MemberOfUnknownSpecialization);
3885
3886  TemplateNameKind isTemplateName(Scope *S,
3887                                  CXXScopeSpec &SS,
3888                                  bool hasTemplateKeyword,
3889                                  UnqualifiedId &Name,
3890                                  ParsedType ObjectType,
3891                                  bool EnteringContext,
3892                                  TemplateTy &Template,
3893                                  bool &MemberOfUnknownSpecialization);
3894
3895  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
3896                                   SourceLocation IILoc,
3897                                   Scope *S,
3898                                   const CXXScopeSpec *SS,
3899                                   TemplateTy &SuggestedTemplate,
3900                                   TemplateNameKind &SuggestedKind);
3901
3902  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
3903  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
3904
3905  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
3906                           SourceLocation EllipsisLoc,
3907                           SourceLocation KeyLoc,
3908                           IdentifierInfo *ParamName,
3909                           SourceLocation ParamNameLoc,
3910                           unsigned Depth, unsigned Position,
3911                           SourceLocation EqualLoc,
3912                           ParsedType DefaultArg);
3913
3914  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
3915  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
3916                                      unsigned Depth,
3917                                      unsigned Position,
3918                                      SourceLocation EqualLoc,
3919                                      Expr *DefaultArg);
3920  Decl *ActOnTemplateTemplateParameter(Scope *S,
3921                                       SourceLocation TmpLoc,
3922                                       TemplateParameterList *Params,
3923                                       SourceLocation EllipsisLoc,
3924                                       IdentifierInfo *ParamName,
3925                                       SourceLocation ParamNameLoc,
3926                                       unsigned Depth,
3927                                       unsigned Position,
3928                                       SourceLocation EqualLoc,
3929                                       ParsedTemplateArgument DefaultArg);
3930
3931  TemplateParameterList *
3932  ActOnTemplateParameterList(unsigned Depth,
3933                             SourceLocation ExportLoc,
3934                             SourceLocation TemplateLoc,
3935                             SourceLocation LAngleLoc,
3936                             Decl **Params, unsigned NumParams,
3937                             SourceLocation RAngleLoc);
3938
3939  /// \brief The context in which we are checking a template parameter
3940  /// list.
3941  enum TemplateParamListContext {
3942    TPC_ClassTemplate,
3943    TPC_FunctionTemplate,
3944    TPC_ClassTemplateMember,
3945    TPC_FriendFunctionTemplate,
3946    TPC_FriendFunctionTemplateDefinition,
3947    TPC_TypeAliasTemplate
3948  };
3949
3950  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
3951                                  TemplateParameterList *OldParams,
3952                                  TemplateParamListContext TPC);
3953  TemplateParameterList *
3954  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
3955                                          SourceLocation DeclLoc,
3956                                          const CXXScopeSpec &SS,
3957                                          TemplateParameterList **ParamLists,
3958                                          unsigned NumParamLists,
3959                                          bool IsFriend,
3960                                          bool &IsExplicitSpecialization,
3961                                          bool &Invalid);
3962
3963  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
3964                                SourceLocation KWLoc, CXXScopeSpec &SS,
3965                                IdentifierInfo *Name, SourceLocation NameLoc,
3966                                AttributeList *Attr,
3967                                TemplateParameterList *TemplateParams,
3968                                AccessSpecifier AS,
3969                                SourceLocation ModulePrivateLoc,
3970                                unsigned NumOuterTemplateParamLists,
3971                            TemplateParameterList **OuterTemplateParamLists);
3972
3973  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
3974                                  TemplateArgumentListInfo &Out);
3975
3976  void NoteAllFoundTemplates(TemplateName Name);
3977
3978  QualType CheckTemplateIdType(TemplateName Template,
3979                               SourceLocation TemplateLoc,
3980                              TemplateArgumentListInfo &TemplateArgs);
3981
3982  TypeResult
3983  ActOnTemplateIdType(CXXScopeSpec &SS,
3984                      TemplateTy Template, SourceLocation TemplateLoc,
3985                      SourceLocation LAngleLoc,
3986                      ASTTemplateArgsPtr TemplateArgs,
3987                      SourceLocation RAngleLoc);
3988
3989  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
3990  /// such as \c class T::template apply<U>.
3991  ///
3992  /// \param TUK
3993  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
3994                                    TypeSpecifierType TagSpec,
3995                                    SourceLocation TagLoc,
3996                                    CXXScopeSpec &SS,
3997                                    TemplateTy TemplateD,
3998                                    SourceLocation TemplateLoc,
3999                                    SourceLocation LAngleLoc,
4000                                    ASTTemplateArgsPtr TemplateArgsIn,
4001                                    SourceLocation RAngleLoc);
4002
4003
4004  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
4005                                 LookupResult &R,
4006                                 bool RequiresADL,
4007                               const TemplateArgumentListInfo &TemplateArgs);
4008  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4009                               const DeclarationNameInfo &NameInfo,
4010                               const TemplateArgumentListInfo &TemplateArgs);
4011
4012  TemplateNameKind ActOnDependentTemplateName(Scope *S,
4013                                              SourceLocation TemplateKWLoc,
4014                                              CXXScopeSpec &SS,
4015                                              UnqualifiedId &Name,
4016                                              ParsedType ObjectType,
4017                                              bool EnteringContext,
4018                                              TemplateTy &Template);
4019
4020  DeclResult
4021  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
4022                                   SourceLocation KWLoc,
4023                                   SourceLocation ModulePrivateLoc,
4024                                   CXXScopeSpec &SS,
4025                                   TemplateTy Template,
4026                                   SourceLocation TemplateNameLoc,
4027                                   SourceLocation LAngleLoc,
4028                                   ASTTemplateArgsPtr TemplateArgs,
4029                                   SourceLocation RAngleLoc,
4030                                   AttributeList *Attr,
4031                                 MultiTemplateParamsArg TemplateParameterLists);
4032
4033  Decl *ActOnTemplateDeclarator(Scope *S,
4034                                MultiTemplateParamsArg TemplateParameterLists,
4035                                Declarator &D);
4036
4037  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4038                                  MultiTemplateParamsArg TemplateParameterLists,
4039                                        Declarator &D);
4040
4041  bool
4042  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4043                                         TemplateSpecializationKind NewTSK,
4044                                         NamedDecl *PrevDecl,
4045                                         TemplateSpecializationKind PrevTSK,
4046                                         SourceLocation PrevPtOfInstantiation,
4047                                         bool &SuppressNew);
4048
4049  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4050                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
4051                                                    LookupResult &Previous);
4052
4053  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4054                         TemplateArgumentListInfo *ExplicitTemplateArgs,
4055                                           LookupResult &Previous);
4056  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
4057
4058  DeclResult
4059  ActOnExplicitInstantiation(Scope *S,
4060                             SourceLocation ExternLoc,
4061                             SourceLocation TemplateLoc,
4062                             unsigned TagSpec,
4063                             SourceLocation KWLoc,
4064                             const CXXScopeSpec &SS,
4065                             TemplateTy Template,
4066                             SourceLocation TemplateNameLoc,
4067                             SourceLocation LAngleLoc,
4068                             ASTTemplateArgsPtr TemplateArgs,
4069                             SourceLocation RAngleLoc,
4070                             AttributeList *Attr);
4071
4072  DeclResult
4073  ActOnExplicitInstantiation(Scope *S,
4074                             SourceLocation ExternLoc,
4075                             SourceLocation TemplateLoc,
4076                             unsigned TagSpec,
4077                             SourceLocation KWLoc,
4078                             CXXScopeSpec &SS,
4079                             IdentifierInfo *Name,
4080                             SourceLocation NameLoc,
4081                             AttributeList *Attr);
4082
4083  DeclResult ActOnExplicitInstantiation(Scope *S,
4084                                        SourceLocation ExternLoc,
4085                                        SourceLocation TemplateLoc,
4086                                        Declarator &D);
4087
4088  TemplateArgumentLoc
4089  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4090                                          SourceLocation TemplateLoc,
4091                                          SourceLocation RAngleLoc,
4092                                          Decl *Param,
4093                          SmallVectorImpl<TemplateArgument> &Converted);
4094
4095  /// \brief Specifies the context in which a particular template
4096  /// argument is being checked.
4097  enum CheckTemplateArgumentKind {
4098    /// \brief The template argument was specified in the code or was
4099    /// instantiated with some deduced template arguments.
4100    CTAK_Specified,
4101
4102    /// \brief The template argument was deduced via template argument
4103    /// deduction.
4104    CTAK_Deduced,
4105
4106    /// \brief The template argument was deduced from an array bound
4107    /// via template argument deduction.
4108    CTAK_DeducedFromArrayBound
4109  };
4110
4111  bool CheckTemplateArgument(NamedDecl *Param,
4112                             const TemplateArgumentLoc &Arg,
4113                             NamedDecl *Template,
4114                             SourceLocation TemplateLoc,
4115                             SourceLocation RAngleLoc,
4116                             unsigned ArgumentPackIndex,
4117                           SmallVectorImpl<TemplateArgument> &Converted,
4118                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
4119
4120  /// \brief Check that the given template arguments can be be provided to
4121  /// the given template, converting the arguments along the way.
4122  ///
4123  /// \param Template The template to which the template arguments are being
4124  /// provided.
4125  ///
4126  /// \param TemplateLoc The location of the template name in the source.
4127  ///
4128  /// \param TemplateArgs The list of template arguments. If the template is
4129  /// a template template parameter, this function may extend the set of
4130  /// template arguments to also include substituted, defaulted template
4131  /// arguments.
4132  ///
4133  /// \param PartialTemplateArgs True if the list of template arguments is
4134  /// intentionally partial, e.g., because we're checking just the initial
4135  /// set of template arguments.
4136  ///
4137  /// \param Converted Will receive the converted, canonicalized template
4138  /// arguments.
4139  ///
4140  /// \returns True if an error occurred, false otherwise.
4141  bool CheckTemplateArgumentList(TemplateDecl *Template,
4142                                 SourceLocation TemplateLoc,
4143                                 TemplateArgumentListInfo &TemplateArgs,
4144                                 bool PartialTemplateArgs,
4145                           SmallVectorImpl<TemplateArgument> &Converted);
4146
4147  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4148                                 const TemplateArgumentLoc &Arg,
4149                           SmallVectorImpl<TemplateArgument> &Converted);
4150
4151  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
4152                             TypeSourceInfo *Arg);
4153  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
4154                                            TemplateArgument &Converted);
4155  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4156                                   QualType InstantiatedParamType, Expr *Arg,
4157                                   TemplateArgument &Converted,
4158                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
4159  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
4160                             const TemplateArgumentLoc &Arg);
4161
4162  ExprResult
4163  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4164                                          QualType ParamType,
4165                                          SourceLocation Loc);
4166  ExprResult
4167  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4168                                              SourceLocation Loc);
4169
4170  /// \brief Enumeration describing how template parameter lists are compared
4171  /// for equality.
4172  enum TemplateParameterListEqualKind {
4173    /// \brief We are matching the template parameter lists of two templates
4174    /// that might be redeclarations.
4175    ///
4176    /// \code
4177    /// template<typename T> struct X;
4178    /// template<typename T> struct X;
4179    /// \endcode
4180    TPL_TemplateMatch,
4181
4182    /// \brief We are matching the template parameter lists of two template
4183    /// template parameters as part of matching the template parameter lists
4184    /// of two templates that might be redeclarations.
4185    ///
4186    /// \code
4187    /// template<template<int I> class TT> struct X;
4188    /// template<template<int Value> class Other> struct X;
4189    /// \endcode
4190    TPL_TemplateTemplateParmMatch,
4191
4192    /// \brief We are matching the template parameter lists of a template
4193    /// template argument against the template parameter lists of a template
4194    /// template parameter.
4195    ///
4196    /// \code
4197    /// template<template<int Value> class Metafun> struct X;
4198    /// template<int Value> struct integer_c;
4199    /// X<integer_c> xic;
4200    /// \endcode
4201    TPL_TemplateTemplateArgumentMatch
4202  };
4203
4204  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
4205                                      TemplateParameterList *Old,
4206                                      bool Complain,
4207                                      TemplateParameterListEqualKind Kind,
4208                                      SourceLocation TemplateArgLoc
4209                                        = SourceLocation());
4210
4211  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
4212
4213  /// \brief Called when the parser has parsed a C++ typename
4214  /// specifier, e.g., "typename T::type".
4215  ///
4216  /// \param S The scope in which this typename type occurs.
4217  /// \param TypenameLoc the location of the 'typename' keyword
4218  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4219  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
4220  /// \param IdLoc the location of the identifier.
4221  TypeResult
4222  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4223                    const CXXScopeSpec &SS, const IdentifierInfo &II,
4224                    SourceLocation IdLoc);
4225
4226  /// \brief Called when the parser has parsed a C++ typename
4227  /// specifier that ends in a template-id, e.g.,
4228  /// "typename MetaFun::template apply<T1, T2>".
4229  ///
4230  /// \param S The scope in which this typename type occurs.
4231  /// \param TypenameLoc the location of the 'typename' keyword
4232  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4233  /// \param TemplateLoc the location of the 'template' keyword, if any.
4234  /// \param TemplateName The template name.
4235  /// \param TemplateNameLoc The location of the template name.
4236  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4237  /// \param TemplateArgs The template arguments.
4238  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4239  TypeResult
4240  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4241                    const CXXScopeSpec &SS,
4242                    SourceLocation TemplateLoc,
4243                    TemplateTy Template,
4244                    SourceLocation TemplateNameLoc,
4245                    SourceLocation LAngleLoc,
4246                    ASTTemplateArgsPtr TemplateArgs,
4247                    SourceLocation RAngleLoc);
4248
4249  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
4250                             SourceLocation KeywordLoc,
4251                             NestedNameSpecifierLoc QualifierLoc,
4252                             const IdentifierInfo &II,
4253                             SourceLocation IILoc);
4254
4255  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
4256                                                    SourceLocation Loc,
4257                                                    DeclarationName Name);
4258  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
4259
4260  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
4261  bool RebuildTemplateParamsInCurrentInstantiation(
4262                                                TemplateParameterList *Params);
4263
4264  std::string
4265  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4266                                  const TemplateArgumentList &Args);
4267
4268  std::string
4269  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4270                                  const TemplateArgument *Args,
4271                                  unsigned NumArgs);
4272
4273  //===--------------------------------------------------------------------===//
4274  // C++ Variadic Templates (C++0x [temp.variadic])
4275  //===--------------------------------------------------------------------===//
4276
4277  /// \brief The context in which an unexpanded parameter pack is
4278  /// being diagnosed.
4279  ///
4280  /// Note that the values of this enumeration line up with the first
4281  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
4282  enum UnexpandedParameterPackContext {
4283    /// \brief An arbitrary expression.
4284    UPPC_Expression = 0,
4285
4286    /// \brief The base type of a class type.
4287    UPPC_BaseType,
4288
4289    /// \brief The type of an arbitrary declaration.
4290    UPPC_DeclarationType,
4291
4292    /// \brief The type of a data member.
4293    UPPC_DataMemberType,
4294
4295    /// \brief The size of a bit-field.
4296    UPPC_BitFieldWidth,
4297
4298    /// \brief The expression in a static assertion.
4299    UPPC_StaticAssertExpression,
4300
4301    /// \brief The fixed underlying type of an enumeration.
4302    UPPC_FixedUnderlyingType,
4303
4304    /// \brief The enumerator value.
4305    UPPC_EnumeratorValue,
4306
4307    /// \brief A using declaration.
4308    UPPC_UsingDeclaration,
4309
4310    /// \brief A friend declaration.
4311    UPPC_FriendDeclaration,
4312
4313    /// \brief A declaration qualifier.
4314    UPPC_DeclarationQualifier,
4315
4316    /// \brief An initializer.
4317    UPPC_Initializer,
4318
4319    /// \brief A default argument.
4320    UPPC_DefaultArgument,
4321
4322    /// \brief The type of a non-type template parameter.
4323    UPPC_NonTypeTemplateParameterType,
4324
4325    /// \brief The type of an exception.
4326    UPPC_ExceptionType,
4327
4328    /// \brief Partial specialization.
4329    UPPC_PartialSpecialization,
4330
4331    /// \brief Microsoft __if_exists.
4332    UPPC_IfExists,
4333
4334    /// \brief Microsoft __if_not_exists.
4335    UPPC_IfNotExists
4336};
4337
4338  /// \brief Diagnose unexpanded parameter packs.
4339  ///
4340  /// \param Loc The location at which we should emit the diagnostic.
4341  ///
4342  /// \param UPPC The context in which we are diagnosing unexpanded
4343  /// parameter packs.
4344  ///
4345  /// \param Unexpanded the set of unexpanded parameter packs.
4346  void DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
4347                                        UnexpandedParameterPackContext UPPC,
4348                    const SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4349
4350  /// \brief If the given type contains an unexpanded parameter pack,
4351  /// diagnose the error.
4352  ///
4353  /// \param Loc The source location where a diagnostc should be emitted.
4354  ///
4355  /// \param T The type that is being checked for unexpanded parameter
4356  /// packs.
4357  ///
4358  /// \returns true if an error occurred, false otherwise.
4359  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
4360                                       UnexpandedParameterPackContext UPPC);
4361
4362  /// \brief If the given expression contains an unexpanded parameter
4363  /// pack, diagnose the error.
4364  ///
4365  /// \param E The expression that is being checked for unexpanded
4366  /// parameter packs.
4367  ///
4368  /// \returns true if an error occurred, false otherwise.
4369  bool DiagnoseUnexpandedParameterPack(Expr *E,
4370                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
4371
4372  /// \brief If the given nested-name-specifier contains an unexpanded
4373  /// parameter pack, diagnose the error.
4374  ///
4375  /// \param SS The nested-name-specifier that is being checked for
4376  /// unexpanded parameter packs.
4377  ///
4378  /// \returns true if an error occurred, false otherwise.
4379  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
4380                                       UnexpandedParameterPackContext UPPC);
4381
4382  /// \brief If the given name contains an unexpanded parameter pack,
4383  /// diagnose the error.
4384  ///
4385  /// \param NameInfo The name (with source location information) that
4386  /// is being checked for unexpanded parameter packs.
4387  ///
4388  /// \returns true if an error occurred, false otherwise.
4389  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
4390                                       UnexpandedParameterPackContext UPPC);
4391
4392  /// \brief If the given template name contains an unexpanded parameter pack,
4393  /// diagnose the error.
4394  ///
4395  /// \param Loc The location of the template name.
4396  ///
4397  /// \param Template The template name that is being checked for unexpanded
4398  /// parameter packs.
4399  ///
4400  /// \returns true if an error occurred, false otherwise.
4401  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
4402                                       TemplateName Template,
4403                                       UnexpandedParameterPackContext UPPC);
4404
4405  /// \brief If the given template argument contains an unexpanded parameter
4406  /// pack, diagnose the error.
4407  ///
4408  /// \param Arg The template argument that is being checked for unexpanded
4409  /// parameter packs.
4410  ///
4411  /// \returns true if an error occurred, false otherwise.
4412  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
4413                                       UnexpandedParameterPackContext UPPC);
4414
4415  /// \brief Collect the set of unexpanded parameter packs within the given
4416  /// template argument.
4417  ///
4418  /// \param Arg The template argument that will be traversed to find
4419  /// unexpanded parameter packs.
4420  void collectUnexpandedParameterPacks(TemplateArgument Arg,
4421                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4422
4423  /// \brief Collect the set of unexpanded parameter packs within the given
4424  /// template argument.
4425  ///
4426  /// \param Arg The template argument that will be traversed to find
4427  /// unexpanded parameter packs.
4428  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
4429                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4430
4431  /// \brief Collect the set of unexpanded parameter packs within the given
4432  /// type.
4433  ///
4434  /// \param T The type that will be traversed to find
4435  /// unexpanded parameter packs.
4436  void collectUnexpandedParameterPacks(QualType T,
4437                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4438
4439  /// \brief Collect the set of unexpanded parameter packs within the given
4440  /// type.
4441  ///
4442  /// \param TL The type that will be traversed to find
4443  /// unexpanded parameter packs.
4444  void collectUnexpandedParameterPacks(TypeLoc TL,
4445                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4446
4447  /// \brief Collect the set of unexpanded parameter packs within the given
4448  /// nested-name-specifier.
4449  ///
4450  /// \param SS The nested-name-specifier that will be traversed to find
4451  /// unexpanded parameter packs.
4452  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
4453                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4454
4455  /// \brief Collect the set of unexpanded parameter packs within the given
4456  /// name.
4457  ///
4458  /// \param NameInfo The name that will be traversed to find
4459  /// unexpanded parameter packs.
4460  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
4461                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4462
4463  /// \brief Invoked when parsing a template argument followed by an
4464  /// ellipsis, which creates a pack expansion.
4465  ///
4466  /// \param Arg The template argument preceding the ellipsis, which
4467  /// may already be invalid.
4468  ///
4469  /// \param EllipsisLoc The location of the ellipsis.
4470  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
4471                                            SourceLocation EllipsisLoc);
4472
4473  /// \brief Invoked when parsing a type followed by an ellipsis, which
4474  /// creates a pack expansion.
4475  ///
4476  /// \param Type The type preceding the ellipsis, which will become
4477  /// the pattern of the pack expansion.
4478  ///
4479  /// \param EllipsisLoc The location of the ellipsis.
4480  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
4481
4482  /// \brief Construct a pack expansion type from the pattern of the pack
4483  /// expansion.
4484  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
4485                                     SourceLocation EllipsisLoc,
4486                                     llvm::Optional<unsigned> NumExpansions);
4487
4488  /// \brief Construct a pack expansion type from the pattern of the pack
4489  /// expansion.
4490  QualType CheckPackExpansion(QualType Pattern,
4491                              SourceRange PatternRange,
4492                              SourceLocation EllipsisLoc,
4493                              llvm::Optional<unsigned> NumExpansions);
4494
4495  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4496  /// creates a pack expansion.
4497  ///
4498  /// \param Pattern The expression preceding the ellipsis, which will become
4499  /// the pattern of the pack expansion.
4500  ///
4501  /// \param EllipsisLoc The location of the ellipsis.
4502  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
4503
4504  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4505  /// creates a pack expansion.
4506  ///
4507  /// \param Pattern The expression preceding the ellipsis, which will become
4508  /// the pattern of the pack expansion.
4509  ///
4510  /// \param EllipsisLoc The location of the ellipsis.
4511  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
4512                                llvm::Optional<unsigned> NumExpansions);
4513
4514  /// \brief Determine whether we could expand a pack expansion with the
4515  /// given set of parameter packs into separate arguments by repeatedly
4516  /// transforming the pattern.
4517  ///
4518  /// \param EllipsisLoc The location of the ellipsis that identifies the
4519  /// pack expansion.
4520  ///
4521  /// \param PatternRange The source range that covers the entire pattern of
4522  /// the pack expansion.
4523  ///
4524  /// \param Unexpanded The set of unexpanded parameter packs within the
4525  /// pattern.
4526  ///
4527  /// \param NumUnexpanded The number of unexpanded parameter packs in
4528  /// \p Unexpanded.
4529  ///
4530  /// \param ShouldExpand Will be set to \c true if the transformer should
4531  /// expand the corresponding pack expansions into separate arguments. When
4532  /// set, \c NumExpansions must also be set.
4533  ///
4534  /// \param RetainExpansion Whether the caller should add an unexpanded
4535  /// pack expansion after all of the expanded arguments. This is used
4536  /// when extending explicitly-specified template argument packs per
4537  /// C++0x [temp.arg.explicit]p9.
4538  ///
4539  /// \param NumExpansions The number of separate arguments that will be in
4540  /// the expanded form of the corresponding pack expansion. This is both an
4541  /// input and an output parameter, which can be set by the caller if the
4542  /// number of expansions is known a priori (e.g., due to a prior substitution)
4543  /// and will be set by the callee when the number of expansions is known.
4544  /// The callee must set this value when \c ShouldExpand is \c true; it may
4545  /// set this value in other cases.
4546  ///
4547  /// \returns true if an error occurred (e.g., because the parameter packs
4548  /// are to be instantiated with arguments of different lengths), false
4549  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
4550  /// must be set.
4551  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
4552                                       SourceRange PatternRange,
4553                             llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
4554                             const MultiLevelTemplateArgumentList &TemplateArgs,
4555                                       bool &ShouldExpand,
4556                                       bool &RetainExpansion,
4557                                       llvm::Optional<unsigned> &NumExpansions);
4558
4559  /// \brief Determine the number of arguments in the given pack expansion
4560  /// type.
4561  ///
4562  /// This routine already assumes that the pack expansion type can be
4563  /// expanded and that the number of arguments in the expansion is
4564  /// consistent across all of the unexpanded parameter packs in its pattern.
4565  unsigned getNumArgumentsInExpansion(QualType T,
4566                            const MultiLevelTemplateArgumentList &TemplateArgs);
4567
4568  /// \brief Determine whether the given declarator contains any unexpanded
4569  /// parameter packs.
4570  ///
4571  /// This routine is used by the parser to disambiguate function declarators
4572  /// with an ellipsis prior to the ')', e.g.,
4573  ///
4574  /// \code
4575  ///   void f(T...);
4576  /// \endcode
4577  ///
4578  /// To determine whether we have an (unnamed) function parameter pack or
4579  /// a variadic function.
4580  ///
4581  /// \returns true if the declarator contains any unexpanded parameter packs,
4582  /// false otherwise.
4583  bool containsUnexpandedParameterPacks(Declarator &D);
4584
4585  //===--------------------------------------------------------------------===//
4586  // C++ Template Argument Deduction (C++ [temp.deduct])
4587  //===--------------------------------------------------------------------===//
4588
4589  /// \brief Describes the result of template argument deduction.
4590  ///
4591  /// The TemplateDeductionResult enumeration describes the result of
4592  /// template argument deduction, as returned from
4593  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
4594  /// structure provides additional information about the results of
4595  /// template argument deduction, e.g., the deduced template argument
4596  /// list (if successful) or the specific template parameters or
4597  /// deduced arguments that were involved in the failure.
4598  enum TemplateDeductionResult {
4599    /// \brief Template argument deduction was successful.
4600    TDK_Success = 0,
4601    /// \brief Template argument deduction exceeded the maximum template
4602    /// instantiation depth (which has already been diagnosed).
4603    TDK_InstantiationDepth,
4604    /// \brief Template argument deduction did not deduce a value
4605    /// for every template parameter.
4606    TDK_Incomplete,
4607    /// \brief Template argument deduction produced inconsistent
4608    /// deduced values for the given template parameter.
4609    TDK_Inconsistent,
4610    /// \brief Template argument deduction failed due to inconsistent
4611    /// cv-qualifiers on a template parameter type that would
4612    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
4613    /// but were given a non-const "X".
4614    TDK_Underqualified,
4615    /// \brief Substitution of the deduced template argument values
4616    /// resulted in an error.
4617    TDK_SubstitutionFailure,
4618    /// \brief Substitution of the deduced template argument values
4619    /// into a non-deduced context produced a type or value that
4620    /// produces a type that does not match the original template
4621    /// arguments provided.
4622    TDK_NonDeducedMismatch,
4623    /// \brief When performing template argument deduction for a function
4624    /// template, there were too many call arguments.
4625    TDK_TooManyArguments,
4626    /// \brief When performing template argument deduction for a function
4627    /// template, there were too few call arguments.
4628    TDK_TooFewArguments,
4629    /// \brief The explicitly-specified template arguments were not valid
4630    /// template arguments for the given template.
4631    TDK_InvalidExplicitArguments,
4632    /// \brief The arguments included an overloaded function name that could
4633    /// not be resolved to a suitable function.
4634    TDK_FailedOverloadResolution
4635  };
4636
4637  TemplateDeductionResult
4638  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
4639                          const TemplateArgumentList &TemplateArgs,
4640                          sema::TemplateDeductionInfo &Info);
4641
4642  TemplateDeductionResult
4643  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4644                              TemplateArgumentListInfo &ExplicitTemplateArgs,
4645                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4646                                 SmallVectorImpl<QualType> &ParamTypes,
4647                                      QualType *FunctionType,
4648                                      sema::TemplateDeductionInfo &Info);
4649
4650  /// brief A function argument from which we performed template argument
4651  // deduction for a call.
4652  struct OriginalCallArg {
4653    OriginalCallArg(QualType OriginalParamType,
4654                    unsigned ArgIdx,
4655                    QualType OriginalArgType)
4656      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
4657        OriginalArgType(OriginalArgType) { }
4658
4659    QualType OriginalParamType;
4660    unsigned ArgIdx;
4661    QualType OriginalArgType;
4662  };
4663
4664  TemplateDeductionResult
4665  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
4666                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4667                                  unsigned NumExplicitlySpecified,
4668                                  FunctionDecl *&Specialization,
4669                                  sema::TemplateDeductionInfo &Info,
4670           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
4671
4672  TemplateDeductionResult
4673  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4674                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4675                          Expr **Args, unsigned NumArgs,
4676                          FunctionDecl *&Specialization,
4677                          sema::TemplateDeductionInfo &Info);
4678
4679  TemplateDeductionResult
4680  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4681                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4682                          QualType ArgFunctionType,
4683                          FunctionDecl *&Specialization,
4684                          sema::TemplateDeductionInfo &Info);
4685
4686  TemplateDeductionResult
4687  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4688                          QualType ToType,
4689                          CXXConversionDecl *&Specialization,
4690                          sema::TemplateDeductionInfo &Info);
4691
4692  TemplateDeductionResult
4693  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4694                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4695                          FunctionDecl *&Specialization,
4696                          sema::TemplateDeductionInfo &Info);
4697
4698  bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
4699                      TypeSourceInfo *&Result);
4700  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
4701
4702  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4703                                                   FunctionTemplateDecl *FT2,
4704                                                   SourceLocation Loc,
4705                                           TemplatePartialOrderingContext TPOC,
4706                                                   unsigned NumCallArguments);
4707  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
4708                                           UnresolvedSetIterator SEnd,
4709                                           TemplatePartialOrderingContext TPOC,
4710                                           unsigned NumCallArguments,
4711                                           SourceLocation Loc,
4712                                           const PartialDiagnostic &NoneDiag,
4713                                           const PartialDiagnostic &AmbigDiag,
4714                                        const PartialDiagnostic &CandidateDiag,
4715                                        bool Complain = true,
4716                                        QualType TargetType = QualType());
4717
4718  ClassTemplatePartialSpecializationDecl *
4719  getMoreSpecializedPartialSpecialization(
4720                                  ClassTemplatePartialSpecializationDecl *PS1,
4721                                  ClassTemplatePartialSpecializationDecl *PS2,
4722                                  SourceLocation Loc);
4723
4724  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4725                                  bool OnlyDeduced,
4726                                  unsigned Depth,
4727                                  SmallVectorImpl<bool> &Used);
4728  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4729                                     SmallVectorImpl<bool> &Deduced) {
4730    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
4731  }
4732  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
4733                                         FunctionTemplateDecl *FunctionTemplate,
4734                                         SmallVectorImpl<bool> &Deduced);
4735
4736  //===--------------------------------------------------------------------===//
4737  // C++ Template Instantiation
4738  //
4739
4740  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
4741                                     const TemplateArgumentList *Innermost = 0,
4742                                                bool RelativeToPrimary = false,
4743                                               const FunctionDecl *Pattern = 0);
4744
4745  /// \brief A template instantiation that is currently in progress.
4746  struct ActiveTemplateInstantiation {
4747    /// \brief The kind of template instantiation we are performing
4748    enum InstantiationKind {
4749      /// We are instantiating a template declaration. The entity is
4750      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
4751      TemplateInstantiation,
4752
4753      /// We are instantiating a default argument for a template
4754      /// parameter. The Entity is the template, and
4755      /// TemplateArgs/NumTemplateArguments provides the template
4756      /// arguments as specified.
4757      /// FIXME: Use a TemplateArgumentList
4758      DefaultTemplateArgumentInstantiation,
4759
4760      /// We are instantiating a default argument for a function.
4761      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
4762      /// provides the template arguments as specified.
4763      DefaultFunctionArgumentInstantiation,
4764
4765      /// We are substituting explicit template arguments provided for
4766      /// a function template. The entity is a FunctionTemplateDecl.
4767      ExplicitTemplateArgumentSubstitution,
4768
4769      /// We are substituting template argument determined as part of
4770      /// template argument deduction for either a class template
4771      /// partial specialization or a function template. The
4772      /// Entity is either a ClassTemplatePartialSpecializationDecl or
4773      /// a FunctionTemplateDecl.
4774      DeducedTemplateArgumentSubstitution,
4775
4776      /// We are substituting prior template arguments into a new
4777      /// template parameter. The template parameter itself is either a
4778      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
4779      PriorTemplateArgumentSubstitution,
4780
4781      /// We are checking the validity of a default template argument that
4782      /// has been used when naming a template-id.
4783      DefaultTemplateArgumentChecking
4784    } Kind;
4785
4786    /// \brief The point of instantiation within the source code.
4787    SourceLocation PointOfInstantiation;
4788
4789    /// \brief The template (or partial specialization) in which we are
4790    /// performing the instantiation, for substitutions of prior template
4791    /// arguments.
4792    NamedDecl *Template;
4793
4794    /// \brief The entity that is being instantiated.
4795    uintptr_t Entity;
4796
4797    /// \brief The list of template arguments we are substituting, if they
4798    /// are not part of the entity.
4799    const TemplateArgument *TemplateArgs;
4800
4801    /// \brief The number of template arguments in TemplateArgs.
4802    unsigned NumTemplateArgs;
4803
4804    /// \brief The template deduction info object associated with the
4805    /// substitution or checking of explicit or deduced template arguments.
4806    sema::TemplateDeductionInfo *DeductionInfo;
4807
4808    /// \brief The source range that covers the construct that cause
4809    /// the instantiation, e.g., the template-id that causes a class
4810    /// template instantiation.
4811    SourceRange InstantiationRange;
4812
4813    ActiveTemplateInstantiation()
4814      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
4815        NumTemplateArgs(0), DeductionInfo(0) {}
4816
4817    /// \brief Determines whether this template is an actual instantiation
4818    /// that should be counted toward the maximum instantiation depth.
4819    bool isInstantiationRecord() const;
4820
4821    friend bool operator==(const ActiveTemplateInstantiation &X,
4822                           const ActiveTemplateInstantiation &Y) {
4823      if (X.Kind != Y.Kind)
4824        return false;
4825
4826      if (X.Entity != Y.Entity)
4827        return false;
4828
4829      switch (X.Kind) {
4830      case TemplateInstantiation:
4831        return true;
4832
4833      case PriorTemplateArgumentSubstitution:
4834      case DefaultTemplateArgumentChecking:
4835        if (X.Template != Y.Template)
4836          return false;
4837
4838        // Fall through
4839
4840      case DefaultTemplateArgumentInstantiation:
4841      case ExplicitTemplateArgumentSubstitution:
4842      case DeducedTemplateArgumentSubstitution:
4843      case DefaultFunctionArgumentInstantiation:
4844        return X.TemplateArgs == Y.TemplateArgs;
4845
4846      }
4847
4848      llvm_unreachable("Invalid InstantiationKind!");
4849    }
4850
4851    friend bool operator!=(const ActiveTemplateInstantiation &X,
4852                           const ActiveTemplateInstantiation &Y) {
4853      return !(X == Y);
4854    }
4855  };
4856
4857  /// \brief List of active template instantiations.
4858  ///
4859  /// This vector is treated as a stack. As one template instantiation
4860  /// requires another template instantiation, additional
4861  /// instantiations are pushed onto the stack up to a
4862  /// user-configurable limit LangOptions::InstantiationDepth.
4863  SmallVector<ActiveTemplateInstantiation, 16>
4864    ActiveTemplateInstantiations;
4865
4866  /// \brief Whether we are in a SFINAE context that is not associated with
4867  /// template instantiation.
4868  ///
4869  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
4870  /// of a template instantiation or template argument deduction.
4871  bool InNonInstantiationSFINAEContext;
4872
4873  /// \brief The number of ActiveTemplateInstantiation entries in
4874  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
4875  /// therefore, should not be counted as part of the instantiation depth.
4876  unsigned NonInstantiationEntries;
4877
4878  /// \brief The last template from which a template instantiation
4879  /// error or warning was produced.
4880  ///
4881  /// This value is used to suppress printing of redundant template
4882  /// instantiation backtraces when there are multiple errors in the
4883  /// same instantiation. FIXME: Does this belong in Sema? It's tough
4884  /// to implement it anywhere else.
4885  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
4886
4887  /// \brief The current index into pack expansion arguments that will be
4888  /// used for substitution of parameter packs.
4889  ///
4890  /// The pack expansion index will be -1 to indicate that parameter packs
4891  /// should be instantiated as themselves. Otherwise, the index specifies
4892  /// which argument within the parameter pack will be used for substitution.
4893  int ArgumentPackSubstitutionIndex;
4894
4895  /// \brief RAII object used to change the argument pack substitution index
4896  /// within a \c Sema object.
4897  ///
4898  /// See \c ArgumentPackSubstitutionIndex for more information.
4899  class ArgumentPackSubstitutionIndexRAII {
4900    Sema &Self;
4901    int OldSubstitutionIndex;
4902
4903  public:
4904    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
4905      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
4906      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
4907    }
4908
4909    ~ArgumentPackSubstitutionIndexRAII() {
4910      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
4911    }
4912  };
4913
4914  friend class ArgumentPackSubstitutionRAII;
4915
4916  /// \brief The stack of calls expression undergoing template instantiation.
4917  ///
4918  /// The top of this stack is used by a fixit instantiating unresolved
4919  /// function calls to fix the AST to match the textual change it prints.
4920  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
4921
4922  /// \brief For each declaration that involved template argument deduction, the
4923  /// set of diagnostics that were suppressed during that template argument
4924  /// deduction.
4925  ///
4926  /// FIXME: Serialize this structure to the AST file.
4927  llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
4928    SuppressedDiagnostics;
4929
4930  /// \brief A stack object to be created when performing template
4931  /// instantiation.
4932  ///
4933  /// Construction of an object of type \c InstantiatingTemplate
4934  /// pushes the current instantiation onto the stack of active
4935  /// instantiations. If the size of this stack exceeds the maximum
4936  /// number of recursive template instantiations, construction
4937  /// produces an error and evaluates true.
4938  ///
4939  /// Destruction of this object will pop the named instantiation off
4940  /// the stack.
4941  struct InstantiatingTemplate {
4942    /// \brief Note that we are instantiating a class template,
4943    /// function template, or a member thereof.
4944    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4945                          Decl *Entity,
4946                          SourceRange InstantiationRange = SourceRange());
4947
4948    /// \brief Note that we are instantiating a default argument in a
4949    /// template-id.
4950    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4951                          TemplateDecl *Template,
4952                          const TemplateArgument *TemplateArgs,
4953                          unsigned NumTemplateArgs,
4954                          SourceRange InstantiationRange = SourceRange());
4955
4956    /// \brief Note that we are instantiating a default argument in a
4957    /// template-id.
4958    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4959                          FunctionTemplateDecl *FunctionTemplate,
4960                          const TemplateArgument *TemplateArgs,
4961                          unsigned NumTemplateArgs,
4962                          ActiveTemplateInstantiation::InstantiationKind Kind,
4963                          sema::TemplateDeductionInfo &DeductionInfo,
4964                          SourceRange InstantiationRange = SourceRange());
4965
4966    /// \brief Note that we are instantiating as part of template
4967    /// argument deduction for a class template partial
4968    /// specialization.
4969    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4970                          ClassTemplatePartialSpecializationDecl *PartialSpec,
4971                          const TemplateArgument *TemplateArgs,
4972                          unsigned NumTemplateArgs,
4973                          sema::TemplateDeductionInfo &DeductionInfo,
4974                          SourceRange InstantiationRange = SourceRange());
4975
4976    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4977                          ParmVarDecl *Param,
4978                          const TemplateArgument *TemplateArgs,
4979                          unsigned NumTemplateArgs,
4980                          SourceRange InstantiationRange = SourceRange());
4981
4982    /// \brief Note that we are substituting prior template arguments into a
4983    /// non-type or template template parameter.
4984    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4985                          NamedDecl *Template,
4986                          NonTypeTemplateParmDecl *Param,
4987                          const TemplateArgument *TemplateArgs,
4988                          unsigned NumTemplateArgs,
4989                          SourceRange InstantiationRange);
4990
4991    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4992                          NamedDecl *Template,
4993                          TemplateTemplateParmDecl *Param,
4994                          const TemplateArgument *TemplateArgs,
4995                          unsigned NumTemplateArgs,
4996                          SourceRange InstantiationRange);
4997
4998    /// \brief Note that we are checking the default template argument
4999    /// against the template parameter for a given template-id.
5000    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5001                          TemplateDecl *Template,
5002                          NamedDecl *Param,
5003                          const TemplateArgument *TemplateArgs,
5004                          unsigned NumTemplateArgs,
5005                          SourceRange InstantiationRange);
5006
5007
5008    /// \brief Note that we have finished instantiating this template.
5009    void Clear();
5010
5011    ~InstantiatingTemplate() { Clear(); }
5012
5013    /// \brief Determines whether we have exceeded the maximum
5014    /// recursive template instantiations.
5015    operator bool() const { return Invalid; }
5016
5017  private:
5018    Sema &SemaRef;
5019    bool Invalid;
5020    bool SavedInNonInstantiationSFINAEContext;
5021    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
5022                                 SourceRange InstantiationRange);
5023
5024    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
5025
5026    InstantiatingTemplate&
5027    operator=(const InstantiatingTemplate&); // not implemented
5028  };
5029
5030  void PrintInstantiationStack();
5031
5032  /// \brief Determines whether we are currently in a context where
5033  /// template argument substitution failures are not considered
5034  /// errors.
5035  ///
5036  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
5037  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
5038  /// template-deduction context object, which can be used to capture
5039  /// diagnostics that will be suppressed.
5040  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
5041
5042  /// \brief RAII class used to determine whether SFINAE has
5043  /// trapped any errors that occur during template argument
5044  /// deduction.`
5045  class SFINAETrap {
5046    Sema &SemaRef;
5047    unsigned PrevSFINAEErrors;
5048    bool PrevInNonInstantiationSFINAEContext;
5049    bool PrevAccessCheckingSFINAE;
5050
5051  public:
5052    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
5053      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
5054        PrevInNonInstantiationSFINAEContext(
5055                                      SemaRef.InNonInstantiationSFINAEContext),
5056        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
5057    {
5058      if (!SemaRef.isSFINAEContext())
5059        SemaRef.InNonInstantiationSFINAEContext = true;
5060      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
5061    }
5062
5063    ~SFINAETrap() {
5064      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
5065      SemaRef.InNonInstantiationSFINAEContext
5066        = PrevInNonInstantiationSFINAEContext;
5067      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
5068    }
5069
5070    /// \brief Determine whether any SFINAE errors have been trapped.
5071    bool hasErrorOccurred() const {
5072      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
5073    }
5074  };
5075
5076  /// \brief The current instantiation scope used to store local
5077  /// variables.
5078  LocalInstantiationScope *CurrentInstantiationScope;
5079
5080  /// \brief The number of typos corrected by CorrectTypo.
5081  unsigned TyposCorrected;
5082
5083  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
5084    UnqualifiedTyposCorrectedMap;
5085
5086  /// \brief A cache containing the results of typo correction for unqualified
5087  /// name lookup.
5088  ///
5089  /// The string is the string that we corrected to (which may be empty, if
5090  /// there was no correction), while the boolean will be true when the
5091  /// string represents a keyword.
5092  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
5093
5094  /// \brief Worker object for performing CFG-based warnings.
5095  sema::AnalysisBasedWarnings AnalysisWarnings;
5096
5097  /// \brief An entity for which implicit template instantiation is required.
5098  ///
5099  /// The source location associated with the declaration is the first place in
5100  /// the source code where the declaration was "used". It is not necessarily
5101  /// the point of instantiation (which will be either before or after the
5102  /// namespace-scope declaration that triggered this implicit instantiation),
5103  /// However, it is the location that diagnostics should generally refer to,
5104  /// because users will need to know what code triggered the instantiation.
5105  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
5106
5107  /// \brief The queue of implicit template instantiations that are required
5108  /// but have not yet been performed.
5109  std::deque<PendingImplicitInstantiation> PendingInstantiations;
5110
5111  /// \brief The queue of implicit template instantiations that are required
5112  /// and must be performed within the current local scope.
5113  ///
5114  /// This queue is only used for member functions of local classes in
5115  /// templates, which must be instantiated in the same scope as their
5116  /// enclosing function, so that they can reference function-local
5117  /// types, static variables, enumerators, etc.
5118  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
5119
5120  void PerformPendingInstantiations(bool LocalOnly = false);
5121
5122  TypeSourceInfo *SubstType(TypeSourceInfo *T,
5123                            const MultiLevelTemplateArgumentList &TemplateArgs,
5124                            SourceLocation Loc, DeclarationName Entity);
5125
5126  QualType SubstType(QualType T,
5127                     const MultiLevelTemplateArgumentList &TemplateArgs,
5128                     SourceLocation Loc, DeclarationName Entity);
5129
5130  TypeSourceInfo *SubstType(TypeLoc TL,
5131                            const MultiLevelTemplateArgumentList &TemplateArgs,
5132                            SourceLocation Loc, DeclarationName Entity);
5133
5134  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
5135                            const MultiLevelTemplateArgumentList &TemplateArgs,
5136                                        SourceLocation Loc,
5137                                        DeclarationName Entity);
5138  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
5139                            const MultiLevelTemplateArgumentList &TemplateArgs,
5140                                int indexAdjustment,
5141                                llvm::Optional<unsigned> NumExpansions);
5142  bool SubstParmTypes(SourceLocation Loc,
5143                      ParmVarDecl **Params, unsigned NumParams,
5144                      const MultiLevelTemplateArgumentList &TemplateArgs,
5145                      SmallVectorImpl<QualType> &ParamTypes,
5146                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
5147  ExprResult SubstExpr(Expr *E,
5148                       const MultiLevelTemplateArgumentList &TemplateArgs);
5149
5150  /// \brief Substitute the given template arguments into a list of
5151  /// expressions, expanding pack expansions if required.
5152  ///
5153  /// \param Exprs The list of expressions to substitute into.
5154  ///
5155  /// \param NumExprs The number of expressions in \p Exprs.
5156  ///
5157  /// \param IsCall Whether this is some form of call, in which case
5158  /// default arguments will be dropped.
5159  ///
5160  /// \param TemplateArgs The set of template arguments to substitute.
5161  ///
5162  /// \param Outputs Will receive all of the substituted arguments.
5163  ///
5164  /// \returns true if an error occurred, false otherwise.
5165  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
5166                  const MultiLevelTemplateArgumentList &TemplateArgs,
5167                  SmallVectorImpl<Expr *> &Outputs);
5168
5169  StmtResult SubstStmt(Stmt *S,
5170                       const MultiLevelTemplateArgumentList &TemplateArgs);
5171
5172  Decl *SubstDecl(Decl *D, DeclContext *Owner,
5173                  const MultiLevelTemplateArgumentList &TemplateArgs);
5174
5175  bool
5176  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
5177                      CXXRecordDecl *Pattern,
5178                      const MultiLevelTemplateArgumentList &TemplateArgs);
5179
5180  bool
5181  InstantiateClass(SourceLocation PointOfInstantiation,
5182                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
5183                   const MultiLevelTemplateArgumentList &TemplateArgs,
5184                   TemplateSpecializationKind TSK,
5185                   bool Complain = true);
5186
5187  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
5188                        const Decl *Pattern, Decl *Inst);
5189
5190  bool
5191  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
5192                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
5193                           TemplateSpecializationKind TSK,
5194                           bool Complain = true);
5195
5196  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
5197                               CXXRecordDecl *Instantiation,
5198                            const MultiLevelTemplateArgumentList &TemplateArgs,
5199                               TemplateSpecializationKind TSK);
5200
5201  void InstantiateClassTemplateSpecializationMembers(
5202                                          SourceLocation PointOfInstantiation,
5203                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
5204                                                TemplateSpecializationKind TSK);
5205
5206  NestedNameSpecifierLoc
5207  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5208                           const MultiLevelTemplateArgumentList &TemplateArgs);
5209
5210  DeclarationNameInfo
5211  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5212                           const MultiLevelTemplateArgumentList &TemplateArgs);
5213  TemplateName
5214  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
5215                    SourceLocation Loc,
5216                    const MultiLevelTemplateArgumentList &TemplateArgs);
5217  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
5218             TemplateArgumentListInfo &Result,
5219             const MultiLevelTemplateArgumentList &TemplateArgs);
5220
5221  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
5222                                     FunctionDecl *Function,
5223                                     bool Recursive = false,
5224                                     bool DefinitionRequired = false);
5225  void InstantiateStaticDataMemberDefinition(
5226                                     SourceLocation PointOfInstantiation,
5227                                     VarDecl *Var,
5228                                     bool Recursive = false,
5229                                     bool DefinitionRequired = false);
5230
5231  void InstantiateMemInitializers(CXXConstructorDecl *New,
5232                                  const CXXConstructorDecl *Tmpl,
5233                            const MultiLevelTemplateArgumentList &TemplateArgs);
5234  bool InstantiateInitializer(Expr *Init,
5235                            const MultiLevelTemplateArgumentList &TemplateArgs,
5236                              SourceLocation &LParenLoc,
5237                              ASTOwningVector<Expr*> &NewArgs,
5238                              SourceLocation &RParenLoc);
5239
5240  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5241                          const MultiLevelTemplateArgumentList &TemplateArgs);
5242  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
5243                          const MultiLevelTemplateArgumentList &TemplateArgs);
5244
5245  // Objective-C declarations.
5246  enum ObjCContainerKind {
5247    OCK_None = -1,
5248    OCK_Interface = 0,
5249    OCK_Protocol,
5250    OCK_Category,
5251    OCK_ClassExtension,
5252    OCK_Implementation,
5253    OCK_CategoryImplementation
5254  };
5255  ObjCContainerKind getObjCContainerKind() const;
5256
5257  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
5258                                 IdentifierInfo *ClassName,
5259                                 SourceLocation ClassLoc,
5260                                 IdentifierInfo *SuperName,
5261                                 SourceLocation SuperLoc,
5262                                 Decl * const *ProtoRefs,
5263                                 unsigned NumProtoRefs,
5264                                 const SourceLocation *ProtoLocs,
5265                                 SourceLocation EndProtoLoc,
5266                                 AttributeList *AttrList);
5267
5268  Decl *ActOnCompatiblityAlias(
5269                    SourceLocation AtCompatibilityAliasLoc,
5270                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
5271                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
5272
5273  bool CheckForwardProtocolDeclarationForCircularDependency(
5274    IdentifierInfo *PName,
5275    SourceLocation &PLoc, SourceLocation PrevLoc,
5276    const ObjCList<ObjCProtocolDecl> &PList);
5277
5278  Decl *ActOnStartProtocolInterface(
5279                    SourceLocation AtProtoInterfaceLoc,
5280                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
5281                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
5282                    const SourceLocation *ProtoLocs,
5283                    SourceLocation EndProtoLoc,
5284                    AttributeList *AttrList);
5285
5286  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
5287                                    IdentifierInfo *ClassName,
5288                                    SourceLocation ClassLoc,
5289                                    IdentifierInfo *CategoryName,
5290                                    SourceLocation CategoryLoc,
5291                                    Decl * const *ProtoRefs,
5292                                    unsigned NumProtoRefs,
5293                                    const SourceLocation *ProtoLocs,
5294                                    SourceLocation EndProtoLoc);
5295
5296  Decl *ActOnStartClassImplementation(
5297                    SourceLocation AtClassImplLoc,
5298                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
5299                    IdentifierInfo *SuperClassname,
5300                    SourceLocation SuperClassLoc);
5301
5302  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
5303                                         IdentifierInfo *ClassName,
5304                                         SourceLocation ClassLoc,
5305                                         IdentifierInfo *CatName,
5306                                         SourceLocation CatLoc);
5307
5308  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
5309                                     IdentifierInfo **IdentList,
5310                                     SourceLocation *IdentLocs,
5311                                     unsigned NumElts);
5312
5313  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
5314                                        const IdentifierLocPair *IdentList,
5315                                        unsigned NumElts,
5316                                        AttributeList *attrList);
5317
5318  void FindProtocolDeclaration(bool WarnOnDeclarations,
5319                               const IdentifierLocPair *ProtocolId,
5320                               unsigned NumProtocols,
5321                               SmallVectorImpl<Decl *> &Protocols);
5322
5323  /// Ensure attributes are consistent with type.
5324  /// \param [in, out] Attributes The attributes to check; they will
5325  /// be modified to be consistent with \arg PropertyTy.
5326  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
5327                                   SourceLocation Loc,
5328                                   unsigned &Attributes);
5329
5330  /// Process the specified property declaration and create decls for the
5331  /// setters and getters as needed.
5332  /// \param property The property declaration being processed
5333  /// \param DC The semantic container for the property
5334  /// \param redeclaredProperty Declaration for property if redeclared
5335  ///        in class extension.
5336  /// \param lexicalDC Container for redeclaredProperty.
5337  void ProcessPropertyDecl(ObjCPropertyDecl *property,
5338                           ObjCContainerDecl *DC,
5339                           ObjCPropertyDecl *redeclaredProperty = 0,
5340                           ObjCContainerDecl *lexicalDC = 0);
5341
5342  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
5343                                ObjCPropertyDecl *SuperProperty,
5344                                const IdentifierInfo *Name);
5345  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
5346
5347  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
5348                                         ObjCMethodDecl *MethodDecl,
5349                                         bool IsInstance);
5350
5351  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
5352
5353  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
5354                                        ObjCInterfaceDecl *ID);
5355
5356  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
5357                                         ObjCProtocolDecl *PDecl);
5358
5359  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
5360                   Decl **allMethods = 0, unsigned allNum = 0,
5361                   Decl **allProperties = 0, unsigned pNum = 0,
5362                   DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
5363
5364  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
5365                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
5366                      Selector GetterSel, Selector SetterSel,
5367                      bool *OverridingProperty,
5368                      tok::ObjCKeywordKind MethodImplKind,
5369                      DeclContext *lexicalDC = 0);
5370
5371  Decl *ActOnPropertyImplDecl(Scope *S,
5372                              SourceLocation AtLoc,
5373                              SourceLocation PropertyLoc,
5374                              bool ImplKind,
5375                              IdentifierInfo *PropertyId,
5376                              IdentifierInfo *PropertyIvar,
5377                              SourceLocation PropertyIvarLoc);
5378
5379  enum ObjCSpecialMethodKind {
5380    OSMK_None,
5381    OSMK_Alloc,
5382    OSMK_New,
5383    OSMK_Copy,
5384    OSMK_RetainingInit,
5385    OSMK_NonRetainingInit
5386  };
5387
5388  struct ObjCArgInfo {
5389    IdentifierInfo *Name;
5390    SourceLocation NameLoc;
5391    // The Type is null if no type was specified, and the DeclSpec is invalid
5392    // in this case.
5393    ParsedType Type;
5394    ObjCDeclSpec DeclSpec;
5395
5396    /// ArgAttrs - Attribute list for this argument.
5397    AttributeList *ArgAttrs;
5398  };
5399
5400  Decl *ActOnMethodDeclaration(
5401    Scope *S,
5402    SourceLocation BeginLoc, // location of the + or -.
5403    SourceLocation EndLoc,   // location of the ; or {.
5404    tok::TokenKind MethodType,
5405    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
5406    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
5407    // optional arguments. The number of types/arguments is obtained
5408    // from the Sel.getNumArgs().
5409    ObjCArgInfo *ArgInfo,
5410    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
5411    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
5412    bool isVariadic, bool MethodDefinition);
5413
5414  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
5415  // Will search "local" class/category implementations for a method decl.
5416  // Will also search in class's root looking for instance method.
5417  // Returns 0 if no method is found.
5418  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
5419                                           ObjCInterfaceDecl *CDecl);
5420  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
5421                                              ObjCInterfaceDecl *ClassDecl);
5422  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
5423                                              const ObjCObjectPointerType *OPT,
5424                                              bool IsInstance);
5425  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
5426                                           bool IsInstance);
5427
5428  bool inferObjCARCLifetime(ValueDecl *decl);
5429
5430  ExprResult
5431  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
5432                            Expr *BaseExpr,
5433                            SourceLocation OpLoc,
5434                            DeclarationName MemberName,
5435                            SourceLocation MemberLoc,
5436                            SourceLocation SuperLoc, QualType SuperType,
5437                            bool Super);
5438
5439  ExprResult
5440  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
5441                            IdentifierInfo &propertyName,
5442                            SourceLocation receiverNameLoc,
5443                            SourceLocation propertyNameLoc);
5444
5445  ObjCMethodDecl *tryCaptureObjCSelf();
5446
5447  /// \brief Describes the kind of message expression indicated by a message
5448  /// send that starts with an identifier.
5449  enum ObjCMessageKind {
5450    /// \brief The message is sent to 'super'.
5451    ObjCSuperMessage,
5452    /// \brief The message is an instance message.
5453    ObjCInstanceMessage,
5454    /// \brief The message is a class message, and the identifier is a type
5455    /// name.
5456    ObjCClassMessage
5457  };
5458
5459  ObjCMessageKind getObjCMessageKind(Scope *S,
5460                                     IdentifierInfo *Name,
5461                                     SourceLocation NameLoc,
5462                                     bool IsSuper,
5463                                     bool HasTrailingDot,
5464                                     ParsedType &ReceiverType);
5465
5466  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
5467                               Selector Sel,
5468                               SourceLocation LBracLoc,
5469                               ArrayRef<SourceLocation> SelectorLocs,
5470                               SourceLocation RBracLoc,
5471                               MultiExprArg Args);
5472
5473  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
5474                               QualType ReceiverType,
5475                               SourceLocation SuperLoc,
5476                               Selector Sel,
5477                               ObjCMethodDecl *Method,
5478                               SourceLocation LBracLoc,
5479                               ArrayRef<SourceLocation> SelectorLocs,
5480                               SourceLocation RBracLoc,
5481                               MultiExprArg Args,
5482                               bool isImplicit = false);
5483
5484  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
5485                                       bool isSuperReceiver,
5486                                       SourceLocation Loc,
5487                                       Selector Sel,
5488                                       ObjCMethodDecl *Method,
5489                                       MultiExprArg Args);
5490
5491  ExprResult ActOnClassMessage(Scope *S,
5492                               ParsedType Receiver,
5493                               Selector Sel,
5494                               SourceLocation LBracLoc,
5495                               ArrayRef<SourceLocation> SelectorLocs,
5496                               SourceLocation RBracLoc,
5497                               MultiExprArg Args);
5498
5499  ExprResult BuildInstanceMessage(Expr *Receiver,
5500                                  QualType ReceiverType,
5501                                  SourceLocation SuperLoc,
5502                                  Selector Sel,
5503                                  ObjCMethodDecl *Method,
5504                                  SourceLocation LBracLoc,
5505                                  ArrayRef<SourceLocation> SelectorLocs,
5506                                  SourceLocation RBracLoc,
5507                                  MultiExprArg Args,
5508                                  bool isImplicit = false);
5509
5510  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
5511                                          QualType ReceiverType,
5512                                          SourceLocation Loc,
5513                                          Selector Sel,
5514                                          ObjCMethodDecl *Method,
5515                                          MultiExprArg Args);
5516
5517  ExprResult ActOnInstanceMessage(Scope *S,
5518                                  Expr *Receiver,
5519                                  Selector Sel,
5520                                  SourceLocation LBracLoc,
5521                                  ArrayRef<SourceLocation> SelectorLocs,
5522                                  SourceLocation RBracLoc,
5523                                  MultiExprArg Args);
5524
5525  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
5526                                  ObjCBridgeCastKind Kind,
5527                                  SourceLocation BridgeKeywordLoc,
5528                                  TypeSourceInfo *TSInfo,
5529                                  Expr *SubExpr);
5530
5531  ExprResult ActOnObjCBridgedCast(Scope *S,
5532                                  SourceLocation LParenLoc,
5533                                  ObjCBridgeCastKind Kind,
5534                                  SourceLocation BridgeKeywordLoc,
5535                                  ParsedType Type,
5536                                  SourceLocation RParenLoc,
5537                                  Expr *SubExpr);
5538
5539  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
5540
5541  /// \brief Check whether the given new method is a valid override of the
5542  /// given overridden method, and set any properties that should be inherited.
5543  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
5544                               const ObjCMethodDecl *Overridden,
5545                               bool IsImplementation);
5546
5547  /// \brief Check whether the given method overrides any methods in its class,
5548  /// calling \c CheckObjCMethodOverride for each overridden method.
5549  bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC);
5550
5551  enum PragmaOptionsAlignKind {
5552    POAK_Native,  // #pragma options align=native
5553    POAK_Natural, // #pragma options align=natural
5554    POAK_Packed,  // #pragma options align=packed
5555    POAK_Power,   // #pragma options align=power
5556    POAK_Mac68k,  // #pragma options align=mac68k
5557    POAK_Reset    // #pragma options align=reset
5558  };
5559
5560  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
5561  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
5562                               SourceLocation PragmaLoc,
5563                               SourceLocation KindLoc);
5564
5565  enum PragmaPackKind {
5566    PPK_Default, // #pragma pack([n])
5567    PPK_Show,    // #pragma pack(show), only supported by MSVC.
5568    PPK_Push,    // #pragma pack(push, [identifier], [n])
5569    PPK_Pop      // #pragma pack(pop, [identifier], [n])
5570  };
5571
5572  enum PragmaMSStructKind {
5573    PMSST_OFF,  // #pragms ms_struct off
5574    PMSST_ON    // #pragms ms_struct on
5575  };
5576
5577  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
5578  void ActOnPragmaPack(PragmaPackKind Kind,
5579                       IdentifierInfo *Name,
5580                       Expr *Alignment,
5581                       SourceLocation PragmaLoc,
5582                       SourceLocation LParenLoc,
5583                       SourceLocation RParenLoc);
5584
5585  /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
5586  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
5587
5588  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
5589  void ActOnPragmaUnused(const Token &Identifier,
5590                         Scope *curScope,
5591                         SourceLocation PragmaLoc);
5592
5593  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
5594  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
5595                             SourceLocation PragmaLoc);
5596
5597  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5598                                 SourceLocation Loc);
5599  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
5600
5601  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
5602  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
5603                         SourceLocation PragmaLoc,
5604                         SourceLocation WeakNameLoc);
5605
5606  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
5607  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
5608                            IdentifierInfo* AliasName,
5609                            SourceLocation PragmaLoc,
5610                            SourceLocation WeakNameLoc,
5611                            SourceLocation AliasNameLoc);
5612
5613  /// ActOnPragmaFPContract - Called on well formed
5614  /// #pragma {STDC,OPENCL} FP_CONTRACT
5615  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
5616
5617  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
5618  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
5619  void AddAlignmentAttributesForRecord(RecordDecl *RD);
5620
5621  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
5622  void AddMsStructLayoutForRecord(RecordDecl *RD);
5623
5624  /// FreePackedContext - Deallocate and null out PackContext.
5625  void FreePackedContext();
5626
5627  /// PushNamespaceVisibilityAttr - Note that we've entered a
5628  /// namespace with a visibility attribute.
5629  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
5630
5631  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
5632  /// add an appropriate visibility attribute.
5633  void AddPushedVisibilityAttribute(Decl *RD);
5634
5635  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
5636  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
5637  void PopPragmaVisibility();
5638
5639  /// FreeVisContext - Deallocate and null out VisContext.
5640  void FreeVisContext();
5641
5642  /// AddCFAuditedAttribute - Check whether we're currently within
5643  /// '#pragma clang arc_cf_code_audited' and, if so, consider adding
5644  /// the appropriate attribute.
5645  void AddCFAuditedAttribute(Decl *D);
5646
5647  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5648  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E);
5649  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T);
5650
5651  /// \brief The kind of conversion being performed.
5652  enum CheckedConversionKind {
5653    /// \brief An implicit conversion.
5654    CCK_ImplicitConversion,
5655    /// \brief A C-style cast.
5656    CCK_CStyleCast,
5657    /// \brief A functional-style cast.
5658    CCK_FunctionalCast,
5659    /// \brief A cast other than a C-style cast.
5660    CCK_OtherCast
5661  };
5662
5663  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
5664  /// cast.  If there is already an implicit cast, merge into the existing one.
5665  /// If isLvalue, the result of the cast is an lvalue.
5666  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
5667                               ExprValueKind VK = VK_RValue,
5668                               const CXXCastPath *BasePath = 0,
5669                               CheckedConversionKind CCK
5670                                  = CCK_ImplicitConversion);
5671
5672  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
5673  /// to the conversion from scalar type ScalarTy to the Boolean type.
5674  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
5675
5676  /// IgnoredValueConversions - Given that an expression's result is
5677  /// syntactically ignored, perform any conversions that are
5678  /// required.
5679  ExprResult IgnoredValueConversions(Expr *E);
5680
5681  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
5682  // functions and arrays to their respective pointers (C99 6.3.2.1).
5683  ExprResult UsualUnaryConversions(Expr *E);
5684
5685  // DefaultFunctionArrayConversion - converts functions and arrays
5686  // to their respective pointers (C99 6.3.2.1).
5687  ExprResult DefaultFunctionArrayConversion(Expr *E);
5688
5689  // DefaultFunctionArrayLvalueConversion - converts functions and
5690  // arrays to their respective pointers and performs the
5691  // lvalue-to-rvalue conversion.
5692  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
5693
5694  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
5695  // the operand.  This is DefaultFunctionArrayLvalueConversion,
5696  // except that it assumes the operand isn't of function or array
5697  // type.
5698  ExprResult DefaultLvalueConversion(Expr *E);
5699
5700  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
5701  // do not have a prototype. Integer promotions are performed on each
5702  // argument, and arguments that have type float are promoted to double.
5703  ExprResult DefaultArgumentPromotion(Expr *E);
5704
5705  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
5706  enum VariadicCallType {
5707    VariadicFunction,
5708    VariadicBlock,
5709    VariadicMethod,
5710    VariadicConstructor,
5711    VariadicDoesNotApply
5712  };
5713
5714  /// GatherArgumentsForCall - Collector argument expressions for various
5715  /// form of call prototypes.
5716  bool GatherArgumentsForCall(SourceLocation CallLoc,
5717                              FunctionDecl *FDecl,
5718                              const FunctionProtoType *Proto,
5719                              unsigned FirstProtoArg,
5720                              Expr **Args, unsigned NumArgs,
5721                              SmallVector<Expr *, 8> &AllArgs,
5722                              VariadicCallType CallType = VariadicDoesNotApply);
5723
5724  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
5725  // will warn if the resulting type is not a POD type.
5726  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
5727                                              FunctionDecl *FDecl);
5728
5729  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
5730  // operands and then handles various conversions that are common to binary
5731  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
5732  // routine returns the first non-arithmetic type found. The client is
5733  // responsible for emitting appropriate error diagnostics.
5734  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
5735                                      bool IsCompAssign = false);
5736
5737  /// AssignConvertType - All of the 'assignment' semantic checks return this
5738  /// enum to indicate whether the assignment was allowed.  These checks are
5739  /// done for simple assignments, as well as initialization, return from
5740  /// function, argument passing, etc.  The query is phrased in terms of a
5741  /// source and destination type.
5742  enum AssignConvertType {
5743    /// Compatible - the types are compatible according to the standard.
5744    Compatible,
5745
5746    /// PointerToInt - The assignment converts a pointer to an int, which we
5747    /// accept as an extension.
5748    PointerToInt,
5749
5750    /// IntToPointer - The assignment converts an int to a pointer, which we
5751    /// accept as an extension.
5752    IntToPointer,
5753
5754    /// FunctionVoidPointer - The assignment is between a function pointer and
5755    /// void*, which the standard doesn't allow, but we accept as an extension.
5756    FunctionVoidPointer,
5757
5758    /// IncompatiblePointer - The assignment is between two pointers types that
5759    /// are not compatible, but we accept them as an extension.
5760    IncompatiblePointer,
5761
5762    /// IncompatiblePointer - The assignment is between two pointers types which
5763    /// point to integers which have a different sign, but are otherwise
5764    /// identical. This is a subset of the above, but broken out because it's by
5765    /// far the most common case of incompatible pointers.
5766    IncompatiblePointerSign,
5767
5768    /// CompatiblePointerDiscardsQualifiers - The assignment discards
5769    /// c/v/r qualifiers, which we accept as an extension.
5770    CompatiblePointerDiscardsQualifiers,
5771
5772    /// IncompatiblePointerDiscardsQualifiers - The assignment
5773    /// discards qualifiers that we don't permit to be discarded,
5774    /// like address spaces.
5775    IncompatiblePointerDiscardsQualifiers,
5776
5777    /// IncompatibleNestedPointerQualifiers - The assignment is between two
5778    /// nested pointer types, and the qualifiers other than the first two
5779    /// levels differ e.g. char ** -> const char **, but we accept them as an
5780    /// extension.
5781    IncompatibleNestedPointerQualifiers,
5782
5783    /// IncompatibleVectors - The assignment is between two vector types that
5784    /// have the same size, which we accept as an extension.
5785    IncompatibleVectors,
5786
5787    /// IntToBlockPointer - The assignment converts an int to a block
5788    /// pointer. We disallow this.
5789    IntToBlockPointer,
5790
5791    /// IncompatibleBlockPointer - The assignment is between two block
5792    /// pointers types that are not compatible.
5793    IncompatibleBlockPointer,
5794
5795    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
5796    /// id type and something else (that is incompatible with it). For example,
5797    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
5798    IncompatibleObjCQualifiedId,
5799
5800    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
5801    /// object with __weak qualifier.
5802    IncompatibleObjCWeakRef,
5803
5804    /// Incompatible - We reject this conversion outright, it is invalid to
5805    /// represent it in the AST.
5806    Incompatible
5807  };
5808
5809  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
5810  /// assignment conversion type specified by ConvTy.  This returns true if the
5811  /// conversion was invalid or false if the conversion was accepted.
5812  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
5813                                SourceLocation Loc,
5814                                QualType DstType, QualType SrcType,
5815                                Expr *SrcExpr, AssignmentAction Action,
5816                                bool *Complained = 0);
5817
5818  /// CheckAssignmentConstraints - Perform type checking for assignment,
5819  /// argument passing, variable initialization, and function return values.
5820  /// C99 6.5.16.
5821  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
5822                                               QualType LHSType,
5823                                               QualType RHSType);
5824
5825  /// Check assignment constraints and prepare for a conversion of the
5826  /// RHS to the LHS type.
5827  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
5828                                               ExprResult &RHS,
5829                                               CastKind &Kind);
5830
5831  // CheckSingleAssignmentConstraints - Currently used by
5832  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
5833  // this routine performs the default function/array converions.
5834  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
5835                                                     ExprResult &RHS,
5836                                                     bool Diagnose = true);
5837
5838  // \brief If the lhs type is a transparent union, check whether we
5839  // can initialize the transparent union with the given expression.
5840  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
5841                                                             ExprResult &RHS);
5842
5843  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
5844
5845  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
5846
5847  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5848                                       AssignmentAction Action,
5849                                       bool AllowExplicit = false);
5850  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5851                                       AssignmentAction Action,
5852                                       bool AllowExplicit,
5853                                       ImplicitConversionSequence& ICS);
5854  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5855                                       const ImplicitConversionSequence& ICS,
5856                                       AssignmentAction Action,
5857                                       CheckedConversionKind CCK
5858                                          = CCK_ImplicitConversion);
5859  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5860                                       const StandardConversionSequence& SCS,
5861                                       AssignmentAction Action,
5862                                       CheckedConversionKind CCK);
5863
5864  /// the following "Check" methods will return a valid/converted QualType
5865  /// or a null QualType (indicating an error diagnostic was issued).
5866
5867  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
5868  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5869                           ExprResult &RHS);
5870  QualType CheckPointerToMemberOperands( // C++ 5.5
5871    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
5872    SourceLocation OpLoc, bool isIndirect);
5873  QualType CheckMultiplyDivideOperands( // C99 6.5.5
5874    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
5875    bool IsDivide);
5876  QualType CheckRemainderOperands( // C99 6.5.5
5877    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5878    bool IsCompAssign = false);
5879  QualType CheckAdditionOperands( // C99 6.5.6
5880    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5881    QualType* CompLHSTy = 0);
5882  QualType CheckSubtractionOperands( // C99 6.5.6
5883    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5884    QualType* CompLHSTy = 0);
5885  QualType CheckShiftOperands( // C99 6.5.7
5886    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
5887    bool IsCompAssign = false);
5888  QualType CheckCompareOperands( // C99 6.5.8/9
5889    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
5890                                bool isRelational);
5891  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
5892    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5893    bool IsCompAssign = false);
5894  QualType CheckLogicalOperands( // C99 6.5.[13,14]
5895    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
5896  // CheckAssignmentOperands is used for both simple and compound assignment.
5897  // For simple assignment, pass both expressions and a null converted type.
5898  // For compound assignment, pass both expressions and the converted type.
5899  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
5900    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
5901
5902  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
5903                                     UnaryOperatorKind Opcode, Expr *Op);
5904  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
5905                                         BinaryOperatorKind Opcode,
5906                                         Expr *LHS, Expr *RHS);
5907  ExprResult checkPseudoObjectRValue(Expr *E);
5908  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
5909
5910  QualType CheckConditionalOperands( // C99 6.5.15
5911    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
5912    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
5913  QualType CXXCheckConditionalOperands( // C++ 5.16
5914    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5915    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5916  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
5917                                    bool *NonStandardCompositeType = 0);
5918  QualType FindCompositePointerType(SourceLocation Loc,
5919                                    ExprResult &E1, ExprResult &E2,
5920                                    bool *NonStandardCompositeType = 0) {
5921    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
5922    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
5923                                                  NonStandardCompositeType);
5924    E1 = Owned(E1Tmp);
5925    E2 = Owned(E2Tmp);
5926    return Composite;
5927  }
5928
5929  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5930                                        SourceLocation QuestionLoc);
5931
5932  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5933                                  SourceLocation QuestionLoc);
5934
5935  /// type checking for vector binary operators.
5936  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5937                               SourceLocation Loc, bool IsCompAssign);
5938  QualType GetSignedVectorType(QualType V);
5939  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
5940                                      SourceLocation Loc, bool isRelational);
5941  QualType CheckVectorLogicalOperands(ExprResult LHS, ExprResult RHS,
5942                                      SourceLocation Loc);
5943
5944  /// type checking declaration initializers (C99 6.7.8)
5945  bool CheckForConstantInitializer(Expr *e, QualType t);
5946
5947  // type checking C++ declaration initializers (C++ [dcl.init]).
5948
5949  /// ReferenceCompareResult - Expresses the result of comparing two
5950  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
5951  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
5952  enum ReferenceCompareResult {
5953    /// Ref_Incompatible - The two types are incompatible, so direct
5954    /// reference binding is not possible.
5955    Ref_Incompatible = 0,
5956    /// Ref_Related - The two types are reference-related, which means
5957    /// that their unqualified forms (T1 and T2) are either the same
5958    /// or T1 is a base class of T2.
5959    Ref_Related,
5960    /// Ref_Compatible_With_Added_Qualification - The two types are
5961    /// reference-compatible with added qualification, meaning that
5962    /// they are reference-compatible and the qualifiers on T1 (cv1)
5963    /// are greater than the qualifiers on T2 (cv2).
5964    Ref_Compatible_With_Added_Qualification,
5965    /// Ref_Compatible - The two types are reference-compatible and
5966    /// have equivalent qualifiers (cv1 == cv2).
5967    Ref_Compatible
5968  };
5969
5970  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
5971                                                      QualType T1, QualType T2,
5972                                                      bool &DerivedToBase,
5973                                                      bool &ObjCConversion,
5974                                                bool &ObjCLifetimeConversion);
5975
5976  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
5977                                 Expr *CastExpr, CastKind &CastKind,
5978                                 ExprValueKind &VK, CXXCastPath &Path);
5979
5980  /// \brief Force an expression with unknown-type to an expression of the
5981  /// given type.
5982  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
5983
5984  // CheckVectorCast - check type constraints for vectors.
5985  // Since vectors are an extension, there are no C standard reference for this.
5986  // We allow casting between vectors and integer datatypes of the same size.
5987  // returns true if the cast is invalid
5988  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5989                       CastKind &Kind);
5990
5991  // CheckExtVectorCast - check type constraints for extended vectors.
5992  // Since vectors are an extension, there are no C standard reference for this.
5993  // We allow casting between vectors and integer datatypes of the same size,
5994  // or vectors and the element type of that vector.
5995  // returns the cast expr
5996  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
5997                                CastKind &Kind);
5998
5999  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
6000                                        SourceLocation LParenLoc,
6001                                        Expr *CastExpr,
6002                                        SourceLocation RParenLoc);
6003
6004  enum ARCConversionResult { ACR_okay, ACR_unbridged };
6005
6006  /// \brief Checks for invalid conversions and casts between
6007  /// retainable pointers and other pointer kinds.
6008  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
6009                                             QualType castType, Expr *&op,
6010                                             CheckedConversionKind CCK);
6011
6012  Expr *stripARCUnbridgedCast(Expr *e);
6013  void diagnoseARCUnbridgedCast(Expr *e);
6014
6015  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
6016                                             QualType ExprType);
6017
6018  /// checkRetainCycles - Check whether an Objective-C message send
6019  /// might create an obvious retain cycle.
6020  void checkRetainCycles(ObjCMessageExpr *msg);
6021  void checkRetainCycles(Expr *receiver, Expr *argument);
6022
6023  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
6024  /// to weak/__unsafe_unretained type.
6025  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
6026
6027  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
6028  /// to weak/__unsafe_unretained expression.
6029  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
6030
6031  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
6032  /// \param Method - May be null.
6033  /// \param [out] ReturnType - The return type of the send.
6034  /// \return true iff there were any incompatible types.
6035  bool CheckMessageArgumentTypes(QualType ReceiverType,
6036                                 Expr **Args, unsigned NumArgs, Selector Sel,
6037                                 ObjCMethodDecl *Method, bool isClassMessage,
6038                                 bool isSuperMessage,
6039                                 SourceLocation lbrac, SourceLocation rbrac,
6040                                 QualType &ReturnType, ExprValueKind &VK);
6041
6042  /// \brief Determine the result of a message send expression based on
6043  /// the type of the receiver, the method expected to receive the message,
6044  /// and the form of the message send.
6045  QualType getMessageSendResultType(QualType ReceiverType,
6046                                    ObjCMethodDecl *Method,
6047                                    bool isClassMessage, bool isSuperMessage);
6048
6049  /// \brief If the given expression involves a message send to a method
6050  /// with a related result type, emit a note describing what happened.
6051  void EmitRelatedResultTypeNote(const Expr *E);
6052
6053  /// CheckBooleanCondition - Diagnose problems involving the use of
6054  /// the given expression as a boolean condition (e.g. in an if
6055  /// statement).  Also performs the standard function and array
6056  /// decays, possibly changing the input variable.
6057  ///
6058  /// \param Loc - A location associated with the condition, e.g. the
6059  /// 'if' keyword.
6060  /// \return true iff there were any errors
6061  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
6062
6063  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
6064                                   Expr *SubExpr);
6065
6066  /// DiagnoseAssignmentAsCondition - Given that an expression is
6067  /// being used as a boolean condition, warn if it's an assignment.
6068  void DiagnoseAssignmentAsCondition(Expr *E);
6069
6070  /// \brief Redundant parentheses over an equality comparison can indicate
6071  /// that the user intended an assignment used as condition.
6072  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
6073
6074  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
6075  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
6076
6077  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
6078  /// the specified width and sign.  If an overflow occurs, detect it and emit
6079  /// the specified diagnostic.
6080  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
6081                                          unsigned NewWidth, bool NewSign,
6082                                          SourceLocation Loc, unsigned DiagID);
6083
6084  /// Checks that the Objective-C declaration is declared in the global scope.
6085  /// Emits an error and marks the declaration as invalid if it's not declared
6086  /// in the global scope.
6087  bool CheckObjCDeclScope(Decl *D);
6088
6089  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
6090  /// and reports the appropriate diagnostics. Returns false on success.
6091  /// Can optionally return the value of the expression.
6092  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0,
6093                                       unsigned DiagId = 0,
6094                                       bool AllowFold = true);
6095
6096  /// VerifyBitField - verifies that a bit field expression is an ICE and has
6097  /// the correct width, and that the field type is valid.
6098  /// Returns false on success.
6099  /// Can optionally return whether the bit-field is of width 0
6100  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
6101                      QualType FieldTy, const Expr *BitWidth,
6102                      bool *ZeroWidth = 0);
6103
6104  enum CUDAFunctionTarget {
6105    CFT_Device,
6106    CFT_Global,
6107    CFT_Host,
6108    CFT_HostDevice
6109  };
6110
6111  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
6112
6113  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
6114                       CUDAFunctionTarget CalleeTarget);
6115
6116  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
6117    return CheckCUDATarget(IdentifyCUDATarget(Caller),
6118                           IdentifyCUDATarget(Callee));
6119  }
6120
6121  /// \name Code completion
6122  //@{
6123  /// \brief Describes the context in which code completion occurs.
6124  enum ParserCompletionContext {
6125    /// \brief Code completion occurs at top-level or namespace context.
6126    PCC_Namespace,
6127    /// \brief Code completion occurs within a class, struct, or union.
6128    PCC_Class,
6129    /// \brief Code completion occurs within an Objective-C interface, protocol,
6130    /// or category.
6131    PCC_ObjCInterface,
6132    /// \brief Code completion occurs within an Objective-C implementation or
6133    /// category implementation
6134    PCC_ObjCImplementation,
6135    /// \brief Code completion occurs within the list of instance variables
6136    /// in an Objective-C interface, protocol, category, or implementation.
6137    PCC_ObjCInstanceVariableList,
6138    /// \brief Code completion occurs following one or more template
6139    /// headers.
6140    PCC_Template,
6141    /// \brief Code completion occurs following one or more template
6142    /// headers within a class.
6143    PCC_MemberTemplate,
6144    /// \brief Code completion occurs within an expression.
6145    PCC_Expression,
6146    /// \brief Code completion occurs within a statement, which may
6147    /// also be an expression or a declaration.
6148    PCC_Statement,
6149    /// \brief Code completion occurs at the beginning of the
6150    /// initialization statement (or expression) in a for loop.
6151    PCC_ForInit,
6152    /// \brief Code completion occurs within the condition of an if,
6153    /// while, switch, or for statement.
6154    PCC_Condition,
6155    /// \brief Code completion occurs within the body of a function on a
6156    /// recovery path, where we do not have a specific handle on our position
6157    /// in the grammar.
6158    PCC_RecoveryInFunction,
6159    /// \brief Code completion occurs where only a type is permitted.
6160    PCC_Type,
6161    /// \brief Code completion occurs in a parenthesized expression, which
6162    /// might also be a type cast.
6163    PCC_ParenthesizedExpression,
6164    /// \brief Code completion occurs within a sequence of declaration
6165    /// specifiers within a function, method, or block.
6166    PCC_LocalDeclarationSpecifiers
6167  };
6168
6169  void CodeCompleteOrdinaryName(Scope *S,
6170                                ParserCompletionContext CompletionContext);
6171  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
6172                            bool AllowNonIdentifiers,
6173                            bool AllowNestedNameSpecifiers);
6174
6175  struct CodeCompleteExpressionData;
6176  void CodeCompleteExpression(Scope *S,
6177                              const CodeCompleteExpressionData &Data);
6178  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
6179                                       SourceLocation OpLoc,
6180                                       bool IsArrow);
6181  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
6182  void CodeCompleteTag(Scope *S, unsigned TagSpec);
6183  void CodeCompleteTypeQualifiers(DeclSpec &DS);
6184  void CodeCompleteCase(Scope *S);
6185  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
6186  void CodeCompleteInitializer(Scope *S, Decl *D);
6187  void CodeCompleteReturn(Scope *S);
6188  void CodeCompleteAfterIf(Scope *S);
6189  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
6190
6191  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6192                               bool EnteringContext);
6193  void CodeCompleteUsing(Scope *S);
6194  void CodeCompleteUsingDirective(Scope *S);
6195  void CodeCompleteNamespaceDecl(Scope *S);
6196  void CodeCompleteNamespaceAliasDecl(Scope *S);
6197  void CodeCompleteOperatorName(Scope *S);
6198  void CodeCompleteConstructorInitializer(Decl *Constructor,
6199                                          CXXCtorInitializer** Initializers,
6200                                          unsigned NumInitializers);
6201
6202  void CodeCompleteObjCAtDirective(Scope *S);
6203  void CodeCompleteObjCAtVisibility(Scope *S);
6204  void CodeCompleteObjCAtStatement(Scope *S);
6205  void CodeCompleteObjCAtExpression(Scope *S);
6206  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
6207  void CodeCompleteObjCPropertyGetter(Scope *S);
6208  void CodeCompleteObjCPropertySetter(Scope *S);
6209  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
6210                                   bool IsParameter);
6211  void CodeCompleteObjCMessageReceiver(Scope *S);
6212  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
6213                                    IdentifierInfo **SelIdents,
6214                                    unsigned NumSelIdents,
6215                                    bool AtArgumentExpression);
6216  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
6217                                    IdentifierInfo **SelIdents,
6218                                    unsigned NumSelIdents,
6219                                    bool AtArgumentExpression,
6220                                    bool IsSuper = false);
6221  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
6222                                       IdentifierInfo **SelIdents,
6223                                       unsigned NumSelIdents,
6224                                       bool AtArgumentExpression,
6225                                       ObjCInterfaceDecl *Super = 0);
6226  void CodeCompleteObjCForCollection(Scope *S,
6227                                     DeclGroupPtrTy IterationVar);
6228  void CodeCompleteObjCSelector(Scope *S,
6229                                IdentifierInfo **SelIdents,
6230                                unsigned NumSelIdents);
6231  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
6232                                          unsigned NumProtocols);
6233  void CodeCompleteObjCProtocolDecl(Scope *S);
6234  void CodeCompleteObjCInterfaceDecl(Scope *S);
6235  void CodeCompleteObjCSuperclass(Scope *S,
6236                                  IdentifierInfo *ClassName,
6237                                  SourceLocation ClassNameLoc);
6238  void CodeCompleteObjCImplementationDecl(Scope *S);
6239  void CodeCompleteObjCInterfaceCategory(Scope *S,
6240                                         IdentifierInfo *ClassName,
6241                                         SourceLocation ClassNameLoc);
6242  void CodeCompleteObjCImplementationCategory(Scope *S,
6243                                              IdentifierInfo *ClassName,
6244                                              SourceLocation ClassNameLoc);
6245  void CodeCompleteObjCPropertyDefinition(Scope *S);
6246  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6247                                              IdentifierInfo *PropertyName);
6248  void CodeCompleteObjCMethodDecl(Scope *S,
6249                                  bool IsInstanceMethod,
6250                                  ParsedType ReturnType);
6251  void CodeCompleteObjCMethodDeclSelector(Scope *S,
6252                                          bool IsInstanceMethod,
6253                                          bool AtParameterName,
6254                                          ParsedType ReturnType,
6255                                          IdentifierInfo **SelIdents,
6256                                          unsigned NumSelIdents);
6257  void CodeCompletePreprocessorDirective(bool InConditional);
6258  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
6259  void CodeCompletePreprocessorMacroName(bool IsDefinition);
6260  void CodeCompletePreprocessorExpression();
6261  void CodeCompletePreprocessorMacroArgument(Scope *S,
6262                                             IdentifierInfo *Macro,
6263                                             MacroInfo *MacroInfo,
6264                                             unsigned Argument);
6265  void CodeCompleteNaturalLanguage();
6266  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
6267                  SmallVectorImpl<CodeCompletionResult> &Results);
6268  //@}
6269
6270  //===--------------------------------------------------------------------===//
6271  // Extra semantic analysis beyond the C type system
6272
6273public:
6274  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
6275                                                unsigned ByteNo) const;
6276
6277private:
6278  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6279                        const ArraySubscriptExpr *ASE=0,
6280                        bool AllowOnePastEnd=true, bool IndexNegated=false);
6281  void CheckArrayAccess(const Expr *E);
6282  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
6283  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
6284                           Expr **Args, unsigned NumArgs);
6285  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
6286
6287  bool CheckablePrintfAttr(const FormatAttr *Format, Expr **Args,
6288                           unsigned NumArgs, bool IsCXXMemberCall);
6289  bool CheckObjCString(Expr *Arg);
6290
6291  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
6292  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
6293
6294  bool SemaBuiltinVAStart(CallExpr *TheCall);
6295  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
6296  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
6297
6298public:
6299  // Used by C++ template instantiation.
6300  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
6301
6302private:
6303  bool SemaBuiltinPrefetch(CallExpr *TheCall);
6304  bool SemaBuiltinObjectSize(CallExpr *TheCall);
6305  bool SemaBuiltinLongjmp(CallExpr *TheCall);
6306  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
6307  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
6308                                     AtomicExpr::AtomicOp Op);
6309  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6310                              llvm::APSInt &Result);
6311
6312  bool SemaCheckStringLiteral(const Expr *E, Expr **Args, unsigned NumArgs,
6313                              bool HasVAListArg, unsigned format_idx,
6314                              unsigned firstDataArg, bool isPrintf,
6315                              bool inFunctionCall = true);
6316
6317  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
6318                         Expr **Args, unsigned NumArgs, bool HasVAListArg,
6319                         unsigned format_idx, unsigned firstDataArg,
6320                         bool isPrintf, bool inFunctionCall);
6321
6322  void CheckNonNullArguments(const NonNullAttr *NonNull,
6323                             const Expr * const *ExprArgs,
6324                             SourceLocation CallSiteLoc);
6325
6326  void CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall);
6327  void CheckFormatArguments(const FormatAttr *Format, Expr **Args,
6328                            unsigned NumArgs, bool IsCXXMember,
6329                            SourceLocation Loc, SourceRange Range);
6330  void CheckPrintfScanfArguments(Expr **Args, unsigned NumArgs,
6331                                 bool HasVAListArg, unsigned format_idx,
6332                                 unsigned firstDataArg, bool isPrintf,
6333                                 SourceLocation Loc, SourceRange range);
6334
6335  void CheckMemaccessArguments(const CallExpr *Call,
6336                               unsigned BId,
6337                               IdentifierInfo *FnName);
6338
6339  void CheckStrlcpycatArguments(const CallExpr *Call,
6340                                IdentifierInfo *FnName);
6341
6342  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
6343                            SourceLocation ReturnLoc);
6344  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
6345  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
6346
6347  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
6348                                   Expr *Init);
6349
6350  /// \brief The parser's current scope.
6351  ///
6352  /// The parser maintains this state here.
6353  Scope *CurScope;
6354
6355protected:
6356  friend class Parser;
6357  friend class InitializationSequence;
6358  friend class ASTReader;
6359  friend class ASTWriter;
6360
6361public:
6362  /// \brief Retrieve the parser's current scope.
6363  ///
6364  /// This routine must only be used when it is certain that semantic analysis
6365  /// and the parser are in precisely the same context, which is not the case
6366  /// when, e.g., we are performing any kind of template instantiation.
6367  /// Therefore, the only safe places to use this scope are in the parser
6368  /// itself and in routines directly invoked from the parser and *never* from
6369  /// template substitution or instantiation.
6370  Scope *getCurScope() const { return CurScope; }
6371
6372  Decl *getObjCDeclContext() const;
6373
6374  DeclContext *getCurLexicalContext() const {
6375    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
6376  }
6377
6378  AvailabilityResult getCurContextAvailability() const;
6379};
6380
6381/// \brief RAII object that enters a new expression evaluation context.
6382class EnterExpressionEvaluationContext {
6383  Sema &Actions;
6384
6385public:
6386  EnterExpressionEvaluationContext(Sema &Actions,
6387                                   Sema::ExpressionEvaluationContext NewContext)
6388    : Actions(Actions) {
6389    Actions.PushExpressionEvaluationContext(NewContext);
6390  }
6391
6392  ~EnterExpressionEvaluationContext() {
6393    Actions.PopExpressionEvaluationContext();
6394  }
6395};
6396
6397}  // end namespace clang
6398
6399#endif
6400