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