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