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