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