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