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