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