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