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