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