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