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