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