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