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