1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Sema class, which performs semantic analysis and
10 // builds ASTs.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_SEMA_SEMA_H
15 #define LLVM_CLANG_SEMA_SEMA_H
16 
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Availability.h"
20 #include "clang/AST/ComparisonCategories.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclarationName.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprConcepts.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/LocInfoType.h"
29 #include "clang/AST/MangleNumberingContext.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/PrettyPrinter.h"
32 #include "clang/AST/StmtCXX.h"
33 #include "clang/AST/TypeLoc.h"
34 #include "clang/AST/TypeOrdering.h"
35 #include "clang/Basic/BitmaskEnum.h"
36 #include "clang/Basic/ExpressionTraits.h"
37 #include "clang/Basic/Module.h"
38 #include "clang/Basic/OpenMPKinds.h"
39 #include "clang/Basic/PragmaKinds.h"
40 #include "clang/Basic/Specifiers.h"
41 #include "clang/Basic/TemplateKinds.h"
42 #include "clang/Basic/TypeTraits.h"
43 #include "clang/Sema/AnalysisBasedWarnings.h"
44 #include "clang/Sema/CleanupInfo.h"
45 #include "clang/Sema/DeclSpec.h"
46 #include "clang/Sema/ExternalSemaSource.h"
47 #include "clang/Sema/IdentifierResolver.h"
48 #include "clang/Sema/ObjCMethodList.h"
49 #include "clang/Sema/Ownership.h"
50 #include "clang/Sema/Scope.h"
51 #include "clang/Sema/SemaConcept.h"
52 #include "clang/Sema/TypoCorrection.h"
53 #include "clang/Sema/Weak.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SetVector.h"
57 #include "llvm/ADT/SmallBitVector.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/TinyPtrVector.h"
61 #include "llvm/Frontend/OpenMP/OMPConstants.h"
62 #include <deque>
63 #include <memory>
64 #include <string>
65 #include <tuple>
66 #include <vector>
67 
68 namespace llvm {
69   class APSInt;
70   template <typename ValueT> struct DenseMapInfo;
71   template <typename ValueT, typename ValueInfoT> class DenseSet;
72   class SmallBitVector;
73   struct InlineAsmIdentifierInfo;
74 }
75 
76 namespace clang {
77   class ADLResult;
78   class ASTConsumer;
79   class ASTContext;
80   class ASTMutationListener;
81   class ASTReader;
82   class ASTWriter;
83   class ArrayType;
84   class ParsedAttr;
85   class BindingDecl;
86   class BlockDecl;
87   class CapturedDecl;
88   class CXXBasePath;
89   class CXXBasePaths;
90   class CXXBindTemporaryExpr;
91   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
92   class CXXConstructorDecl;
93   class CXXConversionDecl;
94   class CXXDeleteExpr;
95   class CXXDestructorDecl;
96   class CXXFieldCollector;
97   class CXXMemberCallExpr;
98   class CXXMethodDecl;
99   class CXXScopeSpec;
100   class CXXTemporary;
101   class CXXTryStmt;
102   class CallExpr;
103   class ClassTemplateDecl;
104   class ClassTemplatePartialSpecializationDecl;
105   class ClassTemplateSpecializationDecl;
106   class VarTemplatePartialSpecializationDecl;
107   class CodeCompleteConsumer;
108   class CodeCompletionAllocator;
109   class CodeCompletionTUInfo;
110   class CodeCompletionResult;
111   class CoroutineBodyStmt;
112   class Decl;
113   class DeclAccessPair;
114   class DeclContext;
115   class DeclRefExpr;
116   class DeclaratorDecl;
117   class DeducedTemplateArgument;
118   class DependentDiagnostic;
119   class DesignatedInitExpr;
120   class Designation;
121   class EnableIfAttr;
122   class EnumConstantDecl;
123   class Expr;
124   class ExtVectorType;
125   class FormatAttr;
126   class FriendDecl;
127   class FunctionDecl;
128   class FunctionProtoType;
129   class FunctionTemplateDecl;
130   class ImplicitConversionSequence;
131   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
132   class InitListExpr;
133   class InitializationKind;
134   class InitializationSequence;
135   class InitializedEntity;
136   class IntegerLiteral;
137   class LabelStmt;
138   class LambdaExpr;
139   class LangOptions;
140   class LocalInstantiationScope;
141   class LookupResult;
142   class MacroInfo;
143   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
144   class ModuleLoader;
145   class MultiLevelTemplateArgumentList;
146   class NamedDecl;
147   class ObjCCategoryDecl;
148   class ObjCCategoryImplDecl;
149   class ObjCCompatibleAliasDecl;
150   class ObjCContainerDecl;
151   class ObjCImplDecl;
152   class ObjCImplementationDecl;
153   class ObjCInterfaceDecl;
154   class ObjCIvarDecl;
155   template <class T> class ObjCList;
156   class ObjCMessageExpr;
157   class ObjCMethodDecl;
158   class ObjCPropertyDecl;
159   class ObjCProtocolDecl;
160   class OMPThreadPrivateDecl;
161   class OMPRequiresDecl;
162   class OMPDeclareReductionDecl;
163   class OMPDeclareSimdDecl;
164   class OMPClause;
165   struct OMPVarListLocTy;
166   struct OverloadCandidate;
167   enum class OverloadCandidateParamOrder : char;
168   enum OverloadCandidateRewriteKind : unsigned;
169   class OverloadCandidateSet;
170   class OverloadExpr;
171   class ParenListExpr;
172   class ParmVarDecl;
173   class Preprocessor;
174   class PseudoDestructorTypeStorage;
175   class PseudoObjectExpr;
176   class QualType;
177   class StandardConversionSequence;
178   class Stmt;
179   class StringLiteral;
180   class SwitchStmt;
181   class TemplateArgument;
182   class TemplateArgumentList;
183   class TemplateArgumentLoc;
184   class TemplateDecl;
185   class TemplateInstantiationCallback;
186   class TemplateParameterList;
187   class TemplatePartialOrderingContext;
188   class TemplateTemplateParmDecl;
189   class Token;
190   class TypeAliasDecl;
191   class TypedefDecl;
192   class TypedefNameDecl;
193   class TypeLoc;
194   class TypoCorrectionConsumer;
195   class UnqualifiedId;
196   class UnresolvedLookupExpr;
197   class UnresolvedMemberExpr;
198   class UnresolvedSetImpl;
199   class UnresolvedSetIterator;
200   class UsingDecl;
201   class UsingShadowDecl;
202   class ValueDecl;
203   class VarDecl;
204   class VarTemplateSpecializationDecl;
205   class VisibilityAttr;
206   class VisibleDeclConsumer;
207   class IndirectFieldDecl;
208   struct DeductionFailureInfo;
209   class TemplateSpecCandidateSet;
210 
211 namespace sema {
212   class AccessedEntity;
213   class BlockScopeInfo;
214   class Capture;
215   class CapturedRegionScopeInfo;
216   class CapturingScopeInfo;
217   class CompoundScopeInfo;
218   class DelayedDiagnostic;
219   class DelayedDiagnosticPool;
220   class FunctionScopeInfo;
221   class LambdaScopeInfo;
222   class PossiblyUnreachableDiag;
223   class SemaPPCallbacks;
224   class TemplateDeductionInfo;
225 }
226 
227 namespace threadSafety {
228   class BeforeSet;
229   void threadSafetyCleanup(BeforeSet* Cache);
230 }
231 
232 // FIXME: No way to easily map from TemplateTypeParmTypes to
233 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
234 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
235                   SourceLocation> UnexpandedParameterPack;
236 
237 /// Describes whether we've seen any nullability information for the given
238 /// file.
239 struct FileNullability {
240   /// The first pointer declarator (of any pointer kind) in the file that does
241   /// not have a corresponding nullability annotation.
242   SourceLocation PointerLoc;
243 
244   /// The end location for the first pointer declarator in the file. Used for
245   /// placing fix-its.
246   SourceLocation PointerEndLoc;
247 
248   /// Which kind of pointer declarator we saw.
249   uint8_t PointerKind;
250 
251   /// Whether we saw any type nullability annotations in the given file.
252   bool SawTypeNullability = false;
253 };
254 
255 /// A mapping from file IDs to a record of whether we've seen nullability
256 /// information in that file.
257 class FileNullabilityMap {
258   /// A mapping from file IDs to the nullability information for each file ID.
259   llvm::DenseMap<FileID, FileNullability> Map;
260 
261   /// A single-element cache based on the file ID.
262   struct {
263     FileID File;
264     FileNullability Nullability;
265   } Cache;
266 
267 public:
268   FileNullability &operator[](FileID file) {
269     // Check the single-element cache.
270     if (file == Cache.File)
271       return Cache.Nullability;
272 
273     // It's not in the single-element cache; flush the cache if we have one.
274     if (!Cache.File.isInvalid()) {
275       Map[Cache.File] = Cache.Nullability;
276     }
277 
278     // Pull this entry into the cache.
279     Cache.File = file;
280     Cache.Nullability = Map[file];
281     return Cache.Nullability;
282   }
283 };
284 
285 /// Keeps track of expected type during expression parsing. The type is tied to
286 /// a particular token, all functions that update or consume the type take a
287 /// start location of the token they are looking at as a parameter. This allows
288 /// to avoid updating the type on hot paths in the parser.
289 class PreferredTypeBuilder {
290 public:
291   PreferredTypeBuilder() = default;
292   explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
293 
294   void enterCondition(Sema &S, SourceLocation Tok);
295   void enterReturn(Sema &S, SourceLocation Tok);
296   void enterVariableInit(SourceLocation Tok, Decl *D);
297   /// Computing a type for the function argument may require running
298   /// overloading, so we postpone its computation until it is actually needed.
299   ///
300   /// Clients should be very careful when using this funciton, as it stores a
301   /// function_ref, clients should make sure all calls to get() with the same
302   /// location happen while function_ref is alive.
303   void enterFunctionArgument(SourceLocation Tok,
304                              llvm::function_ref<QualType()> ComputeType);
305 
306   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
307   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
308                   SourceLocation OpLoc);
309   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
310   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
311   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
312   /// Handles all type casts, including C-style cast, C++ casts, etc.
313   void enterTypeCast(SourceLocation Tok, QualType CastType);
314 
315   QualType get(SourceLocation Tok) const {
316     if (Tok != ExpectedLoc)
317       return QualType();
318     if (!Type.isNull())
319       return Type;
320     if (ComputeType)
321       return ComputeType();
322     return QualType();
323   }
324 
325 private:
326   /// Start position of a token for which we store expected type.
327   SourceLocation ExpectedLoc;
328   /// Expected type for a token starting at ExpectedLoc.
329   QualType Type;
330   /// A function to compute expected type at ExpectedLoc. It is only considered
331   /// if Type is null.
332   llvm::function_ref<QualType()> ComputeType;
333 };
334 
335 /// Sema - This implements semantic analysis and AST building for C.
336 class Sema final {
337   Sema(const Sema &) = delete;
338   void operator=(const Sema &) = delete;
339 
340   /// A key method to reduce duplicate debug info from Sema.
341   virtual void anchor();
342 
343   ///Source of additional semantic information.
344   ExternalSemaSource *ExternalSource;
345 
346   ///Whether Sema has generated a multiplexer and has to delete it.
347   bool isMultiplexExternalSource;
348 
349   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
350 
351   bool isVisibleSlow(const NamedDecl *D);
352 
353   /// Determine whether two declarations should be linked together, given that
354   /// the old declaration might not be visible and the new declaration might
355   /// not have external linkage.
356   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
357                                     const NamedDecl *New) {
358     if (isVisible(Old))
359      return true;
360     // See comment in below overload for why it's safe to compute the linkage
361     // of the new declaration here.
362     if (New->isExternallyDeclarable()) {
363       assert(Old->isExternallyDeclarable() &&
364              "should not have found a non-externally-declarable previous decl");
365       return true;
366     }
367     return false;
368   }
369   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
370 
371   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
372                                       QualType ResultTy,
373                                       ArrayRef<QualType> Args);
374 
375 public:
376   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
377   typedef OpaquePtr<TemplateName> TemplateTy;
378   typedef OpaquePtr<QualType> TypeTy;
379 
380   OpenCLOptions OpenCLFeatures;
381   FPOptions FPFeatures;
382 
383   const LangOptions &LangOpts;
384   Preprocessor &PP;
385   ASTContext &Context;
386   ASTConsumer &Consumer;
387   DiagnosticsEngine &Diags;
388   SourceManager &SourceMgr;
389 
390   /// Flag indicating whether or not to collect detailed statistics.
391   bool CollectStats;
392 
393   /// Code-completion consumer.
394   CodeCompleteConsumer *CodeCompleter;
395 
396   /// CurContext - This is the current declaration context of parsing.
397   DeclContext *CurContext;
398 
399   /// Generally null except when we temporarily switch decl contexts,
400   /// like in \see ActOnObjCTemporaryExitContainerContext.
401   DeclContext *OriginalLexicalContext;
402 
403   /// VAListTagName - The declaration name corresponding to __va_list_tag.
404   /// This is used as part of a hack to omit that class from ADL results.
405   DeclarationName VAListTagName;
406 
407   bool MSStructPragmaOn; // True when \#pragma ms_struct on
408 
409   /// Controls member pointer representation format under the MS ABI.
410   LangOptions::PragmaMSPointersToMembersKind
411       MSPointerToMemberRepresentationMethod;
412 
413   /// Stack of active SEH __finally scopes.  Can be empty.
414   SmallVector<Scope*, 2> CurrentSEHFinally;
415 
416   /// Source location for newly created implicit MSInheritanceAttrs
417   SourceLocation ImplicitMSInheritanceAttrLoc;
418 
419   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
420   /// `TransformTypos` in order to keep track of any TypoExprs that are created
421   /// recursively during typo correction and wipe them away if the correction
422   /// fails.
423   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
424 
425   /// pragma clang section kind
426   enum PragmaClangSectionKind {
427     PCSK_Invalid      = 0,
428     PCSK_BSS          = 1,
429     PCSK_Data         = 2,
430     PCSK_Rodata       = 3,
431     PCSK_Text         = 4,
432     PCSK_Relro        = 5
433    };
434 
435   enum PragmaClangSectionAction {
436     PCSA_Set     = 0,
437     PCSA_Clear   = 1
438   };
439 
440   struct PragmaClangSection {
441     std::string SectionName;
442     bool Valid = false;
443     SourceLocation PragmaLocation;
444 
445     void Act(SourceLocation PragmaLocation,
446              PragmaClangSectionAction Action,
447              StringLiteral* Name);
448    };
449 
450    PragmaClangSection PragmaClangBSSSection;
451    PragmaClangSection PragmaClangDataSection;
452    PragmaClangSection PragmaClangRodataSection;
453    PragmaClangSection PragmaClangRelroSection;
454    PragmaClangSection PragmaClangTextSection;
455 
456   enum PragmaMsStackAction {
457     PSK_Reset     = 0x0,                // #pragma ()
458     PSK_Set       = 0x1,                // #pragma (value)
459     PSK_Push      = 0x2,                // #pragma (push[, id])
460     PSK_Pop       = 0x4,                // #pragma (pop[, id])
461     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
462     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
463     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
464   };
465 
466   template<typename ValueType>
467   struct PragmaStack {
468     struct Slot {
469       llvm::StringRef StackSlotLabel;
470       ValueType Value;
471       SourceLocation PragmaLocation;
472       SourceLocation PragmaPushLocation;
473       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
474            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
475           : StackSlotLabel(StackSlotLabel), Value(Value),
476             PragmaLocation(PragmaLocation),
477             PragmaPushLocation(PragmaPushLocation) {}
478     };
479     void Act(SourceLocation PragmaLocation,
480              PragmaMsStackAction Action,
481              llvm::StringRef StackSlotLabel,
482              ValueType Value);
483 
484     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
485     // method body to restore the stacks on exit, so it works like this:
486     //
487     //   struct S {
488     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
489     //     void Method {}
490     //     #pragma <name>(pop, InternalPragmaSlot)
491     //   };
492     //
493     // It works even with #pragma vtordisp, although MSVC doesn't support
494     //   #pragma vtordisp(push [, id], n)
495     // syntax.
496     //
497     // Push / pop a named sentinel slot.
498     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
499       assert((Action == PSK_Push || Action == PSK_Pop) &&
500              "Can only push / pop #pragma stack sentinels!");
501       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
502     }
503 
504     // Constructors.
505     explicit PragmaStack(const ValueType &Default)
506         : DefaultValue(Default), CurrentValue(Default) {}
507 
508     bool hasValue() const { return CurrentValue != DefaultValue; }
509 
510     SmallVector<Slot, 2> Stack;
511     ValueType DefaultValue; // Value used for PSK_Reset action.
512     ValueType CurrentValue;
513     SourceLocation CurrentPragmaLocation;
514   };
515   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
516   // we shouldn't do so if they're in a module).
517 
518   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
519   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
520   ///
521   /// 0: Suppress all vtordisps
522   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
523   ///    structors
524   /// 2: Always insert vtordisps to support RTTI on partially constructed
525   ///    objects
526   PragmaStack<MSVtorDispMode> VtorDispStack;
527   // #pragma pack.
528   // Sentinel to represent when the stack is set to mac68k alignment.
529   static const unsigned kMac68kAlignmentSentinel = ~0U;
530   PragmaStack<unsigned> PackStack;
531   // The current #pragma pack values and locations at each #include.
532   struct PackIncludeState {
533     unsigned CurrentValue;
534     SourceLocation CurrentPragmaLocation;
535     bool HasNonDefaultValue, ShouldWarnOnInclude;
536   };
537   SmallVector<PackIncludeState, 8> PackIncludeStack;
538   // Segment #pragmas.
539   PragmaStack<StringLiteral *> DataSegStack;
540   PragmaStack<StringLiteral *> BSSSegStack;
541   PragmaStack<StringLiteral *> ConstSegStack;
542   PragmaStack<StringLiteral *> CodeSegStack;
543 
544   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
545   // Actions should be performed only if we enter / exit a C++ method body.
546   class PragmaStackSentinelRAII {
547   public:
548     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
549     ~PragmaStackSentinelRAII();
550 
551   private:
552     Sema &S;
553     StringRef SlotLabel;
554     bool ShouldAct;
555   };
556 
557   /// A mapping that describes the nullability we've seen in each header file.
558   FileNullabilityMap NullabilityMap;
559 
560   /// Last section used with #pragma init_seg.
561   StringLiteral *CurInitSeg;
562   SourceLocation CurInitSegLoc;
563 
564   /// VisContext - Manages the stack for \#pragma GCC visibility.
565   void *VisContext; // Really a "PragmaVisStack*"
566 
567   /// This an attribute introduced by \#pragma clang attribute.
568   struct PragmaAttributeEntry {
569     SourceLocation Loc;
570     ParsedAttr *Attribute;
571     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
572     bool IsUsed;
573   };
574 
575   /// A push'd group of PragmaAttributeEntries.
576   struct PragmaAttributeGroup {
577     /// The location of the push attribute.
578     SourceLocation Loc;
579     /// The namespace of this push group.
580     const IdentifierInfo *Namespace;
581     SmallVector<PragmaAttributeEntry, 2> Entries;
582   };
583 
584   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
585 
586   /// The declaration that is currently receiving an attribute from the
587   /// #pragma attribute stack.
588   const Decl *PragmaAttributeCurrentTargetDecl;
589 
590   /// This represents the last location of a "#pragma clang optimize off"
591   /// directive if such a directive has not been closed by an "on" yet. If
592   /// optimizations are currently "on", this is set to an invalid location.
593   SourceLocation OptimizeOffPragmaLocation;
594 
595   /// Flag indicating if Sema is building a recovery call expression.
596   ///
597   /// This flag is used to avoid building recovery call expressions
598   /// if Sema is already doing so, which would cause infinite recursions.
599   bool IsBuildingRecoveryCallExpr;
600 
601   /// Used to control the generation of ExprWithCleanups.
602   CleanupInfo Cleanup;
603 
604   /// ExprCleanupObjects - This is the stack of objects requiring
605   /// cleanup that are created by the current full expression.  The
606   /// element type here is ExprWithCleanups::Object.
607   SmallVector<BlockDecl*, 8> ExprCleanupObjects;
608 
609   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
610   /// to a variable (constant) that may or may not be odr-used in this Expr, and
611   /// we won't know until all lvalue-to-rvalue and discarded value conversions
612   /// have been applied to all subexpressions of the enclosing full expression.
613   /// This is cleared at the end of each full expression.
614   using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
615   MaybeODRUseExprSet MaybeODRUseExprs;
616 
617   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
618 
619   /// Stack containing information about each of the nested
620   /// function, block, and method scopes that are currently active.
621   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
622 
623   /// The index of the first FunctionScope that corresponds to the current
624   /// context.
625   unsigned FunctionScopesStart = 0;
626 
627   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
628     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
629                               FunctionScopes.end());
630   }
631 
632   /// Stack containing information needed when in C++2a an 'auto' is encountered
633   /// in a function declaration parameter type specifier in order to invent a
634   /// corresponding template parameter in the enclosing abbreviated function
635   /// template. This information is also present in LambdaScopeInfo, stored in
636   /// the FunctionScopes stack.
637   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
638 
639   /// The index of the first InventedParameterInfo that refers to the current
640   /// context.
641   unsigned InventedParameterInfosStart = 0;
642 
643   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
644     return llvm::makeArrayRef(InventedParameterInfos.begin() +
645                                   InventedParameterInfosStart,
646                               InventedParameterInfos.end());
647   }
648 
649   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
650                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
651     ExtVectorDeclsType;
652 
653   /// ExtVectorDecls - This is a list all the extended vector types. This allows
654   /// us to associate a raw vector type with one of the ext_vector type names.
655   /// This is only necessary for issuing pretty diagnostics.
656   ExtVectorDeclsType ExtVectorDecls;
657 
658   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
659   std::unique_ptr<CXXFieldCollector> FieldCollector;
660 
661   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
662 
663   /// Set containing all declared private fields that are not used.
664   NamedDeclSetType UnusedPrivateFields;
665 
666   /// Set containing all typedefs that are likely unused.
667   llvm::SmallSetVector<const TypedefNameDecl *, 4>
668       UnusedLocalTypedefNameCandidates;
669 
670   /// Delete-expressions to be analyzed at the end of translation unit
671   ///
672   /// This list contains class members, and locations of delete-expressions
673   /// that could not be proven as to whether they mismatch with new-expression
674   /// used in initializer of the field.
675   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
676   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
677   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
678 
679   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
680 
681   /// PureVirtualClassDiagSet - a set of class declarations which we have
682   /// emitted a list of pure virtual functions. Used to prevent emitting the
683   /// same list more than once.
684   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
685 
686   /// ParsingInitForAutoVars - a set of declarations with auto types for which
687   /// we are currently parsing the initializer.
688   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
689 
690   /// Look for a locally scoped extern "C" declaration by the given name.
691   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
692 
693   typedef LazyVector<VarDecl *, ExternalSemaSource,
694                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
695     TentativeDefinitionsType;
696 
697   /// All the tentative definitions encountered in the TU.
698   TentativeDefinitionsType TentativeDefinitions;
699 
700   /// All the external declarations encoutered and used in the TU.
701   SmallVector<VarDecl *, 4> ExternalDeclarations;
702 
703   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
704                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
705     UnusedFileScopedDeclsType;
706 
707   /// The set of file scoped decls seen so far that have not been used
708   /// and must warn if not used. Only contains the first declaration.
709   UnusedFileScopedDeclsType UnusedFileScopedDecls;
710 
711   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
712                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
713     DelegatingCtorDeclsType;
714 
715   /// All the delegating constructors seen so far in the file, used for
716   /// cycle detection at the end of the TU.
717   DelegatingCtorDeclsType DelegatingCtorDecls;
718 
719   /// All the overriding functions seen during a class definition
720   /// that had their exception spec checks delayed, plus the overridden
721   /// function.
722   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
723     DelayedOverridingExceptionSpecChecks;
724 
725   /// All the function redeclarations seen during a class definition that had
726   /// their exception spec checks delayed, plus the prior declaration they
727   /// should be checked against. Except during error recovery, the new decl
728   /// should always be a friend declaration, as that's the only valid way to
729   /// redeclare a special member before its class is complete.
730   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
731     DelayedEquivalentExceptionSpecChecks;
732 
733   typedef llvm::MapVector<const FunctionDecl *,
734                           std::unique_ptr<LateParsedTemplate>>
735       LateParsedTemplateMapT;
736   LateParsedTemplateMapT LateParsedTemplateMap;
737 
738   /// Callback to the parser to parse templated functions when needed.
739   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
740   typedef void LateTemplateParserCleanupCB(void *P);
741   LateTemplateParserCB *LateTemplateParser;
742   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
743   void *OpaqueParser;
744 
745   void SetLateTemplateParser(LateTemplateParserCB *LTP,
746                              LateTemplateParserCleanupCB *LTPCleanup,
747                              void *P) {
748     LateTemplateParser = LTP;
749     LateTemplateParserCleanup = LTPCleanup;
750     OpaqueParser = P;
751   }
752 
753   class DelayedDiagnostics;
754 
755   class DelayedDiagnosticsState {
756     sema::DelayedDiagnosticPool *SavedPool;
757     friend class Sema::DelayedDiagnostics;
758   };
759   typedef DelayedDiagnosticsState ParsingDeclState;
760   typedef DelayedDiagnosticsState ProcessingContextState;
761 
762   /// A class which encapsulates the logic for delaying diagnostics
763   /// during parsing and other processing.
764   class DelayedDiagnostics {
765     /// The current pool of diagnostics into which delayed
766     /// diagnostics should go.
767     sema::DelayedDiagnosticPool *CurPool;
768 
769   public:
770     DelayedDiagnostics() : CurPool(nullptr) {}
771 
772     /// Adds a delayed diagnostic.
773     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
774 
775     /// Determines whether diagnostics should be delayed.
776     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
777 
778     /// Returns the current delayed-diagnostics pool.
779     sema::DelayedDiagnosticPool *getCurrentPool() const {
780       return CurPool;
781     }
782 
783     /// Enter a new scope.  Access and deprecation diagnostics will be
784     /// collected in this pool.
785     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
786       DelayedDiagnosticsState state;
787       state.SavedPool = CurPool;
788       CurPool = &pool;
789       return state;
790     }
791 
792     /// Leave a delayed-diagnostic state that was previously pushed.
793     /// Do not emit any of the diagnostics.  This is performed as part
794     /// of the bookkeeping of popping a pool "properly".
795     void popWithoutEmitting(DelayedDiagnosticsState state) {
796       CurPool = state.SavedPool;
797     }
798 
799     /// Enter a new scope where access and deprecation diagnostics are
800     /// not delayed.
801     DelayedDiagnosticsState pushUndelayed() {
802       DelayedDiagnosticsState state;
803       state.SavedPool = CurPool;
804       CurPool = nullptr;
805       return state;
806     }
807 
808     /// Undo a previous pushUndelayed().
809     void popUndelayed(DelayedDiagnosticsState state) {
810       assert(CurPool == nullptr);
811       CurPool = state.SavedPool;
812     }
813   } DelayedDiagnostics;
814 
815   /// A RAII object to temporarily push a declaration context.
816   class ContextRAII {
817   private:
818     Sema &S;
819     DeclContext *SavedContext;
820     ProcessingContextState SavedContextState;
821     QualType SavedCXXThisTypeOverride;
822     unsigned SavedFunctionScopesStart;
823     unsigned SavedInventedParameterInfosStart;
824 
825   public:
826     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
827       : S(S), SavedContext(S.CurContext),
828         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
829         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
830         SavedFunctionScopesStart(S.FunctionScopesStart),
831         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
832     {
833       assert(ContextToPush && "pushing null context");
834       S.CurContext = ContextToPush;
835       if (NewThisContext)
836         S.CXXThisTypeOverride = QualType();
837       // Any saved FunctionScopes do not refer to this context.
838       S.FunctionScopesStart = S.FunctionScopes.size();
839       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
840     }
841 
842     void pop() {
843       if (!SavedContext) return;
844       S.CurContext = SavedContext;
845       S.DelayedDiagnostics.popUndelayed(SavedContextState);
846       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
847       S.FunctionScopesStart = SavedFunctionScopesStart;
848       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
849       SavedContext = nullptr;
850     }
851 
852     ~ContextRAII() {
853       pop();
854     }
855   };
856 
857   /// Used to change context to isConstantEvaluated without pushing a heavy
858   /// ExpressionEvaluationContextRecord object.
859   bool isConstantEvaluatedOverride;
860 
861   bool isConstantEvaluated() {
862     return ExprEvalContexts.back().isConstantEvaluated() ||
863            isConstantEvaluatedOverride;
864   }
865 
866   /// RAII object to handle the state changes required to synthesize
867   /// a function body.
868   class SynthesizedFunctionScope {
869     Sema &S;
870     Sema::ContextRAII SavedContext;
871     bool PushedCodeSynthesisContext = false;
872 
873   public:
874     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
875         : S(S), SavedContext(S, DC) {
876       S.PushFunctionScope();
877       S.PushExpressionEvaluationContext(
878           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
879       if (auto *FD = dyn_cast<FunctionDecl>(DC))
880         FD->setWillHaveBody(true);
881       else
882         assert(isa<ObjCMethodDecl>(DC));
883     }
884 
885     void addContextNote(SourceLocation UseLoc) {
886       assert(!PushedCodeSynthesisContext);
887 
888       Sema::CodeSynthesisContext Ctx;
889       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
890       Ctx.PointOfInstantiation = UseLoc;
891       Ctx.Entity = cast<Decl>(S.CurContext);
892       S.pushCodeSynthesisContext(Ctx);
893 
894       PushedCodeSynthesisContext = true;
895     }
896 
897     ~SynthesizedFunctionScope() {
898       if (PushedCodeSynthesisContext)
899         S.popCodeSynthesisContext();
900       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
901         FD->setWillHaveBody(false);
902       S.PopExpressionEvaluationContext();
903       S.PopFunctionScopeInfo();
904     }
905   };
906 
907   /// WeakUndeclaredIdentifiers - Identifiers contained in
908   /// \#pragma weak before declared. rare. may alias another
909   /// identifier, declared or undeclared
910   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
911 
912   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
913   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
914   /// to define functions that occur in multiple standards to call the version
915   /// in the currently selected standard.
916   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
917 
918 
919   /// Load weak undeclared identifiers from the external source.
920   void LoadExternalWeakUndeclaredIdentifiers();
921 
922   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
923   /// \#pragma weak during processing of other Decls.
924   /// I couldn't figure out a clean way to generate these in-line, so
925   /// we store them here and handle separately -- which is a hack.
926   /// It would be best to refactor this.
927   SmallVector<Decl*,2> WeakTopLevelDecl;
928 
929   IdentifierResolver IdResolver;
930 
931   /// Translation Unit Scope - useful to Objective-C actions that need
932   /// to lookup file scope declarations in the "ordinary" C decl namespace.
933   /// For example, user-defined classes, built-in "id" type, etc.
934   Scope *TUScope;
935 
936   /// The C++ "std" namespace, where the standard library resides.
937   LazyDeclPtr StdNamespace;
938 
939   /// The C++ "std::bad_alloc" class, which is defined by the C++
940   /// standard library.
941   LazyDeclPtr StdBadAlloc;
942 
943   /// The C++ "std::align_val_t" enum class, which is defined by the C++
944   /// standard library.
945   LazyDeclPtr StdAlignValT;
946 
947   /// The C++ "std::experimental" namespace, where the experimental parts
948   /// of the standard library resides.
949   NamespaceDecl *StdExperimentalNamespaceCache;
950 
951   /// The C++ "std::initializer_list" template, which is defined in
952   /// \<initializer_list>.
953   ClassTemplateDecl *StdInitializerList;
954 
955   /// The C++ "std::coroutine_traits" template, which is defined in
956   /// \<coroutine_traits>
957   ClassTemplateDecl *StdCoroutineTraitsCache;
958 
959   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
960   RecordDecl *CXXTypeInfoDecl;
961 
962   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
963   RecordDecl *MSVCGuidDecl;
964 
965   /// Caches identifiers/selectors for NSFoundation APIs.
966   std::unique_ptr<NSAPI> NSAPIObj;
967 
968   /// The declaration of the Objective-C NSNumber class.
969   ObjCInterfaceDecl *NSNumberDecl;
970 
971   /// The declaration of the Objective-C NSValue class.
972   ObjCInterfaceDecl *NSValueDecl;
973 
974   /// Pointer to NSNumber type (NSNumber *).
975   QualType NSNumberPointer;
976 
977   /// Pointer to NSValue type (NSValue *).
978   QualType NSValuePointer;
979 
980   /// The Objective-C NSNumber methods used to create NSNumber literals.
981   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
982 
983   /// The declaration of the Objective-C NSString class.
984   ObjCInterfaceDecl *NSStringDecl;
985 
986   /// Pointer to NSString type (NSString *).
987   QualType NSStringPointer;
988 
989   /// The declaration of the stringWithUTF8String: method.
990   ObjCMethodDecl *StringWithUTF8StringMethod;
991 
992   /// The declaration of the valueWithBytes:objCType: method.
993   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
994 
995   /// The declaration of the Objective-C NSArray class.
996   ObjCInterfaceDecl *NSArrayDecl;
997 
998   /// The declaration of the arrayWithObjects:count: method.
999   ObjCMethodDecl *ArrayWithObjectsMethod;
1000 
1001   /// The declaration of the Objective-C NSDictionary class.
1002   ObjCInterfaceDecl *NSDictionaryDecl;
1003 
1004   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1005   ObjCMethodDecl *DictionaryWithObjectsMethod;
1006 
1007   /// id<NSCopying> type.
1008   QualType QIDNSCopying;
1009 
1010   /// will hold 'respondsToSelector:'
1011   Selector RespondsToSelectorSel;
1012 
1013   /// A flag to remember whether the implicit forms of operator new and delete
1014   /// have been declared.
1015   bool GlobalNewDeleteDeclared;
1016 
1017   /// A flag to indicate that we're in a context that permits abstract
1018   /// references to fields.  This is really a
1019   bool AllowAbstractFieldReference;
1020 
1021   /// Describes how the expressions currently being parsed are
1022   /// evaluated at run-time, if at all.
1023   enum class ExpressionEvaluationContext {
1024     /// The current expression and its subexpressions occur within an
1025     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1026     /// \c sizeof, where the type of the expression may be significant but
1027     /// no code will be generated to evaluate the value of the expression at
1028     /// run time.
1029     Unevaluated,
1030 
1031     /// The current expression occurs within a braced-init-list within
1032     /// an unevaluated operand. This is mostly like a regular unevaluated
1033     /// context, except that we still instantiate constexpr functions that are
1034     /// referenced here so that we can perform narrowing checks correctly.
1035     UnevaluatedList,
1036 
1037     /// The current expression occurs within a discarded statement.
1038     /// This behaves largely similarly to an unevaluated operand in preventing
1039     /// definitions from being required, but not in other ways.
1040     DiscardedStatement,
1041 
1042     /// The current expression occurs within an unevaluated
1043     /// operand that unconditionally permits abstract references to
1044     /// fields, such as a SIZE operator in MS-style inline assembly.
1045     UnevaluatedAbstract,
1046 
1047     /// The current context is "potentially evaluated" in C++11 terms,
1048     /// but the expression is evaluated at compile-time (like the values of
1049     /// cases in a switch statement).
1050     ConstantEvaluated,
1051 
1052     /// The current expression is potentially evaluated at run time,
1053     /// which means that code may be generated to evaluate the value of the
1054     /// expression at run time.
1055     PotentiallyEvaluated,
1056 
1057     /// The current expression is potentially evaluated, but any
1058     /// declarations referenced inside that expression are only used if
1059     /// in fact the current expression is used.
1060     ///
1061     /// This value is used when parsing default function arguments, for which
1062     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1063     /// through varargs) but do not want to mark declarations as "referenced"
1064     /// until the default argument is used.
1065     PotentiallyEvaluatedIfUsed
1066   };
1067 
1068   /// Data structure used to record current or nested
1069   /// expression evaluation contexts.
1070   struct ExpressionEvaluationContextRecord {
1071     /// The expression evaluation context.
1072     ExpressionEvaluationContext Context;
1073 
1074     /// Whether the enclosing context needed a cleanup.
1075     CleanupInfo ParentCleanup;
1076 
1077     /// Whether we are in a decltype expression.
1078     bool IsDecltype;
1079 
1080     /// The number of active cleanup objects when we entered
1081     /// this expression evaluation context.
1082     unsigned NumCleanupObjects;
1083 
1084     /// The number of typos encountered during this expression evaluation
1085     /// context (i.e. the number of TypoExprs created).
1086     unsigned NumTypos;
1087 
1088     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1089 
1090     /// The lambdas that are present within this context, if it
1091     /// is indeed an unevaluated context.
1092     SmallVector<LambdaExpr *, 2> Lambdas;
1093 
1094     /// The declaration that provides context for lambda expressions
1095     /// and block literals if the normal declaration context does not
1096     /// suffice, e.g., in a default function argument.
1097     Decl *ManglingContextDecl;
1098 
1099     /// If we are processing a decltype type, a set of call expressions
1100     /// for which we have deferred checking the completeness of the return type.
1101     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1102 
1103     /// If we are processing a decltype type, a set of temporary binding
1104     /// expressions for which we have deferred checking the destructor.
1105     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1106 
1107     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1108 
1109     /// Expressions appearing as the LHS of a volatile assignment in this
1110     /// context. We produce a warning for these when popping the context if
1111     /// they are not discarded-value expressions nor unevaluated operands.
1112     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1113 
1114     /// \brief Describes whether we are in an expression constext which we have
1115     /// to handle differently.
1116     enum ExpressionKind {
1117       EK_Decltype, EK_TemplateArgument, EK_Other
1118     } ExprContext;
1119 
1120     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1121                                       unsigned NumCleanupObjects,
1122                                       CleanupInfo ParentCleanup,
1123                                       Decl *ManglingContextDecl,
1124                                       ExpressionKind ExprContext)
1125         : Context(Context), ParentCleanup(ParentCleanup),
1126           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1127           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1128 
1129     bool isUnevaluated() const {
1130       return Context == ExpressionEvaluationContext::Unevaluated ||
1131              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1132              Context == ExpressionEvaluationContext::UnevaluatedList;
1133     }
1134     bool isConstantEvaluated() const {
1135       return Context == ExpressionEvaluationContext::ConstantEvaluated;
1136     }
1137   };
1138 
1139   /// A stack of expression evaluation contexts.
1140   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1141 
1142   /// Emit a warning for all pending noderef expressions that we recorded.
1143   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1144 
1145   /// Compute the mangling number context for a lambda expression or
1146   /// block literal. Also return the extra mangling decl if any.
1147   ///
1148   /// \param DC - The DeclContext containing the lambda expression or
1149   /// block literal.
1150   std::tuple<MangleNumberingContext *, Decl *>
1151   getCurrentMangleNumberContext(const DeclContext *DC);
1152 
1153 
1154   /// SpecialMemberOverloadResult - The overloading result for a special member
1155   /// function.
1156   ///
1157   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1158   /// integer are used to determine whether overload resolution succeeded.
1159   class SpecialMemberOverloadResult {
1160   public:
1161     enum Kind {
1162       NoMemberOrDeleted,
1163       Ambiguous,
1164       Success
1165     };
1166 
1167   private:
1168     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1169 
1170   public:
1171     SpecialMemberOverloadResult() : Pair() {}
1172     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1173         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1174 
1175     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1176     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1177 
1178     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1179     void setKind(Kind K) { Pair.setInt(K); }
1180   };
1181 
1182   class SpecialMemberOverloadResultEntry
1183       : public llvm::FastFoldingSetNode,
1184         public SpecialMemberOverloadResult {
1185   public:
1186     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1187       : FastFoldingSetNode(ID)
1188     {}
1189   };
1190 
1191   /// A cache of special member function overload resolution results
1192   /// for C++ records.
1193   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1194 
1195   /// A cache of the flags available in enumerations with the flag_bits
1196   /// attribute.
1197   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1198 
1199   /// The kind of translation unit we are processing.
1200   ///
1201   /// When we're processing a complete translation unit, Sema will perform
1202   /// end-of-translation-unit semantic tasks (such as creating
1203   /// initializers for tentative definitions in C) once parsing has
1204   /// completed. Modules and precompiled headers perform different kinds of
1205   /// checks.
1206   TranslationUnitKind TUKind;
1207 
1208   llvm::BumpPtrAllocator BumpAlloc;
1209 
1210   /// The number of SFINAE diagnostics that have been trapped.
1211   unsigned NumSFINAEErrors;
1212 
1213   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1214     UnparsedDefaultArgInstantiationsMap;
1215 
1216   /// A mapping from parameters with unparsed default arguments to the
1217   /// set of instantiations of each parameter.
1218   ///
1219   /// This mapping is a temporary data structure used when parsing
1220   /// nested class templates or nested classes of class templates,
1221   /// where we might end up instantiating an inner class before the
1222   /// default arguments of its methods have been parsed.
1223   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1224 
1225   // Contains the locations of the beginning of unparsed default
1226   // argument locations.
1227   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1228 
1229   /// UndefinedInternals - all the used, undefined objects which require a
1230   /// definition in this translation unit.
1231   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1232 
1233   /// Determine if VD, which must be a variable or function, is an external
1234   /// symbol that nonetheless can't be referenced from outside this translation
1235   /// unit because its type has no linkage and it's not extern "C".
1236   bool isExternalWithNoLinkageType(ValueDecl *VD);
1237 
1238   /// Obtain a sorted list of functions that are undefined but ODR-used.
1239   void getUndefinedButUsed(
1240       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1241 
1242   /// Retrieves list of suspicious delete-expressions that will be checked at
1243   /// the end of translation unit.
1244   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1245   getMismatchingDeleteExpressions() const;
1246 
1247   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1248   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1249 
1250   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1251   /// We need to maintain a list, since selectors can have differing signatures
1252   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1253   /// of selectors are "overloaded").
1254   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1255   /// methods inside categories with a particular selector.
1256   GlobalMethodPool MethodPool;
1257 
1258   /// Method selectors used in a \@selector expression. Used for implementation
1259   /// of -Wselector.
1260   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1261 
1262   /// List of SourceLocations where 'self' is implicitly retained inside a
1263   /// block.
1264   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1265       ImplicitlyRetainedSelfLocs;
1266 
1267   /// Kinds of C++ special members.
1268   enum CXXSpecialMember {
1269     CXXDefaultConstructor,
1270     CXXCopyConstructor,
1271     CXXMoveConstructor,
1272     CXXCopyAssignment,
1273     CXXMoveAssignment,
1274     CXXDestructor,
1275     CXXInvalid
1276   };
1277 
1278   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1279       SpecialMemberDecl;
1280 
1281   /// The C++ special members which we are currently in the process of
1282   /// declaring. If this process recursively triggers the declaration of the
1283   /// same special member, we should act as if it is not yet declared.
1284   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1285 
1286   /// Kinds of defaulted comparison operator functions.
1287   enum class DefaultedComparisonKind : unsigned char {
1288     /// This is not a defaultable comparison operator.
1289     None,
1290     /// This is an operator== that should be implemented as a series of
1291     /// subobject comparisons.
1292     Equal,
1293     /// This is an operator<=> that should be implemented as a series of
1294     /// subobject comparisons.
1295     ThreeWay,
1296     /// This is an operator!= that should be implemented as a rewrite in terms
1297     /// of a == comparison.
1298     NotEqual,
1299     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1300     /// terms of a <=> comparison.
1301     Relational,
1302   };
1303 
1304   /// The function definitions which were renamed as part of typo-correction
1305   /// to match their respective declarations. We want to keep track of them
1306   /// to ensure that we don't emit a "redefinition" error if we encounter a
1307   /// correctly named definition after the renamed definition.
1308   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1309 
1310   /// Stack of types that correspond to the parameter entities that are
1311   /// currently being copy-initialized. Can be empty.
1312   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1313 
1314   void ReadMethodPool(Selector Sel);
1315   void updateOutOfDateSelector(Selector Sel);
1316 
1317   /// Private Helper predicate to check for 'self'.
1318   bool isSelfExpr(Expr *RExpr);
1319   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1320 
1321   /// Cause the active diagnostic on the DiagosticsEngine to be
1322   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1323   /// should not be used elsewhere.
1324   void EmitCurrentDiagnostic(unsigned DiagID);
1325 
1326   /// Records and restores the FP_CONTRACT state on entry/exit of compound
1327   /// statements.
1328   class FPContractStateRAII {
1329   public:
1330     FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1331     ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1332 
1333   private:
1334     Sema& S;
1335     FPOptions OldFPFeaturesState;
1336   };
1337 
1338   void addImplicitTypedef(StringRef Name, QualType T);
1339 
1340   bool WarnedStackExhausted = false;
1341 
1342 public:
1343   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1344        TranslationUnitKind TUKind = TU_Complete,
1345        CodeCompleteConsumer *CompletionConsumer = nullptr);
1346   ~Sema();
1347 
1348   /// Perform initialization that occurs after the parser has been
1349   /// initialized but before it parses anything.
1350   void Initialize();
1351 
1352   const LangOptions &getLangOpts() const { return LangOpts; }
1353   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1354   FPOptions     &getFPOptions() { return FPFeatures; }
1355 
1356   DiagnosticsEngine &getDiagnostics() const { return Diags; }
1357   SourceManager &getSourceManager() const { return SourceMgr; }
1358   Preprocessor &getPreprocessor() const { return PP; }
1359   ASTContext &getASTContext() const { return Context; }
1360   ASTConsumer &getASTConsumer() const { return Consumer; }
1361   ASTMutationListener *getASTMutationListener() const;
1362   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1363 
1364   ///Registers an external source. If an external source already exists,
1365   /// creates a multiplex external source and appends to it.
1366   ///
1367   ///\param[in] E - A non-null external sema source.
1368   ///
1369   void addExternalSource(ExternalSemaSource *E);
1370 
1371   void PrintStats() const;
1372 
1373   /// Warn that the stack is nearly exhausted.
1374   void warnStackExhausted(SourceLocation Loc);
1375 
1376   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1377   /// guaranteed). Produces a warning if we're low on stack space and allocates
1378   /// more in that case. Use this in code that may recurse deeply (for example,
1379   /// in template instantiation) to avoid stack overflow.
1380   void runWithSufficientStackSpace(SourceLocation Loc,
1381                                    llvm::function_ref<void()> Fn);
1382 
1383   /// Helper class that creates diagnostics with optional
1384   /// template instantiation stacks.
1385   ///
1386   /// This class provides a wrapper around the basic DiagnosticBuilder
1387   /// class that emits diagnostics. SemaDiagnosticBuilder is
1388   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1389   /// does) and, if the diagnostic comes from inside a template
1390   /// instantiation, printing the template instantiation stack as
1391   /// well.
1392   class SemaDiagnosticBuilder : public DiagnosticBuilder {
1393     Sema &SemaRef;
1394     unsigned DiagID;
1395 
1396   public:
1397     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1398       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1399 
1400     // This is a cunning lie. DiagnosticBuilder actually performs move
1401     // construction in its copy constructor (but due to varied uses, it's not
1402     // possible to conveniently express this as actual move construction). So
1403     // the default copy ctor here is fine, because the base class disables the
1404     // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1405     // in that case anwyay.
1406     SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1407 
1408     ~SemaDiagnosticBuilder() {
1409       // If we aren't active, there is nothing to do.
1410       if (!isActive()) return;
1411 
1412       // Otherwise, we need to emit the diagnostic. First flush the underlying
1413       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1414       // won't emit the diagnostic in its own destructor.
1415       //
1416       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1417       // do its own needless checks to see if the diagnostic needs to be
1418       // emitted. However, because we take care to ensure that the builder
1419       // objects never escape, a sufficiently smart compiler will be able to
1420       // eliminate that code.
1421       FlushCounts();
1422       Clear();
1423 
1424       // Dispatch to Sema to emit the diagnostic.
1425       SemaRef.EmitCurrentDiagnostic(DiagID);
1426     }
1427 
1428     /// Teach operator<< to produce an object of the correct type.
1429     template<typename T>
1430     friend const SemaDiagnosticBuilder &operator<<(
1431         const SemaDiagnosticBuilder &Diag, const T &Value) {
1432       const DiagnosticBuilder &BaseDiag = Diag;
1433       BaseDiag << Value;
1434       return Diag;
1435     }
1436   };
1437 
1438   /// Emit a diagnostic.
1439   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1440     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1441     return SemaDiagnosticBuilder(DB, *this, DiagID);
1442   }
1443 
1444   /// Emit a partial diagnostic.
1445   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1446 
1447   /// Build a partial diagnostic.
1448   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1449 
1450   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1451 
1452   /// Get a string to suggest for zero-initialization of a type.
1453   std::string
1454   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1455   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1456 
1457   /// Calls \c Lexer::getLocForEndOfToken()
1458   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1459 
1460   /// Retrieve the module loader associated with the preprocessor.
1461   ModuleLoader &getModuleLoader() const;
1462 
1463   /// Invent a new identifier for parameters of abbreviated templates.
1464   IdentifierInfo *
1465   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1466                                              unsigned Index);
1467 
1468   void emitAndClearUnusedLocalTypedefWarnings();
1469 
1470   enum TUFragmentKind {
1471     /// The global module fragment, between 'module;' and a module-declaration.
1472     Global,
1473     /// A normal translation unit fragment. For a non-module unit, this is the
1474     /// entire translation unit. Otherwise, it runs from the module-declaration
1475     /// to the private-module-fragment (if any) or the end of the TU (if not).
1476     Normal,
1477     /// The private module fragment, between 'module :private;' and the end of
1478     /// the translation unit.
1479     Private
1480   };
1481 
1482   void ActOnStartOfTranslationUnit();
1483   void ActOnEndOfTranslationUnit();
1484   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1485 
1486   void CheckDelegatingCtorCycles();
1487 
1488   Scope *getScopeForContext(DeclContext *Ctx);
1489 
1490   void PushFunctionScope();
1491   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1492   sema::LambdaScopeInfo *PushLambdaScope();
1493 
1494   /// This is used to inform Sema what the current TemplateParameterDepth
1495   /// is during Parsing.  Currently it is used to pass on the depth
1496   /// when parsing generic lambda 'auto' parameters.
1497   void RecordParsingTemplateParameterDepth(unsigned Depth);
1498 
1499   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1500                                RecordDecl *RD, CapturedRegionKind K,
1501                                unsigned OpenMPCaptureLevel = 0);
1502 
1503   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1504   /// time after they've been popped.
1505   class PoppedFunctionScopeDeleter {
1506     Sema *Self;
1507 
1508   public:
1509     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1510     void operator()(sema::FunctionScopeInfo *Scope) const;
1511   };
1512 
1513   using PoppedFunctionScopePtr =
1514       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1515 
1516   PoppedFunctionScopePtr
1517   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1518                        const Decl *D = nullptr,
1519                        QualType BlockType = QualType());
1520 
1521   sema::FunctionScopeInfo *getCurFunction() const {
1522     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1523   }
1524 
1525   sema::FunctionScopeInfo *getEnclosingFunction() const;
1526 
1527   void setFunctionHasBranchIntoScope();
1528   void setFunctionHasBranchProtectedScope();
1529   void setFunctionHasIndirectGoto();
1530 
1531   void PushCompoundScope(bool IsStmtExpr);
1532   void PopCompoundScope();
1533 
1534   sema::CompoundScopeInfo &getCurCompoundScope() const;
1535 
1536   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1537 
1538   /// Retrieve the current block, if any.
1539   sema::BlockScopeInfo *getCurBlock();
1540 
1541   /// Get the innermost lambda enclosing the current location, if any. This
1542   /// looks through intervening non-lambda scopes such as local functions and
1543   /// blocks.
1544   sema::LambdaScopeInfo *getEnclosingLambda() const;
1545 
1546   /// Retrieve the current lambda scope info, if any.
1547   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1548   /// lambda scope info ignoring all inner capturing scopes that are not
1549   /// lambda scopes.
1550   sema::LambdaScopeInfo *
1551   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1552 
1553   /// Retrieve the current generic lambda info, if any.
1554   sema::LambdaScopeInfo *getCurGenericLambda();
1555 
1556   /// Retrieve the current captured region, if any.
1557   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1558 
1559   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1560   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1561 
1562   /// Called before parsing a function declarator belonging to a function
1563   /// declaration.
1564   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1565                                                unsigned TemplateParameterDepth);
1566 
1567   /// Called after parsing a function declarator belonging to a function
1568   /// declaration.
1569   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1570 
1571   void ActOnComment(SourceRange Comment);
1572 
1573   //===--------------------------------------------------------------------===//
1574   // Type Analysis / Processing: SemaType.cpp.
1575   //
1576 
1577   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1578                               const DeclSpec *DS = nullptr);
1579   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1580                               const DeclSpec *DS = nullptr);
1581   QualType BuildPointerType(QualType T,
1582                             SourceLocation Loc, DeclarationName Entity);
1583   QualType BuildReferenceType(QualType T, bool LValueRef,
1584                               SourceLocation Loc, DeclarationName Entity);
1585   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1586                           Expr *ArraySize, unsigned Quals,
1587                           SourceRange Brackets, DeclarationName Entity);
1588   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1589   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1590                               SourceLocation AttrLoc);
1591   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1592                                  SourceLocation AttrLoc);
1593 
1594   /// Same as above, but constructs the AddressSpace index if not provided.
1595   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1596                                  SourceLocation AttrLoc);
1597 
1598   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1599 
1600   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1601 
1602   /// Build a function type.
1603   ///
1604   /// This routine checks the function type according to C++ rules and
1605   /// under the assumption that the result type and parameter types have
1606   /// just been instantiated from a template. It therefore duplicates
1607   /// some of the behavior of GetTypeForDeclarator, but in a much
1608   /// simpler form that is only suitable for this narrow use case.
1609   ///
1610   /// \param T The return type of the function.
1611   ///
1612   /// \param ParamTypes The parameter types of the function. This array
1613   /// will be modified to account for adjustments to the types of the
1614   /// function parameters.
1615   ///
1616   /// \param Loc The location of the entity whose type involves this
1617   /// function type or, if there is no such entity, the location of the
1618   /// type that will have function type.
1619   ///
1620   /// \param Entity The name of the entity that involves the function
1621   /// type, if known.
1622   ///
1623   /// \param EPI Extra information about the function type. Usually this will
1624   /// be taken from an existing function with the same prototype.
1625   ///
1626   /// \returns A suitable function type, if there are no errors. The
1627   /// unqualified type will always be a FunctionProtoType.
1628   /// Otherwise, returns a NULL type.
1629   QualType BuildFunctionType(QualType T,
1630                              MutableArrayRef<QualType> ParamTypes,
1631                              SourceLocation Loc, DeclarationName Entity,
1632                              const FunctionProtoType::ExtProtoInfo &EPI);
1633 
1634   QualType BuildMemberPointerType(QualType T, QualType Class,
1635                                   SourceLocation Loc,
1636                                   DeclarationName Entity);
1637   QualType BuildBlockPointerType(QualType T,
1638                                  SourceLocation Loc, DeclarationName Entity);
1639   QualType BuildParenType(QualType T);
1640   QualType BuildAtomicType(QualType T, SourceLocation Loc);
1641   QualType BuildReadPipeType(QualType T,
1642                          SourceLocation Loc);
1643   QualType BuildWritePipeType(QualType T,
1644                          SourceLocation Loc);
1645 
1646   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1647   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1648 
1649   /// Package the given type and TSI into a ParsedType.
1650   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1651   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1652   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1653   static QualType GetTypeFromParser(ParsedType Ty,
1654                                     TypeSourceInfo **TInfo = nullptr);
1655   CanThrowResult canThrow(const Stmt *E);
1656   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1657                                                 const FunctionProtoType *FPT);
1658   void UpdateExceptionSpec(FunctionDecl *FD,
1659                            const FunctionProtoType::ExceptionSpecInfo &ESI);
1660   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1661   bool CheckDistantExceptionSpec(QualType T);
1662   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1663   bool CheckEquivalentExceptionSpec(
1664       const FunctionProtoType *Old, SourceLocation OldLoc,
1665       const FunctionProtoType *New, SourceLocation NewLoc);
1666   bool CheckEquivalentExceptionSpec(
1667       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1668       const FunctionProtoType *Old, SourceLocation OldLoc,
1669       const FunctionProtoType *New, SourceLocation NewLoc);
1670   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1671   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1672                                 const PartialDiagnostic &NestedDiagID,
1673                                 const PartialDiagnostic &NoteID,
1674                                 const PartialDiagnostic &NoThrowDiagID,
1675                                 const FunctionProtoType *Superset,
1676                                 SourceLocation SuperLoc,
1677                                 const FunctionProtoType *Subset,
1678                                 SourceLocation SubLoc);
1679   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1680                                const PartialDiagnostic &NoteID,
1681                                const FunctionProtoType *Target,
1682                                SourceLocation TargetLoc,
1683                                const FunctionProtoType *Source,
1684                                SourceLocation SourceLoc);
1685 
1686   TypeResult ActOnTypeName(Scope *S, Declarator &D);
1687 
1688   /// The parser has parsed the context-sensitive type 'instancetype'
1689   /// in an Objective-C message declaration. Return the appropriate type.
1690   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1691 
1692   /// Abstract class used to diagnose incomplete types.
1693   struct TypeDiagnoser {
1694     TypeDiagnoser() {}
1695 
1696     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1697     virtual ~TypeDiagnoser() {}
1698   };
1699 
1700   static int getPrintable(int I) { return I; }
1701   static unsigned getPrintable(unsigned I) { return I; }
1702   static bool getPrintable(bool B) { return B; }
1703   static const char * getPrintable(const char *S) { return S; }
1704   static StringRef getPrintable(StringRef S) { return S; }
1705   static const std::string &getPrintable(const std::string &S) { return S; }
1706   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1707     return II;
1708   }
1709   static DeclarationName getPrintable(DeclarationName N) { return N; }
1710   static QualType getPrintable(QualType T) { return T; }
1711   static SourceRange getPrintable(SourceRange R) { return R; }
1712   static SourceRange getPrintable(SourceLocation L) { return L; }
1713   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1714   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1715 
1716   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1717     unsigned DiagID;
1718     std::tuple<const Ts &...> Args;
1719 
1720     template <std::size_t... Is>
1721     void emit(const SemaDiagnosticBuilder &DB,
1722               std::index_sequence<Is...>) const {
1723       // Apply all tuple elements to the builder in order.
1724       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1725       (void)Dummy;
1726     }
1727 
1728   public:
1729     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1730         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1731       assert(DiagID != 0 && "no diagnostic for type diagnoser");
1732     }
1733 
1734     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1735       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1736       emit(DB, std::index_sequence_for<Ts...>());
1737       DB << T;
1738     }
1739   };
1740 
1741 private:
1742   /// Methods for marking which expressions involve dereferencing a pointer
1743   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1744   /// they are parsed, meaning that a noderef pointer may not be accessed. For
1745   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1746   /// `*p`, but need to check that `address of` is called on it. This requires
1747   /// keeping a container of all pending expressions and checking if the address
1748   /// of them are eventually taken.
1749   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1750   void CheckAddressOfNoDeref(const Expr *E);
1751   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1752 
1753   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1754                                TypeDiagnoser *Diagnoser);
1755 
1756   struct ModuleScope {
1757     SourceLocation BeginLoc;
1758     clang::Module *Module = nullptr;
1759     bool ModuleInterface = false;
1760     bool ImplicitGlobalModuleFragment = false;
1761     VisibleModuleSet OuterVisibleModules;
1762   };
1763   /// The modules we're currently parsing.
1764   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1765 
1766   /// Namespace definitions that we will export when they finish.
1767   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1768 
1769   /// Get the module whose scope we are currently within.
1770   Module *getCurrentModule() const {
1771     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1772   }
1773 
1774   VisibleModuleSet VisibleModules;
1775 
1776 public:
1777   /// Get the module owning an entity.
1778   Module *getOwningModule(const Decl *Entity) {
1779     return Entity->getOwningModule();
1780   }
1781 
1782   /// Make a merged definition of an existing hidden definition \p ND
1783   /// visible at the specified location.
1784   void makeMergedDefinitionVisible(NamedDecl *ND);
1785 
1786   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1787 
1788   /// Determine whether a declaration is visible to name lookup.
1789   bool isVisible(const NamedDecl *D) {
1790     return !D->isHidden() || isVisibleSlow(D);
1791   }
1792 
1793   /// Determine whether any declaration of an entity is visible.
1794   bool
1795   hasVisibleDeclaration(const NamedDecl *D,
1796                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1797     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1798   }
1799   bool hasVisibleDeclarationSlow(const NamedDecl *D,
1800                                  llvm::SmallVectorImpl<Module *> *Modules);
1801 
1802   bool hasVisibleMergedDefinition(NamedDecl *Def);
1803   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1804 
1805   /// Determine if \p D and \p Suggested have a structurally compatible
1806   /// layout as described in C11 6.2.7/1.
1807   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1808 
1809   /// Determine if \p D has a visible definition. If not, suggest a declaration
1810   /// that should be made visible to expose the definition.
1811   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1812                             bool OnlyNeedComplete = false);
1813   bool hasVisibleDefinition(const NamedDecl *D) {
1814     NamedDecl *Hidden;
1815     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1816   }
1817 
1818   /// Determine if the template parameter \p D has a visible default argument.
1819   bool
1820   hasVisibleDefaultArgument(const NamedDecl *D,
1821                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1822 
1823   /// Determine if there is a visible declaration of \p D that is an explicit
1824   /// specialization declaration for a specialization of a template. (For a
1825   /// member specialization, use hasVisibleMemberSpecialization.)
1826   bool hasVisibleExplicitSpecialization(
1827       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1828 
1829   /// Determine if there is a visible declaration of \p D that is a member
1830   /// specialization declaration (as opposed to an instantiated declaration).
1831   bool hasVisibleMemberSpecialization(
1832       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1833 
1834   /// Determine if \p A and \p B are equivalent internal linkage declarations
1835   /// from different modules, and thus an ambiguity error can be downgraded to
1836   /// an extension warning.
1837   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1838                                               const NamedDecl *B);
1839   void diagnoseEquivalentInternalLinkageDeclarations(
1840       SourceLocation Loc, const NamedDecl *D,
1841       ArrayRef<const NamedDecl *> Equiv);
1842 
1843   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1844 
1845   bool isCompleteType(SourceLocation Loc, QualType T) {
1846     return !RequireCompleteTypeImpl(Loc, T, nullptr);
1847   }
1848   bool RequireCompleteType(SourceLocation Loc, QualType T,
1849                            TypeDiagnoser &Diagnoser);
1850   bool RequireCompleteType(SourceLocation Loc, QualType T,
1851                            unsigned DiagID);
1852 
1853   template <typename... Ts>
1854   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1855                            const Ts &...Args) {
1856     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1857     return RequireCompleteType(Loc, T, Diagnoser);
1858   }
1859 
1860   void completeExprArrayBound(Expr *E);
1861   bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1862   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1863 
1864   template <typename... Ts>
1865   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1866     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1867     return RequireCompleteExprType(E, Diagnoser);
1868   }
1869 
1870   bool RequireLiteralType(SourceLocation Loc, QualType T,
1871                           TypeDiagnoser &Diagnoser);
1872   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1873 
1874   template <typename... Ts>
1875   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1876                           const Ts &...Args) {
1877     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1878     return RequireLiteralType(Loc, T, Diagnoser);
1879   }
1880 
1881   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1882                              const CXXScopeSpec &SS, QualType T,
1883                              TagDecl *OwnedTagDecl = nullptr);
1884 
1885   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1886   /// If AsUnevaluated is false, E is treated as though it were an evaluated
1887   /// context, such as when building a type for decltype(auto).
1888   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1889                              bool AsUnevaluated = true);
1890   QualType BuildUnaryTransformType(QualType BaseType,
1891                                    UnaryTransformType::UTTKind UKind,
1892                                    SourceLocation Loc);
1893 
1894   //===--------------------------------------------------------------------===//
1895   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1896   //
1897 
1898   struct SkipBodyInfo {
1899     SkipBodyInfo()
1900         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1901           New(nullptr) {}
1902     bool ShouldSkip;
1903     bool CheckSameAsPrevious;
1904     NamedDecl *Previous;
1905     NamedDecl *New;
1906   };
1907 
1908   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1909 
1910   void DiagnoseUseOfUnimplementedSelectors();
1911 
1912   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1913 
1914   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1915                          Scope *S, CXXScopeSpec *SS = nullptr,
1916                          bool isClassName = false, bool HasTrailingDot = false,
1917                          ParsedType ObjectType = nullptr,
1918                          bool IsCtorOrDtorName = false,
1919                          bool WantNontrivialTypeSourceInfo = false,
1920                          bool IsClassTemplateDeductionContext = true,
1921                          IdentifierInfo **CorrectedII = nullptr);
1922   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1923   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1924   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1925                                SourceLocation IILoc,
1926                                Scope *S,
1927                                CXXScopeSpec *SS,
1928                                ParsedType &SuggestedType,
1929                                bool IsTemplateName = false);
1930 
1931   /// Attempt to behave like MSVC in situations where lookup of an unqualified
1932   /// type name has failed in a dependent context. In these situations, we
1933   /// automatically form a DependentTypeName that will retry lookup in a related
1934   /// scope during instantiation.
1935   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1936                                       SourceLocation NameLoc,
1937                                       bool IsTemplateTypeArg);
1938 
1939   /// Describes the result of the name lookup and resolution performed
1940   /// by \c ClassifyName().
1941   enum NameClassificationKind {
1942     /// This name is not a type or template in this context, but might be
1943     /// something else.
1944     NC_Unknown,
1945     /// Classification failed; an error has been produced.
1946     NC_Error,
1947     /// The name has been typo-corrected to a keyword.
1948     NC_Keyword,
1949     /// The name was classified as a type.
1950     NC_Type,
1951     /// The name was classified as a specific non-type, non-template
1952     /// declaration. ActOnNameClassifiedAsNonType should be called to
1953     /// convert the declaration to an expression.
1954     NC_NonType,
1955     /// The name was classified as an ADL-only function name.
1956     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1957     /// result to an expression.
1958     NC_UndeclaredNonType,
1959     /// The name denotes a member of a dependent type that could not be
1960     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1961     /// convert the result to an expression.
1962     NC_DependentNonType,
1963     /// The name was classified as a non-type, and an expression representing
1964     /// that name has been formed.
1965     NC_ContextIndependentExpr,
1966     /// The name was classified as a template whose specializations are types.
1967     NC_TypeTemplate,
1968     /// The name was classified as a variable template name.
1969     NC_VarTemplate,
1970     /// The name was classified as a function template name.
1971     NC_FunctionTemplate,
1972     /// The name was classified as an ADL-only function template name.
1973     NC_UndeclaredTemplate,
1974     /// The name was classified as a concept name.
1975     NC_Concept,
1976   };
1977 
1978   class NameClassification {
1979     NameClassificationKind Kind;
1980     union {
1981       ExprResult Expr;
1982       NamedDecl *NonTypeDecl;
1983       TemplateName Template;
1984       ParsedType Type;
1985     };
1986 
1987     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1988 
1989   public:
1990     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1991 
1992     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1993 
1994     static NameClassification Error() {
1995       return NameClassification(NC_Error);
1996     }
1997 
1998     static NameClassification Unknown() {
1999       return NameClassification(NC_Unknown);
2000     }
2001 
2002     static NameClassification ContextIndependentExpr(ExprResult E) {
2003       NameClassification Result(NC_ContextIndependentExpr);
2004       Result.Expr = E;
2005       return Result;
2006     }
2007 
2008     static NameClassification NonType(NamedDecl *D) {
2009       NameClassification Result(NC_NonType);
2010       Result.NonTypeDecl = D;
2011       return Result;
2012     }
2013 
2014     static NameClassification UndeclaredNonType() {
2015       return NameClassification(NC_UndeclaredNonType);
2016     }
2017 
2018     static NameClassification DependentNonType() {
2019       return NameClassification(NC_DependentNonType);
2020     }
2021 
2022     static NameClassification TypeTemplate(TemplateName Name) {
2023       NameClassification Result(NC_TypeTemplate);
2024       Result.Template = Name;
2025       return Result;
2026     }
2027 
2028     static NameClassification VarTemplate(TemplateName Name) {
2029       NameClassification Result(NC_VarTemplate);
2030       Result.Template = Name;
2031       return Result;
2032     }
2033 
2034     static NameClassification FunctionTemplate(TemplateName Name) {
2035       NameClassification Result(NC_FunctionTemplate);
2036       Result.Template = Name;
2037       return Result;
2038     }
2039 
2040     static NameClassification Concept(TemplateName Name) {
2041       NameClassification Result(NC_Concept);
2042       Result.Template = Name;
2043       return Result;
2044     }
2045 
2046     static NameClassification UndeclaredTemplate(TemplateName Name) {
2047       NameClassification Result(NC_UndeclaredTemplate);
2048       Result.Template = Name;
2049       return Result;
2050     }
2051 
2052     NameClassificationKind getKind() const { return Kind; }
2053 
2054     ExprResult getExpression() const {
2055       assert(Kind == NC_ContextIndependentExpr);
2056       return Expr;
2057     }
2058 
2059     ParsedType getType() const {
2060       assert(Kind == NC_Type);
2061       return Type;
2062     }
2063 
2064     NamedDecl *getNonTypeDecl() const {
2065       assert(Kind == NC_NonType);
2066       return NonTypeDecl;
2067     }
2068 
2069     TemplateName getTemplateName() const {
2070       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2071              Kind == NC_VarTemplate || Kind == NC_Concept ||
2072              Kind == NC_UndeclaredTemplate);
2073       return Template;
2074     }
2075 
2076     TemplateNameKind getTemplateNameKind() const {
2077       switch (Kind) {
2078       case NC_TypeTemplate:
2079         return TNK_Type_template;
2080       case NC_FunctionTemplate:
2081         return TNK_Function_template;
2082       case NC_VarTemplate:
2083         return TNK_Var_template;
2084       case NC_Concept:
2085         return TNK_Concept_template;
2086       case NC_UndeclaredTemplate:
2087         return TNK_Undeclared_template;
2088       default:
2089         llvm_unreachable("unsupported name classification.");
2090       }
2091     }
2092   };
2093 
2094   /// Perform name lookup on the given name, classifying it based on
2095   /// the results of name lookup and the following token.
2096   ///
2097   /// This routine is used by the parser to resolve identifiers and help direct
2098   /// parsing. When the identifier cannot be found, this routine will attempt
2099   /// to correct the typo and classify based on the resulting name.
2100   ///
2101   /// \param S The scope in which we're performing name lookup.
2102   ///
2103   /// \param SS The nested-name-specifier that precedes the name.
2104   ///
2105   /// \param Name The identifier. If typo correction finds an alternative name,
2106   /// this pointer parameter will be updated accordingly.
2107   ///
2108   /// \param NameLoc The location of the identifier.
2109   ///
2110   /// \param NextToken The token following the identifier. Used to help
2111   /// disambiguate the name.
2112   ///
2113   /// \param CCC The correction callback, if typo correction is desired.
2114   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2115                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2116                                   const Token &NextToken,
2117                                   CorrectionCandidateCallback *CCC = nullptr);
2118 
2119   /// Act on the result of classifying a name as an undeclared (ADL-only)
2120   /// non-type declaration.
2121   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2122                                                     SourceLocation NameLoc);
2123   /// Act on the result of classifying a name as an undeclared member of a
2124   /// dependent base class.
2125   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2126                                                    IdentifierInfo *Name,
2127                                                    SourceLocation NameLoc,
2128                                                    bool IsAddressOfOperand);
2129   /// Act on the result of classifying a name as a specific non-type
2130   /// declaration.
2131   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2132                                           NamedDecl *Found,
2133                                           SourceLocation NameLoc,
2134                                           const Token &NextToken);
2135 
2136   /// Describes the detailed kind of a template name. Used in diagnostics.
2137   enum class TemplateNameKindForDiagnostics {
2138     ClassTemplate,
2139     FunctionTemplate,
2140     VarTemplate,
2141     AliasTemplate,
2142     TemplateTemplateParam,
2143     Concept,
2144     DependentTemplate
2145   };
2146   TemplateNameKindForDiagnostics
2147   getTemplateNameKindForDiagnostics(TemplateName Name);
2148 
2149   /// Determine whether it's plausible that E was intended to be a
2150   /// template-name.
2151   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2152     if (!getLangOpts().CPlusPlus || E.isInvalid())
2153       return false;
2154     Dependent = false;
2155     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2156       return !DRE->hasExplicitTemplateArgs();
2157     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2158       return !ME->hasExplicitTemplateArgs();
2159     Dependent = true;
2160     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2161       return !DSDRE->hasExplicitTemplateArgs();
2162     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2163       return !DSME->hasExplicitTemplateArgs();
2164     // Any additional cases recognized here should also be handled by
2165     // diagnoseExprIntendedAsTemplateName.
2166     return false;
2167   }
2168   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2169                                           SourceLocation Less,
2170                                           SourceLocation Greater);
2171 
2172   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2173 
2174   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2175                               MultiTemplateParamsArg TemplateParameterLists);
2176   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2177   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2178   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2179                                     DeclarationName Name, SourceLocation Loc,
2180                                     bool IsTemplateId);
2181   void
2182   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2183                             SourceLocation FallbackLoc,
2184                             SourceLocation ConstQualLoc = SourceLocation(),
2185                             SourceLocation VolatileQualLoc = SourceLocation(),
2186                             SourceLocation RestrictQualLoc = SourceLocation(),
2187                             SourceLocation AtomicQualLoc = SourceLocation(),
2188                             SourceLocation UnalignedQualLoc = SourceLocation());
2189 
2190   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2191   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2192   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2193                                     const LookupResult &R);
2194   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2195   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2196                    const LookupResult &R);
2197   void CheckShadow(Scope *S, VarDecl *D);
2198 
2199   /// Warn if 'E', which is an expression that is about to be modified, refers
2200   /// to a shadowing declaration.
2201   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2202 
2203   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2204 
2205 private:
2206   /// Map of current shadowing declarations to shadowed declarations. Warn if
2207   /// it looks like the user is trying to modify the shadowing declaration.
2208   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2209 
2210 public:
2211   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2212   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2213   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2214                                     TypedefNameDecl *NewTD);
2215   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2216   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2217                                     TypeSourceInfo *TInfo,
2218                                     LookupResult &Previous);
2219   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2220                                   LookupResult &Previous, bool &Redeclaration);
2221   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2222                                      TypeSourceInfo *TInfo,
2223                                      LookupResult &Previous,
2224                                      MultiTemplateParamsArg TemplateParamLists,
2225                                      bool &AddToScope,
2226                                      ArrayRef<BindingDecl *> Bindings = None);
2227   NamedDecl *
2228   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2229                                MultiTemplateParamsArg TemplateParamLists);
2230   // Returns true if the variable declaration is a redeclaration
2231   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2232   void CheckVariableDeclarationType(VarDecl *NewVD);
2233   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2234                                      Expr *Init);
2235   void CheckCompleteVariableDeclaration(VarDecl *VD);
2236   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2237   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2238 
2239   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2240                                      TypeSourceInfo *TInfo,
2241                                      LookupResult &Previous,
2242                                      MultiTemplateParamsArg TemplateParamLists,
2243                                      bool &AddToScope);
2244   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2245 
2246   enum class CheckConstexprKind {
2247     /// Diagnose issues that are non-constant or that are extensions.
2248     Diagnose,
2249     /// Identify whether this function satisfies the formal rules for constexpr
2250     /// functions in the current lanugage mode (with no extensions).
2251     CheckValid
2252   };
2253 
2254   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2255                                         CheckConstexprKind Kind);
2256 
2257   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2258   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2259                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2260   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2261                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2262   // Returns true if the function declaration is a redeclaration
2263   bool CheckFunctionDeclaration(Scope *S,
2264                                 FunctionDecl *NewFD, LookupResult &Previous,
2265                                 bool IsMemberSpecialization);
2266   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2267   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2268                                       QualType NewT, QualType OldT);
2269   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2270   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2271   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2272                                                    bool IsDefinition);
2273   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2274   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2275   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2276                                           SourceLocation Loc,
2277                                           QualType T);
2278   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2279                               SourceLocation NameLoc, IdentifierInfo *Name,
2280                               QualType T, TypeSourceInfo *TSInfo,
2281                               StorageClass SC);
2282   void ActOnParamDefaultArgument(Decl *param,
2283                                  SourceLocation EqualLoc,
2284                                  Expr *defarg);
2285   void ActOnParamUnparsedDefaultArgument(Decl *param,
2286                                          SourceLocation EqualLoc,
2287                                          SourceLocation ArgLoc);
2288   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2289   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2290                                SourceLocation EqualLoc);
2291 
2292   // Contexts where using non-trivial C union types can be disallowed. This is
2293   // passed to err_non_trivial_c_union_in_invalid_context.
2294   enum NonTrivialCUnionContext {
2295     // Function parameter.
2296     NTCUC_FunctionParam,
2297     // Function return.
2298     NTCUC_FunctionReturn,
2299     // Default-initialized object.
2300     NTCUC_DefaultInitializedObject,
2301     // Variable with automatic storage duration.
2302     NTCUC_AutoVar,
2303     // Initializer expression that might copy from another object.
2304     NTCUC_CopyInit,
2305     // Assignment.
2306     NTCUC_Assignment,
2307     // Compound literal.
2308     NTCUC_CompoundLiteral,
2309     // Block capture.
2310     NTCUC_BlockCapture,
2311     // lvalue-to-rvalue conversion of volatile type.
2312     NTCUC_LValueToRValueVolatile,
2313   };
2314 
2315   /// Emit diagnostics if the initializer or any of its explicit or
2316   /// implicitly-generated subexpressions require copying or
2317   /// default-initializing a type that is or contains a C union type that is
2318   /// non-trivial to copy or default-initialize.
2319   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2320 
2321   // These flags are passed to checkNonTrivialCUnion.
2322   enum NonTrivialCUnionKind {
2323     NTCUK_Init = 0x1,
2324     NTCUK_Destruct = 0x2,
2325     NTCUK_Copy = 0x4,
2326   };
2327 
2328   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2329   /// a non-trivial C union is used in an invalid context.
2330   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2331                              NonTrivialCUnionContext UseContext,
2332                              unsigned NonTrivialKind);
2333 
2334   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2335   void ActOnUninitializedDecl(Decl *dcl);
2336   void ActOnInitializerError(Decl *Dcl);
2337 
2338   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2339   void ActOnCXXForRangeDecl(Decl *D);
2340   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2341                                         IdentifierInfo *Ident,
2342                                         ParsedAttributes &Attrs,
2343                                         SourceLocation AttrEnd);
2344   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2345   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2346   void CheckStaticLocalForDllExport(VarDecl *VD);
2347   void FinalizeDeclaration(Decl *D);
2348   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2349                                          ArrayRef<Decl *> Group);
2350   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2351 
2352   /// Should be called on all declarations that might have attached
2353   /// documentation comments.
2354   void ActOnDocumentableDecl(Decl *D);
2355   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2356 
2357   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2358                                        SourceLocation LocAfterDecls);
2359   void CheckForFunctionRedefinition(
2360       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2361       SkipBodyInfo *SkipBody = nullptr);
2362   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2363                                 MultiTemplateParamsArg TemplateParamLists,
2364                                 SkipBodyInfo *SkipBody = nullptr);
2365   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2366                                 SkipBodyInfo *SkipBody = nullptr);
2367   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2368   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2369   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2370   bool isObjCMethodDecl(Decl *D) {
2371     return D && isa<ObjCMethodDecl>(D);
2372   }
2373 
2374   /// Determine whether we can delay parsing the body of a function or
2375   /// function template until it is used, assuming we don't care about emitting
2376   /// code for that function.
2377   ///
2378   /// This will be \c false if we may need the body of the function in the
2379   /// middle of parsing an expression (where it's impractical to switch to
2380   /// parsing a different function), for instance, if it's constexpr in C++11
2381   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2382   bool canDelayFunctionBody(const Declarator &D);
2383 
2384   /// Determine whether we can skip parsing the body of a function
2385   /// definition, assuming we don't care about analyzing its body or emitting
2386   /// code for that function.
2387   ///
2388   /// This will be \c false only if we may need the body of the function in
2389   /// order to parse the rest of the program (for instance, if it is
2390   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2391   bool canSkipFunctionBody(Decl *D);
2392 
2393   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2394   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2395   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2396   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2397   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2398 
2399   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2400   /// attribute for which parsing is delayed.
2401   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2402 
2403   /// Diagnose any unused parameters in the given sequence of
2404   /// ParmVarDecl pointers.
2405   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2406 
2407   /// Diagnose whether the size of parameters or return value of a
2408   /// function or obj-c method definition is pass-by-value and larger than a
2409   /// specified threshold.
2410   void
2411   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2412                                          QualType ReturnTy, NamedDecl *D);
2413 
2414   void DiagnoseInvalidJumps(Stmt *Body);
2415   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2416                               SourceLocation AsmLoc,
2417                               SourceLocation RParenLoc);
2418 
2419   /// Handle a C++11 empty-declaration and attribute-declaration.
2420   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2421                               SourceLocation SemiLoc);
2422 
2423   enum class ModuleDeclKind {
2424     Interface,      ///< 'export module X;'
2425     Implementation, ///< 'module X;'
2426   };
2427 
2428   /// The parser has processed a module-declaration that begins the definition
2429   /// of a module interface or implementation.
2430   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2431                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2432                                  ModuleIdPath Path, bool IsFirstDecl);
2433 
2434   /// The parser has processed a global-module-fragment declaration that begins
2435   /// the definition of the global module fragment of the current module unit.
2436   /// \param ModuleLoc The location of the 'module' keyword.
2437   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2438 
2439   /// The parser has processed a private-module-fragment declaration that begins
2440   /// the definition of the private module fragment of the current module unit.
2441   /// \param ModuleLoc The location of the 'module' keyword.
2442   /// \param PrivateLoc The location of the 'private' keyword.
2443   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2444                                                 SourceLocation PrivateLoc);
2445 
2446   /// The parser has processed a module import declaration.
2447   ///
2448   /// \param StartLoc The location of the first token in the declaration. This
2449   ///        could be the location of an '@', 'export', or 'import'.
2450   /// \param ExportLoc The location of the 'export' keyword, if any.
2451   /// \param ImportLoc The location of the 'import' keyword.
2452   /// \param Path The module access path.
2453   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2454                                SourceLocation ExportLoc,
2455                                SourceLocation ImportLoc, ModuleIdPath Path);
2456   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2457                                SourceLocation ExportLoc,
2458                                SourceLocation ImportLoc, Module *M,
2459                                ModuleIdPath Path = {});
2460 
2461   /// The parser has processed a module import translated from a
2462   /// #include or similar preprocessing directive.
2463   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2464   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2465 
2466   /// The parsed has entered a submodule.
2467   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2468   /// The parser has left a submodule.
2469   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2470 
2471   /// Create an implicit import of the given module at the given
2472   /// source location, for error recovery, if possible.
2473   ///
2474   /// This routine is typically used when an entity found by name lookup
2475   /// is actually hidden within a module that we know about but the user
2476   /// has forgotten to import.
2477   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2478                                                   Module *Mod);
2479 
2480   /// Kinds of missing import. Note, the values of these enumerators correspond
2481   /// to %select values in diagnostics.
2482   enum class MissingImportKind {
2483     Declaration,
2484     Definition,
2485     DefaultArgument,
2486     ExplicitSpecialization,
2487     PartialSpecialization
2488   };
2489 
2490   /// Diagnose that the specified declaration needs to be visible but
2491   /// isn't, and suggest a module import that would resolve the problem.
2492   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2493                              MissingImportKind MIK, bool Recover = true);
2494   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2495                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2496                              MissingImportKind MIK, bool Recover);
2497 
2498   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2499                              SourceLocation LBraceLoc);
2500   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2501                               SourceLocation RBraceLoc);
2502 
2503   /// We've found a use of a templated declaration that would trigger an
2504   /// implicit instantiation. Check that any relevant explicit specializations
2505   /// and partial specializations are visible, and diagnose if not.
2506   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2507 
2508   /// We've found a use of a template specialization that would select a
2509   /// partial specialization. Check that the partial specialization is visible,
2510   /// and diagnose if not.
2511   void checkPartialSpecializationVisibility(SourceLocation Loc,
2512                                             NamedDecl *Spec);
2513 
2514   /// Retrieve a suitable printing policy for diagnostics.
2515   PrintingPolicy getPrintingPolicy() const {
2516     return getPrintingPolicy(Context, PP);
2517   }
2518 
2519   /// Retrieve a suitable printing policy for diagnostics.
2520   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2521                                           const Preprocessor &PP);
2522 
2523   /// Scope actions.
2524   void ActOnPopScope(SourceLocation Loc, Scope *S);
2525   void ActOnTranslationUnitScope(Scope *S);
2526 
2527   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2528                                    RecordDecl *&AnonRecord);
2529   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2530                                    MultiTemplateParamsArg TemplateParams,
2531                                    bool IsExplicitInstantiation,
2532                                    RecordDecl *&AnonRecord);
2533 
2534   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2535                                     AccessSpecifier AS,
2536                                     RecordDecl *Record,
2537                                     const PrintingPolicy &Policy);
2538 
2539   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2540                                        RecordDecl *Record);
2541 
2542   /// Common ways to introduce type names without a tag for use in diagnostics.
2543   /// Keep in sync with err_tag_reference_non_tag.
2544   enum NonTagKind {
2545     NTK_NonStruct,
2546     NTK_NonClass,
2547     NTK_NonUnion,
2548     NTK_NonEnum,
2549     NTK_Typedef,
2550     NTK_TypeAlias,
2551     NTK_Template,
2552     NTK_TypeAliasTemplate,
2553     NTK_TemplateTemplateArgument,
2554   };
2555 
2556   /// Given a non-tag type declaration, returns an enum useful for indicating
2557   /// what kind of non-tag type this is.
2558   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2559 
2560   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2561                                     TagTypeKind NewTag, bool isDefinition,
2562                                     SourceLocation NewTagLoc,
2563                                     const IdentifierInfo *Name);
2564 
2565   enum TagUseKind {
2566     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
2567     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
2568     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
2569     TUK_Friend       // Friend declaration:  'friend struct foo;'
2570   };
2571 
2572   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2573                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2574                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2575                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2576                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2577                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2578                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2579                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2580                  SkipBodyInfo *SkipBody = nullptr);
2581 
2582   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2583                                 unsigned TagSpec, SourceLocation TagLoc,
2584                                 CXXScopeSpec &SS, IdentifierInfo *Name,
2585                                 SourceLocation NameLoc,
2586                                 const ParsedAttributesView &Attr,
2587                                 MultiTemplateParamsArg TempParamLists);
2588 
2589   TypeResult ActOnDependentTag(Scope *S,
2590                                unsigned TagSpec,
2591                                TagUseKind TUK,
2592                                const CXXScopeSpec &SS,
2593                                IdentifierInfo *Name,
2594                                SourceLocation TagLoc,
2595                                SourceLocation NameLoc);
2596 
2597   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2598                  IdentifierInfo *ClassName,
2599                  SmallVectorImpl<Decl *> &Decls);
2600   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2601                    Declarator &D, Expr *BitfieldWidth);
2602 
2603   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2604                          Declarator &D, Expr *BitfieldWidth,
2605                          InClassInitStyle InitStyle,
2606                          AccessSpecifier AS);
2607   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2608                                    SourceLocation DeclStart, Declarator &D,
2609                                    Expr *BitfieldWidth,
2610                                    InClassInitStyle InitStyle,
2611                                    AccessSpecifier AS,
2612                                    const ParsedAttr &MSPropertyAttr);
2613 
2614   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2615                             TypeSourceInfo *TInfo,
2616                             RecordDecl *Record, SourceLocation Loc,
2617                             bool Mutable, Expr *BitfieldWidth,
2618                             InClassInitStyle InitStyle,
2619                             SourceLocation TSSL,
2620                             AccessSpecifier AS, NamedDecl *PrevDecl,
2621                             Declarator *D = nullptr);
2622 
2623   bool CheckNontrivialField(FieldDecl *FD);
2624   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2625 
2626   enum TrivialABIHandling {
2627     /// The triviality of a method unaffected by "trivial_abi".
2628     TAH_IgnoreTrivialABI,
2629 
2630     /// The triviality of a method affected by "trivial_abi".
2631     TAH_ConsiderTrivialABI
2632   };
2633 
2634   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2635                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2636                               bool Diagnose = false);
2637 
2638   /// For a defaulted function, the kind of defaulted function that it is.
2639   class DefaultedFunctionKind {
2640     CXXSpecialMember SpecialMember : 8;
2641     DefaultedComparisonKind Comparison : 8;
2642 
2643   public:
2644     DefaultedFunctionKind()
2645         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2646     }
2647     DefaultedFunctionKind(CXXSpecialMember CSM)
2648         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2649     DefaultedFunctionKind(DefaultedComparisonKind Comp)
2650         : SpecialMember(CXXInvalid), Comparison(Comp) {}
2651 
2652     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2653     bool isComparison() const {
2654       return Comparison != DefaultedComparisonKind::None;
2655     }
2656 
2657     explicit operator bool() const {
2658       return isSpecialMember() || isComparison();
2659     }
2660 
2661     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2662     DefaultedComparisonKind asComparison() const { return Comparison; }
2663 
2664     /// Get the index of this function kind for use in diagnostics.
2665     unsigned getDiagnosticIndex() const {
2666       static_assert(CXXInvalid > CXXDestructor,
2667                     "invalid should have highest index");
2668       static_assert((unsigned)DefaultedComparisonKind::None == 0,
2669                     "none should be equal to zero");
2670       return SpecialMember + (unsigned)Comparison;
2671     }
2672   };
2673 
2674   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2675 
2676   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2677     return getDefaultedFunctionKind(MD).asSpecialMember();
2678   }
2679   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2680     return getDefaultedFunctionKind(FD).asComparison();
2681   }
2682 
2683   void ActOnLastBitfield(SourceLocation DeclStart,
2684                          SmallVectorImpl<Decl *> &AllIvarDecls);
2685   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2686                   Declarator &D, Expr *BitfieldWidth,
2687                   tok::ObjCKeywordKind visibility);
2688 
2689   // This is used for both record definitions and ObjC interface declarations.
2690   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2691                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
2692                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
2693 
2694   /// ActOnTagStartDefinition - Invoked when we have entered the
2695   /// scope of a tag's definition (e.g., for an enumeration, class,
2696   /// struct, or union).
2697   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2698 
2699   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2700   /// Differently from C++, actually parse the body and reject / error out
2701   /// in case of a structural mismatch.
2702   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2703                                 SkipBodyInfo &SkipBody);
2704 
2705   typedef void *SkippedDefinitionContext;
2706 
2707   /// Invoked when we enter a tag definition that we're skipping.
2708   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2709 
2710   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2711 
2712   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2713   /// C++ record definition's base-specifiers clause and are starting its
2714   /// member declarations.
2715   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2716                                        SourceLocation FinalLoc,
2717                                        bool IsFinalSpelledSealed,
2718                                        SourceLocation LBraceLoc);
2719 
2720   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2721   /// the definition of a tag (enumeration, class, struct, or union).
2722   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2723                                 SourceRange BraceRange);
2724 
2725   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2726 
2727   void ActOnObjCContainerFinishDefinition();
2728 
2729   /// Invoked when we must temporarily exit the objective-c container
2730   /// scope for parsing/looking-up C constructs.
2731   ///
2732   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2733   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2734   void ActOnObjCReenterContainerContext(DeclContext *DC);
2735 
2736   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2737   /// error parsing the definition of a tag.
2738   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2739 
2740   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2741                                       EnumConstantDecl *LastEnumConst,
2742                                       SourceLocation IdLoc,
2743                                       IdentifierInfo *Id,
2744                                       Expr *val);
2745   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2746   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2747                               QualType EnumUnderlyingTy, bool IsFixed,
2748                               const EnumDecl *Prev);
2749 
2750   /// Determine whether the body of an anonymous enumeration should be skipped.
2751   /// \param II The name of the first enumerator.
2752   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2753                                       SourceLocation IILoc);
2754 
2755   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2756                           SourceLocation IdLoc, IdentifierInfo *Id,
2757                           const ParsedAttributesView &Attrs,
2758                           SourceLocation EqualLoc, Expr *Val);
2759   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2760                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2761                      const ParsedAttributesView &Attr);
2762 
2763   DeclContext *getContainingDC(DeclContext *DC);
2764 
2765   /// Set the current declaration context until it gets popped.
2766   void PushDeclContext(Scope *S, DeclContext *DC);
2767   void PopDeclContext();
2768 
2769   /// EnterDeclaratorContext - Used when we must lookup names in the context
2770   /// of a declarator's nested name specifier.
2771   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2772   void ExitDeclaratorContext(Scope *S);
2773 
2774   /// Push the parameters of D, which must be a function, into scope.
2775   void ActOnReenterFunctionContext(Scope* S, Decl* D);
2776   void ActOnExitFunctionContext();
2777 
2778   DeclContext *getFunctionLevelDeclContext();
2779 
2780   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2781   /// to the function decl for the function being parsed.  If we're currently
2782   /// in a 'block', this returns the containing context.
2783   FunctionDecl *getCurFunctionDecl();
2784 
2785   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2786   /// the method decl for the method being parsed.  If we're currently
2787   /// in a 'block', this returns the containing context.
2788   ObjCMethodDecl *getCurMethodDecl();
2789 
2790   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2791   /// or C function we're in, otherwise return null.  If we're currently
2792   /// in a 'block', this returns the containing context.
2793   NamedDecl *getCurFunctionOrMethodDecl();
2794 
2795   /// Add this decl to the scope shadowed decl chains.
2796   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2797 
2798   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2799   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2800   /// true if 'D' belongs to the given declaration context.
2801   ///
2802   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2803   ///        enclosing namespace set of the context, rather than contained
2804   ///        directly within it.
2805   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2806                      bool AllowInlineNamespace = false);
2807 
2808   /// Finds the scope corresponding to the given decl context, if it
2809   /// happens to be an enclosing scope.  Otherwise return NULL.
2810   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2811 
2812   /// Subroutines of ActOnDeclarator().
2813   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2814                                 TypeSourceInfo *TInfo);
2815   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2816 
2817   /// Describes the kind of merge to perform for availability
2818   /// attributes (including "deprecated", "unavailable", and "availability").
2819   enum AvailabilityMergeKind {
2820     /// Don't merge availability attributes at all.
2821     AMK_None,
2822     /// Merge availability attributes for a redeclaration, which requires
2823     /// an exact match.
2824     AMK_Redeclaration,
2825     /// Merge availability attributes for an override, which requires
2826     /// an exact match or a weakening of constraints.
2827     AMK_Override,
2828     /// Merge availability attributes for an implementation of
2829     /// a protocol requirement.
2830     AMK_ProtocolImplementation,
2831   };
2832 
2833   /// Describes the kind of priority given to an availability attribute.
2834   ///
2835   /// The sum of priorities deteremines the final priority of the attribute.
2836   /// The final priority determines how the attribute will be merged.
2837   /// An attribute with a lower priority will always remove higher priority
2838   /// attributes for the specified platform when it is being applied. An
2839   /// attribute with a higher priority will not be applied if the declaration
2840   /// already has an availability attribute with a lower priority for the
2841   /// specified platform. The final prirority values are not expected to match
2842   /// the values in this enumeration, but instead should be treated as a plain
2843   /// integer value. This enumeration just names the priority weights that are
2844   /// used to calculate that final vaue.
2845   enum AvailabilityPriority : int {
2846     /// The availability attribute was specified explicitly next to the
2847     /// declaration.
2848     AP_Explicit = 0,
2849 
2850     /// The availability attribute was applied using '#pragma clang attribute'.
2851     AP_PragmaClangAttribute = 1,
2852 
2853     /// The availability attribute for a specific platform was inferred from
2854     /// an availability attribute for another platform.
2855     AP_InferredFromOtherPlatform = 2
2856   };
2857 
2858   /// Attribute merging methods. Return true if a new attribute was added.
2859   AvailabilityAttr *
2860   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2861                         IdentifierInfo *Platform, bool Implicit,
2862                         VersionTuple Introduced, VersionTuple Deprecated,
2863                         VersionTuple Obsoleted, bool IsUnavailable,
2864                         StringRef Message, bool IsStrict, StringRef Replacement,
2865                         AvailabilityMergeKind AMK, int Priority);
2866   TypeVisibilityAttr *
2867   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2868                           TypeVisibilityAttr::VisibilityType Vis);
2869   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2870                                       VisibilityAttr::VisibilityType Vis);
2871   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2872                           StringRef Uuid);
2873   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2874   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2875   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
2876                                             const AttributeCommonInfo &CI,
2877                                             bool BestCase,
2878                                             MSInheritanceModel Model);
2879   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2880                               IdentifierInfo *Format, int FormatIdx,
2881                               int FirstArg);
2882   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2883                                 StringRef Name);
2884   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2885                                 StringRef Name);
2886   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2887                                           const AttributeCommonInfo &CI,
2888                                           const IdentifierInfo *Ident);
2889   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2890   NoSpeculativeLoadHardeningAttr *
2891   mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2892                                       const NoSpeculativeLoadHardeningAttr &AL);
2893   SpeculativeLoadHardeningAttr *
2894   mergeSpeculativeLoadHardeningAttr(Decl *D,
2895                                     const SpeculativeLoadHardeningAttr &AL);
2896   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2897                                           const AttributeCommonInfo &CI);
2898   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2899   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2900                                                 const InternalLinkageAttr &AL);
2901   CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2902   CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2903 
2904   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2905                            AvailabilityMergeKind AMK = AMK_Redeclaration);
2906   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2907                             LookupResult &OldDecls);
2908   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2909                          bool MergeTypeWithOld);
2910   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2911                                     Scope *S, bool MergeTypeWithOld);
2912   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2913   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2914   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2915   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2916   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2917   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2918   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2919 
2920   // AssignmentAction - This is used by all the assignment diagnostic functions
2921   // to represent what is actually causing the operation
2922   enum AssignmentAction {
2923     AA_Assigning,
2924     AA_Passing,
2925     AA_Returning,
2926     AA_Converting,
2927     AA_Initializing,
2928     AA_Sending,
2929     AA_Casting,
2930     AA_Passing_CFAudited
2931   };
2932 
2933   /// C++ Overloading.
2934   enum OverloadKind {
2935     /// This is a legitimate overload: the existing declarations are
2936     /// functions or function templates with different signatures.
2937     Ovl_Overload,
2938 
2939     /// This is not an overload because the signature exactly matches
2940     /// an existing declaration.
2941     Ovl_Match,
2942 
2943     /// This is not an overload because the lookup results contain a
2944     /// non-function.
2945     Ovl_NonFunction
2946   };
2947   OverloadKind CheckOverload(Scope *S,
2948                              FunctionDecl *New,
2949                              const LookupResult &OldDecls,
2950                              NamedDecl *&OldDecl,
2951                              bool IsForUsingDecl);
2952   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2953                   bool ConsiderCudaAttrs = true,
2954                   bool ConsiderRequiresClauses = true);
2955 
2956   ImplicitConversionSequence
2957   TryImplicitConversion(Expr *From, QualType ToType,
2958                         bool SuppressUserConversions,
2959                         bool AllowExplicit,
2960                         bool InOverloadResolution,
2961                         bool CStyle,
2962                         bool AllowObjCWritebackConversion);
2963 
2964   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2965   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2966   bool IsComplexPromotion(QualType FromType, QualType ToType);
2967   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2968                            bool InOverloadResolution,
2969                            QualType& ConvertedType, bool &IncompatibleObjC);
2970   bool isObjCPointerConversion(QualType FromType, QualType ToType,
2971                                QualType& ConvertedType, bool &IncompatibleObjC);
2972   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2973                                  QualType &ConvertedType);
2974   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2975                                 QualType& ConvertedType);
2976   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2977                                   const FunctionProtoType *NewType,
2978                                   unsigned *ArgPos = nullptr);
2979   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2980                                   QualType FromType, QualType ToType);
2981 
2982   void maybeExtendBlockObject(ExprResult &E);
2983   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2984   bool CheckPointerConversion(Expr *From, QualType ToType,
2985                               CastKind &Kind,
2986                               CXXCastPath& BasePath,
2987                               bool IgnoreBaseAccess,
2988                               bool Diagnose = true);
2989   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2990                                  bool InOverloadResolution,
2991                                  QualType &ConvertedType);
2992   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2993                                     CastKind &Kind,
2994                                     CXXCastPath &BasePath,
2995                                     bool IgnoreBaseAccess);
2996   bool IsQualificationConversion(QualType FromType, QualType ToType,
2997                                  bool CStyle, bool &ObjCLifetimeConversion);
2998   bool IsFunctionConversion(QualType FromType, QualType ToType,
2999                             QualType &ResultTy);
3000   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3001   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3002 
3003   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3004                                              const VarDecl *NRVOCandidate,
3005                                              QualType ResultType,
3006                                              Expr *Value,
3007                                              bool AllowNRVO = true);
3008 
3009   bool CanPerformAggregateInitializationForOverloadResolution(
3010       const InitializedEntity &Entity, InitListExpr *From);
3011 
3012   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3013                                     ExprResult Init);
3014   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3015                                        SourceLocation EqualLoc,
3016                                        ExprResult Init,
3017                                        bool TopLevelOfInitList = false,
3018                                        bool AllowExplicit = false);
3019   ExprResult PerformObjectArgumentInitialization(Expr *From,
3020                                                  NestedNameSpecifier *Qualifier,
3021                                                  NamedDecl *FoundDecl,
3022                                                  CXXMethodDecl *Method);
3023 
3024   /// Check that the lifetime of the initializer (and its subobjects) is
3025   /// sufficient for initializing the entity, and perform lifetime extension
3026   /// (when permitted) if not.
3027   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3028 
3029   ExprResult PerformContextuallyConvertToBool(Expr *From);
3030   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3031 
3032   /// Contexts in which a converted constant expression is required.
3033   enum CCEKind {
3034     CCEK_CaseValue,   ///< Expression in a case label.
3035     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
3036     CCEK_TemplateArg, ///< Value of a non-type template parameter.
3037     CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
3038     CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3039     CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3040   };
3041   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3042                                               llvm::APSInt &Value, CCEKind CCE);
3043   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3044                                               APValue &Value, CCEKind CCE);
3045 
3046   /// Abstract base class used to perform a contextual implicit
3047   /// conversion from an expression to any type passing a filter.
3048   class ContextualImplicitConverter {
3049   public:
3050     bool Suppress;
3051     bool SuppressConversion;
3052 
3053     ContextualImplicitConverter(bool Suppress = false,
3054                                 bool SuppressConversion = false)
3055         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3056 
3057     /// Determine whether the specified type is a valid destination type
3058     /// for this conversion.
3059     virtual bool match(QualType T) = 0;
3060 
3061     /// Emits a diagnostic complaining that the expression does not have
3062     /// integral or enumeration type.
3063     virtual SemaDiagnosticBuilder
3064     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3065 
3066     /// Emits a diagnostic when the expression has incomplete class type.
3067     virtual SemaDiagnosticBuilder
3068     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3069 
3070     /// Emits a diagnostic when the only matching conversion function
3071     /// is explicit.
3072     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3073         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3074 
3075     /// Emits a note for the explicit conversion function.
3076     virtual SemaDiagnosticBuilder
3077     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3078 
3079     /// Emits a diagnostic when there are multiple possible conversion
3080     /// functions.
3081     virtual SemaDiagnosticBuilder
3082     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3083 
3084     /// Emits a note for one of the candidate conversions.
3085     virtual SemaDiagnosticBuilder
3086     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3087 
3088     /// Emits a diagnostic when we picked a conversion function
3089     /// (for cases when we are not allowed to pick a conversion function).
3090     virtual SemaDiagnosticBuilder diagnoseConversion(
3091         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3092 
3093     virtual ~ContextualImplicitConverter() {}
3094   };
3095 
3096   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3097     bool AllowScopedEnumerations;
3098 
3099   public:
3100     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3101                         bool Suppress, bool SuppressConversion)
3102         : ContextualImplicitConverter(Suppress, SuppressConversion),
3103           AllowScopedEnumerations(AllowScopedEnumerations) {}
3104 
3105     /// Match an integral or (possibly scoped) enumeration type.
3106     bool match(QualType T) override;
3107 
3108     SemaDiagnosticBuilder
3109     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3110       return diagnoseNotInt(S, Loc, T);
3111     }
3112 
3113     /// Emits a diagnostic complaining that the expression does not have
3114     /// integral or enumeration type.
3115     virtual SemaDiagnosticBuilder
3116     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3117   };
3118 
3119   /// Perform a contextual implicit conversion.
3120   ExprResult PerformContextualImplicitConversion(
3121       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3122 
3123 
3124   enum ObjCSubscriptKind {
3125     OS_Array,
3126     OS_Dictionary,
3127     OS_Error
3128   };
3129   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3130 
3131   // Note that LK_String is intentionally after the other literals, as
3132   // this is used for diagnostics logic.
3133   enum ObjCLiteralKind {
3134     LK_Array,
3135     LK_Dictionary,
3136     LK_Numeric,
3137     LK_Boxed,
3138     LK_String,
3139     LK_Block,
3140     LK_None
3141   };
3142   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3143 
3144   ExprResult PerformObjectMemberConversion(Expr *From,
3145                                            NestedNameSpecifier *Qualifier,
3146                                            NamedDecl *FoundDecl,
3147                                            NamedDecl *Member);
3148 
3149   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3150   // TODO: make this is a typesafe union.
3151   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3152   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3153 
3154   using ADLCallKind = CallExpr::ADLCallKind;
3155 
3156   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3157                             ArrayRef<Expr *> Args,
3158                             OverloadCandidateSet &CandidateSet,
3159                             bool SuppressUserConversions = false,
3160                             bool PartialOverloading = false,
3161                             bool AllowExplicit = true,
3162                             bool AllowExplicitConversion = false,
3163                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3164                             ConversionSequenceList EarlyConversions = None,
3165                             OverloadCandidateParamOrder PO = {});
3166   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3167                       ArrayRef<Expr *> Args,
3168                       OverloadCandidateSet &CandidateSet,
3169                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3170                       bool SuppressUserConversions = false,
3171                       bool PartialOverloading = false,
3172                       bool FirstArgumentIsBase = false);
3173   void AddMethodCandidate(DeclAccessPair FoundDecl,
3174                           QualType ObjectType,
3175                           Expr::Classification ObjectClassification,
3176                           ArrayRef<Expr *> Args,
3177                           OverloadCandidateSet& CandidateSet,
3178                           bool SuppressUserConversion = false,
3179                           OverloadCandidateParamOrder PO = {});
3180   void AddMethodCandidate(CXXMethodDecl *Method,
3181                           DeclAccessPair FoundDecl,
3182                           CXXRecordDecl *ActingContext, QualType ObjectType,
3183                           Expr::Classification ObjectClassification,
3184                           ArrayRef<Expr *> Args,
3185                           OverloadCandidateSet& CandidateSet,
3186                           bool SuppressUserConversions = false,
3187                           bool PartialOverloading = false,
3188                           ConversionSequenceList EarlyConversions = None,
3189                           OverloadCandidateParamOrder PO = {});
3190   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3191                                   DeclAccessPair FoundDecl,
3192                                   CXXRecordDecl *ActingContext,
3193                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3194                                   QualType ObjectType,
3195                                   Expr::Classification ObjectClassification,
3196                                   ArrayRef<Expr *> Args,
3197                                   OverloadCandidateSet& CandidateSet,
3198                                   bool SuppressUserConversions = false,
3199                                   bool PartialOverloading = false,
3200                                   OverloadCandidateParamOrder PO = {});
3201   void AddTemplateOverloadCandidate(
3202       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3203       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3204       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3205       bool PartialOverloading = false, bool AllowExplicit = true,
3206       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3207       OverloadCandidateParamOrder PO = {});
3208   bool CheckNonDependentConversions(
3209       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3210       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3211       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3212       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3213       Expr::Classification ObjectClassification = {},
3214       OverloadCandidateParamOrder PO = {});
3215   void AddConversionCandidate(
3216       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3217       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3218       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3219       bool AllowExplicit, bool AllowResultConversion = true);
3220   void AddTemplateConversionCandidate(
3221       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3222       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3223       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3224       bool AllowExplicit, bool AllowResultConversion = true);
3225   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3226                              DeclAccessPair FoundDecl,
3227                              CXXRecordDecl *ActingContext,
3228                              const FunctionProtoType *Proto,
3229                              Expr *Object, ArrayRef<Expr *> Args,
3230                              OverloadCandidateSet& CandidateSet);
3231   void AddNonMemberOperatorCandidates(
3232       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3233       OverloadCandidateSet &CandidateSet,
3234       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3235   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3236                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3237                                    OverloadCandidateSet &CandidateSet,
3238                                    OverloadCandidateParamOrder PO = {});
3239   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3240                            OverloadCandidateSet& CandidateSet,
3241                            bool IsAssignmentOperator = false,
3242                            unsigned NumContextualBoolArguments = 0);
3243   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3244                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3245                                     OverloadCandidateSet& CandidateSet);
3246   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3247                                             SourceLocation Loc,
3248                                             ArrayRef<Expr *> Args,
3249                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3250                                             OverloadCandidateSet& CandidateSet,
3251                                             bool PartialOverloading = false);
3252 
3253   // Emit as a 'note' the specific overload candidate
3254   void NoteOverloadCandidate(
3255       NamedDecl *Found, FunctionDecl *Fn,
3256       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3257       QualType DestType = QualType(), bool TakingAddress = false);
3258 
3259   // Emit as a series of 'note's all template and non-templates identified by
3260   // the expression Expr
3261   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3262                                  bool TakingAddress = false);
3263 
3264   /// Check the enable_if expressions on the given function. Returns the first
3265   /// failing attribute, or NULL if they were all successful.
3266   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3267                               bool MissingImplicitThis = false);
3268 
3269   /// Find the failed Boolean condition within a given Boolean
3270   /// constant expression, and describe it with a string.
3271   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3272 
3273   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3274   /// non-ArgDependent DiagnoseIfAttrs.
3275   ///
3276   /// Argument-dependent diagnose_if attributes should be checked each time a
3277   /// function is used as a direct callee of a function call.
3278   ///
3279   /// Returns true if any errors were emitted.
3280   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3281                                            const Expr *ThisArg,
3282                                            ArrayRef<const Expr *> Args,
3283                                            SourceLocation Loc);
3284 
3285   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3286   /// ArgDependent DiagnoseIfAttrs.
3287   ///
3288   /// Argument-independent diagnose_if attributes should be checked on every use
3289   /// of a function.
3290   ///
3291   /// Returns true if any errors were emitted.
3292   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3293                                              SourceLocation Loc);
3294 
3295   /// Returns whether the given function's address can be taken or not,
3296   /// optionally emitting a diagnostic if the address can't be taken.
3297   ///
3298   /// Returns false if taking the address of the function is illegal.
3299   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3300                                          bool Complain = false,
3301                                          SourceLocation Loc = SourceLocation());
3302 
3303   // [PossiblyAFunctionType]  -->   [Return]
3304   // NonFunctionType --> NonFunctionType
3305   // R (A) --> R(A)
3306   // R (*)(A) --> R (A)
3307   // R (&)(A) --> R (A)
3308   // R (S::*)(A) --> R (A)
3309   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3310 
3311   FunctionDecl *
3312   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3313                                      QualType TargetType,
3314                                      bool Complain,
3315                                      DeclAccessPair &Found,
3316                                      bool *pHadMultipleCandidates = nullptr);
3317 
3318   FunctionDecl *
3319   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3320 
3321   bool resolveAndFixAddressOfSingleOverloadCandidate(
3322       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3323 
3324   FunctionDecl *
3325   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3326                                               bool Complain = false,
3327                                               DeclAccessPair *Found = nullptr);
3328 
3329   bool ResolveAndFixSingleFunctionTemplateSpecialization(
3330                       ExprResult &SrcExpr,
3331                       bool DoFunctionPointerConverion = false,
3332                       bool Complain = false,
3333                       SourceRange OpRangeForComplaining = SourceRange(),
3334                       QualType DestTypeForComplaining = QualType(),
3335                       unsigned DiagIDForComplaining = 0);
3336 
3337 
3338   Expr *FixOverloadedFunctionReference(Expr *E,
3339                                        DeclAccessPair FoundDecl,
3340                                        FunctionDecl *Fn);
3341   ExprResult FixOverloadedFunctionReference(ExprResult,
3342                                             DeclAccessPair FoundDecl,
3343                                             FunctionDecl *Fn);
3344 
3345   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3346                                    ArrayRef<Expr *> Args,
3347                                    OverloadCandidateSet &CandidateSet,
3348                                    bool PartialOverloading = false);
3349 
3350   // An enum used to represent the different possible results of building a
3351   // range-based for loop.
3352   enum ForRangeStatus {
3353     FRS_Success,
3354     FRS_NoViableFunction,
3355     FRS_DiagnosticIssued
3356   };
3357 
3358   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3359                                            SourceLocation RangeLoc,
3360                                            const DeclarationNameInfo &NameInfo,
3361                                            LookupResult &MemberLookup,
3362                                            OverloadCandidateSet *CandidateSet,
3363                                            Expr *Range, ExprResult *CallExpr);
3364 
3365   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3366                                      UnresolvedLookupExpr *ULE,
3367                                      SourceLocation LParenLoc,
3368                                      MultiExprArg Args,
3369                                      SourceLocation RParenLoc,
3370                                      Expr *ExecConfig,
3371                                      bool AllowTypoCorrection=true,
3372                                      bool CalleesAddressIsTaken=false);
3373 
3374   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3375                               MultiExprArg Args, SourceLocation RParenLoc,
3376                               OverloadCandidateSet *CandidateSet,
3377                               ExprResult *Result);
3378 
3379   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3380                                      UnaryOperatorKind Opc,
3381                                      const UnresolvedSetImpl &Fns,
3382                                      Expr *input, bool RequiresADL = true);
3383 
3384   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3385                              OverloadedOperatorKind Op,
3386                              const UnresolvedSetImpl &Fns,
3387                              ArrayRef<Expr *> Args, bool RequiresADL = true);
3388   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3389                                    BinaryOperatorKind Opc,
3390                                    const UnresolvedSetImpl &Fns,
3391                                    Expr *LHS, Expr *RHS,
3392                                    bool RequiresADL = true,
3393                                    bool AllowRewrittenCandidates = true,
3394                                    FunctionDecl *DefaultedFn = nullptr);
3395   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3396                                                 const UnresolvedSetImpl &Fns,
3397                                                 Expr *LHS, Expr *RHS,
3398                                                 FunctionDecl *DefaultedFn);
3399 
3400   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3401                                                 SourceLocation RLoc,
3402                                                 Expr *Base,Expr *Idx);
3403 
3404   ExprResult
3405   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3406                             SourceLocation LParenLoc,
3407                             MultiExprArg Args,
3408                             SourceLocation RParenLoc);
3409   ExprResult
3410   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3411                                MultiExprArg Args,
3412                                SourceLocation RParenLoc);
3413 
3414   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3415                                       SourceLocation OpLoc,
3416                                       bool *NoArrowOperatorFound = nullptr);
3417 
3418   /// CheckCallReturnType - Checks that a call expression's return type is
3419   /// complete. Returns true on failure. The location passed in is the location
3420   /// that best represents the call.
3421   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3422                            CallExpr *CE, FunctionDecl *FD);
3423 
3424   /// Helpers for dealing with blocks and functions.
3425   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3426                                 bool CheckParameterNames);
3427   void CheckCXXDefaultArguments(FunctionDecl *FD);
3428   void CheckExtraCXXDefaultArguments(Declarator &D);
3429   Scope *getNonFieldDeclScope(Scope *S);
3430 
3431   /// \name Name lookup
3432   ///
3433   /// These routines provide name lookup that is used during semantic
3434   /// analysis to resolve the various kinds of names (identifiers,
3435   /// overloaded operator names, constructor names, etc.) into zero or
3436   /// more declarations within a particular scope. The major entry
3437   /// points are LookupName, which performs unqualified name lookup,
3438   /// and LookupQualifiedName, which performs qualified name lookup.
3439   ///
3440   /// All name lookup is performed based on some specific criteria,
3441   /// which specify what names will be visible to name lookup and how
3442   /// far name lookup should work. These criteria are important both
3443   /// for capturing language semantics (certain lookups will ignore
3444   /// certain names, for example) and for performance, since name
3445   /// lookup is often a bottleneck in the compilation of C++. Name
3446   /// lookup criteria is specified via the LookupCriteria enumeration.
3447   ///
3448   /// The results of name lookup can vary based on the kind of name
3449   /// lookup performed, the current language, and the translation
3450   /// unit. In C, for example, name lookup will either return nothing
3451   /// (no entity found) or a single declaration. In C++, name lookup
3452   /// can additionally refer to a set of overloaded functions or
3453   /// result in an ambiguity. All of the possible results of name
3454   /// lookup are captured by the LookupResult class, which provides
3455   /// the ability to distinguish among them.
3456   //@{
3457 
3458   /// Describes the kind of name lookup to perform.
3459   enum LookupNameKind {
3460     /// Ordinary name lookup, which finds ordinary names (functions,
3461     /// variables, typedefs, etc.) in C and most kinds of names
3462     /// (functions, variables, members, types, etc.) in C++.
3463     LookupOrdinaryName = 0,
3464     /// Tag name lookup, which finds the names of enums, classes,
3465     /// structs, and unions.
3466     LookupTagName,
3467     /// Label name lookup.
3468     LookupLabel,
3469     /// Member name lookup, which finds the names of
3470     /// class/struct/union members.
3471     LookupMemberName,
3472     /// Look up of an operator name (e.g., operator+) for use with
3473     /// operator overloading. This lookup is similar to ordinary name
3474     /// lookup, but will ignore any declarations that are class members.
3475     LookupOperatorName,
3476     /// Look up of a name that precedes the '::' scope resolution
3477     /// operator in C++. This lookup completely ignores operator, object,
3478     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3479     LookupNestedNameSpecifierName,
3480     /// Look up a namespace name within a C++ using directive or
3481     /// namespace alias definition, ignoring non-namespace names (C++
3482     /// [basic.lookup.udir]p1).
3483     LookupNamespaceName,
3484     /// Look up all declarations in a scope with the given name,
3485     /// including resolved using declarations.  This is appropriate
3486     /// for checking redeclarations for a using declaration.
3487     LookupUsingDeclName,
3488     /// Look up an ordinary name that is going to be redeclared as a
3489     /// name with linkage. This lookup ignores any declarations that
3490     /// are outside of the current scope unless they have linkage. See
3491     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3492     LookupRedeclarationWithLinkage,
3493     /// Look up a friend of a local class. This lookup does not look
3494     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3495     LookupLocalFriendName,
3496     /// Look up the name of an Objective-C protocol.
3497     LookupObjCProtocolName,
3498     /// Look up implicit 'self' parameter of an objective-c method.
3499     LookupObjCImplicitSelfParam,
3500     /// Look up the name of an OpenMP user-defined reduction operation.
3501     LookupOMPReductionName,
3502     /// Look up the name of an OpenMP user-defined mapper.
3503     LookupOMPMapperName,
3504     /// Look up any declaration with any name.
3505     LookupAnyName
3506   };
3507 
3508   /// Specifies whether (or how) name lookup is being performed for a
3509   /// redeclaration (vs. a reference).
3510   enum RedeclarationKind {
3511     /// The lookup is a reference to this name that is not for the
3512     /// purpose of redeclaring the name.
3513     NotForRedeclaration = 0,
3514     /// The lookup results will be used for redeclaration of a name,
3515     /// if an entity by that name already exists and is visible.
3516     ForVisibleRedeclaration,
3517     /// The lookup results will be used for redeclaration of a name
3518     /// with external linkage; non-visible lookup results with external linkage
3519     /// may also be found.
3520     ForExternalRedeclaration
3521   };
3522 
3523   RedeclarationKind forRedeclarationInCurContext() {
3524     // A declaration with an owning module for linkage can never link against
3525     // anything that is not visible. We don't need to check linkage here; if
3526     // the context has internal linkage, redeclaration lookup won't find things
3527     // from other TUs, and we can't safely compute linkage yet in general.
3528     if (cast<Decl>(CurContext)
3529             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3530       return ForVisibleRedeclaration;
3531     return ForExternalRedeclaration;
3532   }
3533 
3534   /// The possible outcomes of name lookup for a literal operator.
3535   enum LiteralOperatorLookupResult {
3536     /// The lookup resulted in an error.
3537     LOLR_Error,
3538     /// The lookup found no match but no diagnostic was issued.
3539     LOLR_ErrorNoDiagnostic,
3540     /// The lookup found a single 'cooked' literal operator, which
3541     /// expects a normal literal to be built and passed to it.
3542     LOLR_Cooked,
3543     /// The lookup found a single 'raw' literal operator, which expects
3544     /// a string literal containing the spelling of the literal token.
3545     LOLR_Raw,
3546     /// The lookup found an overload set of literal operator templates,
3547     /// which expect the characters of the spelling of the literal token to be
3548     /// passed as a non-type template argument pack.
3549     LOLR_Template,
3550     /// The lookup found an overload set of literal operator templates,
3551     /// which expect the character type and characters of the spelling of the
3552     /// string literal token to be passed as template arguments.
3553     LOLR_StringTemplate
3554   };
3555 
3556   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3557                                                   CXXSpecialMember SM,
3558                                                   bool ConstArg,
3559                                                   bool VolatileArg,
3560                                                   bool RValueThis,
3561                                                   bool ConstThis,
3562                                                   bool VolatileThis);
3563 
3564   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3565   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3566       TypoRecoveryCallback;
3567 
3568 private:
3569   bool CppLookupName(LookupResult &R, Scope *S);
3570 
3571   struct TypoExprState {
3572     std::unique_ptr<TypoCorrectionConsumer> Consumer;
3573     TypoDiagnosticGenerator DiagHandler;
3574     TypoRecoveryCallback RecoveryHandler;
3575     TypoExprState();
3576     TypoExprState(TypoExprState &&other) noexcept;
3577     TypoExprState &operator=(TypoExprState &&other) noexcept;
3578   };
3579 
3580   /// The set of unhandled TypoExprs and their associated state.
3581   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3582 
3583   /// Creates a new TypoExpr AST node.
3584   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3585                               TypoDiagnosticGenerator TDG,
3586                               TypoRecoveryCallback TRC);
3587 
3588   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3589   //
3590   // The boolean value will be true to indicate that the namespace was loaded
3591   // from an AST/PCH file, or false otherwise.
3592   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3593 
3594   /// Whether we have already loaded known namespaces from an extenal
3595   /// source.
3596   bool LoadedExternalKnownNamespaces;
3597 
3598   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3599   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3600   /// should be skipped entirely.
3601   std::unique_ptr<TypoCorrectionConsumer>
3602   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3603                              Sema::LookupNameKind LookupKind, Scope *S,
3604                              CXXScopeSpec *SS,
3605                              CorrectionCandidateCallback &CCC,
3606                              DeclContext *MemberContext, bool EnteringContext,
3607                              const ObjCObjectPointerType *OPT,
3608                              bool ErrorRecovery);
3609 
3610 public:
3611   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3612 
3613   /// Clears the state of the given TypoExpr.
3614   void clearDelayedTypo(TypoExpr *TE);
3615 
3616   /// Look up a name, looking for a single declaration.  Return
3617   /// null if the results were absent, ambiguous, or overloaded.
3618   ///
3619   /// It is preferable to use the elaborated form and explicitly handle
3620   /// ambiguity and overloaded.
3621   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3622                               SourceLocation Loc,
3623                               LookupNameKind NameKind,
3624                               RedeclarationKind Redecl
3625                                 = NotForRedeclaration);
3626   bool LookupBuiltin(LookupResult &R);
3627   bool LookupName(LookupResult &R, Scope *S,
3628                   bool AllowBuiltinCreation = false);
3629   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3630                            bool InUnqualifiedLookup = false);
3631   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3632                            CXXScopeSpec &SS);
3633   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3634                         bool AllowBuiltinCreation = false,
3635                         bool EnteringContext = false);
3636   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3637                                    RedeclarationKind Redecl
3638                                      = NotForRedeclaration);
3639   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3640 
3641   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3642                                     QualType T1, QualType T2,
3643                                     UnresolvedSetImpl &Functions);
3644 
3645   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3646                                  SourceLocation GnuLabelLoc = SourceLocation());
3647 
3648   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3649   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3650   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3651                                                unsigned Quals);
3652   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3653                                          bool RValueThis, unsigned ThisQuals);
3654   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3655                                               unsigned Quals);
3656   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3657                                         bool RValueThis, unsigned ThisQuals);
3658   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3659 
3660   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3661   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3662                                                     ArrayRef<QualType> ArgTys,
3663                                                     bool AllowRaw,
3664                                                     bool AllowTemplate,
3665                                                     bool AllowStringTemplate,
3666                                                     bool DiagnoseMissing);
3667   bool isKnownName(StringRef name);
3668 
3669   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3670   enum class FunctionEmissionStatus {
3671     Emitted,
3672     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
3673     OMPDiscarded,      // Discarded due to OpenMP hostness
3674     TemplateDiscarded, // Discarded due to uninstantiated templates
3675     Unknown,
3676   };
3677   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3678 
3679   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3680   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3681 
3682   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3683                                ArrayRef<Expr *> Args, ADLResult &Functions);
3684 
3685   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3686                           VisibleDeclConsumer &Consumer,
3687                           bool IncludeGlobalScope = true,
3688                           bool LoadExternal = true);
3689   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3690                           VisibleDeclConsumer &Consumer,
3691                           bool IncludeGlobalScope = true,
3692                           bool IncludeDependentBases = false,
3693                           bool LoadExternal = true);
3694 
3695   enum CorrectTypoKind {
3696     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
3697     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3698   };
3699 
3700   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3701                              Sema::LookupNameKind LookupKind,
3702                              Scope *S, CXXScopeSpec *SS,
3703                              CorrectionCandidateCallback &CCC,
3704                              CorrectTypoKind Mode,
3705                              DeclContext *MemberContext = nullptr,
3706                              bool EnteringContext = false,
3707                              const ObjCObjectPointerType *OPT = nullptr,
3708                              bool RecordFailure = true);
3709 
3710   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3711                                Sema::LookupNameKind LookupKind, Scope *S,
3712                                CXXScopeSpec *SS,
3713                                CorrectionCandidateCallback &CCC,
3714                                TypoDiagnosticGenerator TDG,
3715                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3716                                DeclContext *MemberContext = nullptr,
3717                                bool EnteringContext = false,
3718                                const ObjCObjectPointerType *OPT = nullptr);
3719 
3720   /// Process any TypoExprs in the given Expr and its children,
3721   /// generating diagnostics as appropriate and returning a new Expr if there
3722   /// were typos that were all successfully corrected and ExprError if one or
3723   /// more typos could not be corrected.
3724   ///
3725   /// \param E The Expr to check for TypoExprs.
3726   ///
3727   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3728   /// initializer.
3729   ///
3730   /// \param Filter A function applied to a newly rebuilt Expr to determine if
3731   /// it is an acceptable/usable result from a single combination of typo
3732   /// corrections. As long as the filter returns ExprError, different
3733   /// combinations of corrections will be tried until all are exhausted.
3734   ExprResult
3735   CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3736                             llvm::function_ref<ExprResult(Expr *)> Filter =
3737                                 [](Expr *E) -> ExprResult { return E; });
3738 
3739   ExprResult
3740   CorrectDelayedTyposInExpr(Expr *E,
3741                             llvm::function_ref<ExprResult(Expr *)> Filter) {
3742     return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3743   }
3744 
3745   ExprResult
3746   CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3747                             llvm::function_ref<ExprResult(Expr *)> Filter =
3748                                 [](Expr *E) -> ExprResult { return E; }) {
3749     return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3750   }
3751 
3752   ExprResult
3753   CorrectDelayedTyposInExpr(ExprResult ER,
3754                             llvm::function_ref<ExprResult(Expr *)> Filter) {
3755     return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3756   }
3757 
3758   void diagnoseTypo(const TypoCorrection &Correction,
3759                     const PartialDiagnostic &TypoDiag,
3760                     bool ErrorRecovery = true);
3761 
3762   void diagnoseTypo(const TypoCorrection &Correction,
3763                     const PartialDiagnostic &TypoDiag,
3764                     const PartialDiagnostic &PrevNote,
3765                     bool ErrorRecovery = true);
3766 
3767   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3768 
3769   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3770                                           ArrayRef<Expr *> Args,
3771                                    AssociatedNamespaceSet &AssociatedNamespaces,
3772                                    AssociatedClassSet &AssociatedClasses);
3773 
3774   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3775                             bool ConsiderLinkage, bool AllowInlineNamespace);
3776 
3777   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3778 
3779   void DiagnoseAmbiguousLookup(LookupResult &Result);
3780   //@}
3781 
3782   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3783                                           SourceLocation IdLoc,
3784                                           bool TypoCorrection = false);
3785   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3786                                  Scope *S, bool ForRedeclaration,
3787                                  SourceLocation Loc);
3788   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3789                                       Scope *S);
3790   void AddKnownFunctionAttributes(FunctionDecl *FD);
3791 
3792   // More parsing and symbol table subroutines.
3793 
3794   void ProcessPragmaWeak(Scope *S, Decl *D);
3795   // Decl attributes - this routine is the top level dispatcher.
3796   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3797   // Helper for delayed processing of attributes.
3798   void ProcessDeclAttributeDelayed(Decl *D,
3799                                    const ParsedAttributesView &AttrList);
3800   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3801                              bool IncludeCXX11Attributes = true);
3802   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3803                                    const ParsedAttributesView &AttrList);
3804 
3805   void checkUnusedDeclAttributes(Declarator &D);
3806 
3807   /// Determine if type T is a valid subject for a nonnull and similar
3808   /// attributes. By default, we look through references (the behavior used by
3809   /// nonnull), but if the second parameter is true, then we treat a reference
3810   /// type as valid.
3811   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3812 
3813   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3814   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3815                             const FunctionDecl *FD = nullptr);
3816   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3817   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3818   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3819                                       StringRef &Str,
3820                                       SourceLocation *ArgLocation = nullptr);
3821   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3822   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3823   bool checkMSInheritanceAttrOnDefinition(
3824       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3825       MSInheritanceModel SemanticSpelling);
3826 
3827   void CheckAlignasUnderalignment(Decl *D);
3828 
3829   /// Adjust the calling convention of a method to be the ABI default if it
3830   /// wasn't specified explicitly.  This handles method types formed from
3831   /// function type typedefs and typename template arguments.
3832   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3833                               SourceLocation Loc);
3834 
3835   // Check if there is an explicit attribute, but only look through parens.
3836   // The intent is to look for an attribute on the current declarator, but not
3837   // one that came from a typedef.
3838   bool hasExplicitCallingConv(QualType T);
3839 
3840   /// Get the outermost AttributedType node that sets a calling convention.
3841   /// Valid types should not have multiple attributes with different CCs.
3842   const AttributedType *getCallingConvAttributedType(QualType T) const;
3843 
3844   /// Stmt attributes - this routine is the top level dispatcher.
3845   StmtResult ProcessStmtAttributes(Stmt *Stmt,
3846                                    const ParsedAttributesView &Attrs,
3847                                    SourceRange Range);
3848 
3849   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3850                                    ObjCMethodDecl *MethodDecl,
3851                                    bool IsProtocolMethodDecl);
3852 
3853   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3854                                    ObjCMethodDecl *Overridden,
3855                                    bool IsProtocolMethodDecl);
3856 
3857   /// WarnExactTypedMethods - This routine issues a warning if method
3858   /// implementation declaration matches exactly that of its declaration.
3859   void WarnExactTypedMethods(ObjCMethodDecl *Method,
3860                              ObjCMethodDecl *MethodDecl,
3861                              bool IsProtocolMethodDecl);
3862 
3863   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3864 
3865   /// CheckImplementationIvars - This routine checks if the instance variables
3866   /// listed in the implelementation match those listed in the interface.
3867   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3868                                 ObjCIvarDecl **Fields, unsigned nIvars,
3869                                 SourceLocation Loc);
3870 
3871   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3872   /// remains unimplemented in the class or category \@implementation.
3873   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3874                                  ObjCContainerDecl* IDecl,
3875                                  bool IncompleteImpl = false);
3876 
3877   /// DiagnoseUnimplementedProperties - This routine warns on those properties
3878   /// which must be implemented by this implementation.
3879   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3880                                        ObjCContainerDecl *CDecl,
3881                                        bool SynthesizeProperties);
3882 
3883   /// Diagnose any null-resettable synthesized setters.
3884   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3885 
3886   /// DefaultSynthesizeProperties - This routine default synthesizes all
3887   /// properties which must be synthesized in the class's \@implementation.
3888   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3889                                    ObjCInterfaceDecl *IDecl,
3890                                    SourceLocation AtEnd);
3891   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3892 
3893   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3894   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3895   /// declared in class 'IFace'.
3896   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3897                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3898 
3899   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3900   /// backs the property is not used in the property's accessor.
3901   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3902                                            const ObjCImplementationDecl *ImplD);
3903 
3904   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3905   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3906   /// It also returns ivar's property on success.
3907   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3908                                                const ObjCPropertyDecl *&PDecl) const;
3909 
3910   /// Called by ActOnProperty to handle \@property declarations in
3911   /// class extensions.
3912   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3913                       SourceLocation AtLoc,
3914                       SourceLocation LParenLoc,
3915                       FieldDeclarator &FD,
3916                       Selector GetterSel,
3917                       SourceLocation GetterNameLoc,
3918                       Selector SetterSel,
3919                       SourceLocation SetterNameLoc,
3920                       const bool isReadWrite,
3921                       unsigned &Attributes,
3922                       const unsigned AttributesAsWritten,
3923                       QualType T,
3924                       TypeSourceInfo *TSI,
3925                       tok::ObjCKeywordKind MethodImplKind);
3926 
3927   /// Called by ActOnProperty and HandlePropertyInClassExtension to
3928   /// handle creating the ObjcPropertyDecl for a category or \@interface.
3929   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3930                                        ObjCContainerDecl *CDecl,
3931                                        SourceLocation AtLoc,
3932                                        SourceLocation LParenLoc,
3933                                        FieldDeclarator &FD,
3934                                        Selector GetterSel,
3935                                        SourceLocation GetterNameLoc,
3936                                        Selector SetterSel,
3937                                        SourceLocation SetterNameLoc,
3938                                        const bool isReadWrite,
3939                                        const unsigned Attributes,
3940                                        const unsigned AttributesAsWritten,
3941                                        QualType T,
3942                                        TypeSourceInfo *TSI,
3943                                        tok::ObjCKeywordKind MethodImplKind,
3944                                        DeclContext *lexicalDC = nullptr);
3945 
3946   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3947   /// warning) when atomic property has one but not the other user-declared
3948   /// setter or getter.
3949   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3950                                        ObjCInterfaceDecl* IDecl);
3951 
3952   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3953 
3954   void DiagnoseMissingDesignatedInitOverrides(
3955                                           const ObjCImplementationDecl *ImplD,
3956                                           const ObjCInterfaceDecl *IFD);
3957 
3958   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3959 
3960   enum MethodMatchStrategy {
3961     MMS_loose,
3962     MMS_strict
3963   };
3964 
3965   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3966   /// true, or false, accordingly.
3967   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3968                                   const ObjCMethodDecl *PrevMethod,
3969                                   MethodMatchStrategy strategy = MMS_strict);
3970 
3971   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3972   /// or protocol against those declared in their implementations.
3973   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3974                                   const SelectorSet &ClsMap,
3975                                   SelectorSet &InsMapSeen,
3976                                   SelectorSet &ClsMapSeen,
3977                                   ObjCImplDecl* IMPDecl,
3978                                   ObjCContainerDecl* IDecl,
3979                                   bool &IncompleteImpl,
3980                                   bool ImmediateClass,
3981                                   bool WarnCategoryMethodImpl=false);
3982 
3983   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3984   /// category matches with those implemented in its primary class and
3985   /// warns each time an exact match is found.
3986   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3987 
3988   /// Add the given method to the list of globally-known methods.
3989   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3990 
3991   /// Returns default addr space for method qualifiers.
3992   LangAS getDefaultCXXMethodAddrSpace() const;
3993 
3994 private:
3995   /// AddMethodToGlobalPool - Add an instance or factory method to the global
3996   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3997   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3998 
3999   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4000   /// optionally warns if there are multiple signatures.
4001   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4002                                            bool receiverIdOrClass,
4003                                            bool instance);
4004 
4005 public:
4006   /// - Returns instance or factory methods in global method pool for
4007   /// given selector. It checks the desired kind first, if none is found, and
4008   /// parameter checkTheOther is set, it then checks the other kind. If no such
4009   /// method or only one method is found, function returns false; otherwise, it
4010   /// returns true.
4011   bool
4012   CollectMultipleMethodsInGlobalPool(Selector Sel,
4013                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4014                                      bool InstanceFirst, bool CheckTheOther,
4015                                      const ObjCObjectType *TypeBound = nullptr);
4016 
4017   bool
4018   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4019                                  SourceRange R, bool receiverIdOrClass,
4020                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4021 
4022   void
4023   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4024                                      Selector Sel, SourceRange R,
4025                                      bool receiverIdOrClass);
4026 
4027 private:
4028   /// - Returns a selector which best matches given argument list or
4029   /// nullptr if none could be found
4030   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4031                                    bool IsInstance,
4032                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4033 
4034 
4035   /// Record the typo correction failure and return an empty correction.
4036   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4037                                   bool RecordFailure = true) {
4038     if (RecordFailure)
4039       TypoCorrectionFailures[Typo].insert(TypoLoc);
4040     return TypoCorrection();
4041   }
4042 
4043 public:
4044   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4045   /// unit are added to a global pool. This allows us to efficiently associate
4046   /// a selector with a method declaraation for purposes of typechecking
4047   /// messages sent to "id" (where the class of the object is unknown).
4048   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4049     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4050   }
4051 
4052   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4053   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4054     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4055   }
4056 
4057   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4058   /// pool.
4059   void AddAnyMethodToGlobalPool(Decl *D);
4060 
4061   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4062   /// there are multiple signatures.
4063   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4064                                                    bool receiverIdOrClass=false) {
4065     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4066                                     /*instance*/true);
4067   }
4068 
4069   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4070   /// there are multiple signatures.
4071   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4072                                                   bool receiverIdOrClass=false) {
4073     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4074                                     /*instance*/false);
4075   }
4076 
4077   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4078                               QualType ObjectType=QualType());
4079   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4080   /// implementation.
4081   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4082 
4083   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4084   /// initialization.
4085   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4086                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4087 
4088   //===--------------------------------------------------------------------===//
4089   // Statement Parsing Callbacks: SemaStmt.cpp.
4090 public:
4091   class FullExprArg {
4092   public:
4093     FullExprArg() : E(nullptr) { }
4094     FullExprArg(Sema &actions) : E(nullptr) { }
4095 
4096     ExprResult release() {
4097       return E;
4098     }
4099 
4100     Expr *get() const { return E; }
4101 
4102     Expr *operator->() {
4103       return E;
4104     }
4105 
4106   private:
4107     // FIXME: No need to make the entire Sema class a friend when it's just
4108     // Sema::MakeFullExpr that needs access to the constructor below.
4109     friend class Sema;
4110 
4111     explicit FullExprArg(Expr *expr) : E(expr) {}
4112 
4113     Expr *E;
4114   };
4115 
4116   FullExprArg MakeFullExpr(Expr *Arg) {
4117     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4118   }
4119   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4120     return FullExprArg(
4121         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4122   }
4123   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4124     ExprResult FE =
4125         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4126                             /*DiscardedValue*/ true);
4127     return FullExprArg(FE.get());
4128   }
4129 
4130   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4131   StmtResult ActOnExprStmtError();
4132 
4133   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4134                            bool HasLeadingEmptyMacro = false);
4135 
4136   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4137   void ActOnFinishOfCompoundStmt();
4138   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4139                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4140 
4141   /// A RAII object to enter scope of a compound statement.
4142   class CompoundScopeRAII {
4143   public:
4144     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4145       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4146     }
4147 
4148     ~CompoundScopeRAII() {
4149       S.ActOnFinishOfCompoundStmt();
4150     }
4151 
4152   private:
4153     Sema &S;
4154   };
4155 
4156   /// An RAII helper that pops function a function scope on exit.
4157   struct FunctionScopeRAII {
4158     Sema &S;
4159     bool Active;
4160     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4161     ~FunctionScopeRAII() {
4162       if (Active)
4163         S.PopFunctionScopeInfo();
4164     }
4165     void disable() { Active = false; }
4166   };
4167 
4168   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4169                                    SourceLocation StartLoc,
4170                                    SourceLocation EndLoc);
4171   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4172   StmtResult ActOnForEachLValueExpr(Expr *E);
4173   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4174   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4175                            SourceLocation DotDotDotLoc, ExprResult RHS,
4176                            SourceLocation ColonLoc);
4177   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4178 
4179   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4180                                       SourceLocation ColonLoc,
4181                                       Stmt *SubStmt, Scope *CurScope);
4182   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4183                             SourceLocation ColonLoc, Stmt *SubStmt);
4184 
4185   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4186                                  ArrayRef<const Attr*> Attrs,
4187                                  Stmt *SubStmt);
4188 
4189   class ConditionResult;
4190   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4191                          Stmt *InitStmt,
4192                          ConditionResult Cond, Stmt *ThenVal,
4193                          SourceLocation ElseLoc, Stmt *ElseVal);
4194   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4195                          Stmt *InitStmt,
4196                          ConditionResult Cond, Stmt *ThenVal,
4197                          SourceLocation ElseLoc, Stmt *ElseVal);
4198   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4199                                     Stmt *InitStmt,
4200                                     ConditionResult Cond);
4201   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4202                                            Stmt *Switch, Stmt *Body);
4203   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4204                             Stmt *Body);
4205   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4206                          SourceLocation WhileLoc, SourceLocation CondLParen,
4207                          Expr *Cond, SourceLocation CondRParen);
4208 
4209   StmtResult ActOnForStmt(SourceLocation ForLoc,
4210                           SourceLocation LParenLoc,
4211                           Stmt *First,
4212                           ConditionResult Second,
4213                           FullExprArg Third,
4214                           SourceLocation RParenLoc,
4215                           Stmt *Body);
4216   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4217                                            Expr *collection);
4218   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4219                                         Stmt *First, Expr *collection,
4220                                         SourceLocation RParenLoc);
4221   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4222 
4223   enum BuildForRangeKind {
4224     /// Initial building of a for-range statement.
4225     BFRK_Build,
4226     /// Instantiation or recovery rebuild of a for-range statement. Don't
4227     /// attempt any typo-correction.
4228     BFRK_Rebuild,
4229     /// Determining whether a for-range statement could be built. Avoid any
4230     /// unnecessary or irreversible actions.
4231     BFRK_Check
4232   };
4233 
4234   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4235                                   SourceLocation CoawaitLoc,
4236                                   Stmt *InitStmt,
4237                                   Stmt *LoopVar,
4238                                   SourceLocation ColonLoc, Expr *Collection,
4239                                   SourceLocation RParenLoc,
4240                                   BuildForRangeKind Kind);
4241   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4242                                   SourceLocation CoawaitLoc,
4243                                   Stmt *InitStmt,
4244                                   SourceLocation ColonLoc,
4245                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4246                                   Expr *Cond, Expr *Inc,
4247                                   Stmt *LoopVarDecl,
4248                                   SourceLocation RParenLoc,
4249                                   BuildForRangeKind Kind);
4250   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4251 
4252   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4253                            SourceLocation LabelLoc,
4254                            LabelDecl *TheDecl);
4255   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4256                                    SourceLocation StarLoc,
4257                                    Expr *DestExp);
4258   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4259   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4260 
4261   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4262                                 CapturedRegionKind Kind, unsigned NumParams);
4263   typedef std::pair<StringRef, QualType> CapturedParamNameType;
4264   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4265                                 CapturedRegionKind Kind,
4266                                 ArrayRef<CapturedParamNameType> Params,
4267                                 unsigned OpenMPCaptureLevel = 0);
4268   StmtResult ActOnCapturedRegionEnd(Stmt *S);
4269   void ActOnCapturedRegionError();
4270   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4271                                            SourceLocation Loc,
4272                                            unsigned NumParams);
4273 
4274   enum CopyElisionSemanticsKind {
4275     CES_Strict = 0,
4276     CES_AllowParameters = 1,
4277     CES_AllowDifferentTypes = 2,
4278     CES_AllowExceptionVariables = 4,
4279     CES_FormerDefault = (CES_AllowParameters),
4280     CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4281     CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4282                          CES_AllowExceptionVariables),
4283   };
4284 
4285   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4286                                    CopyElisionSemanticsKind CESK);
4287   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4288                               CopyElisionSemanticsKind CESK);
4289 
4290   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4291                              Scope *CurScope);
4292   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4293   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4294 
4295   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4296                              bool IsVolatile, unsigned NumOutputs,
4297                              unsigned NumInputs, IdentifierInfo **Names,
4298                              MultiExprArg Constraints, MultiExprArg Exprs,
4299                              Expr *AsmString, MultiExprArg Clobbers,
4300                              unsigned NumLabels,
4301                              SourceLocation RParenLoc);
4302 
4303   void FillInlineAsmIdentifierInfo(Expr *Res,
4304                                    llvm::InlineAsmIdentifierInfo &Info);
4305   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4306                                        SourceLocation TemplateKWLoc,
4307                                        UnqualifiedId &Id,
4308                                        bool IsUnevaluatedContext);
4309   bool LookupInlineAsmField(StringRef Base, StringRef Member,
4310                             unsigned &Offset, SourceLocation AsmLoc);
4311   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4312                                          SourceLocation AsmLoc);
4313   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4314                             ArrayRef<Token> AsmToks,
4315                             StringRef AsmString,
4316                             unsigned NumOutputs, unsigned NumInputs,
4317                             ArrayRef<StringRef> Constraints,
4318                             ArrayRef<StringRef> Clobbers,
4319                             ArrayRef<Expr*> Exprs,
4320                             SourceLocation EndLoc);
4321   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4322                                    SourceLocation Location,
4323                                    bool AlwaysCreate);
4324 
4325   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4326                                   SourceLocation StartLoc,
4327                                   SourceLocation IdLoc, IdentifierInfo *Id,
4328                                   bool Invalid = false);
4329 
4330   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4331 
4332   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4333                                   Decl *Parm, Stmt *Body);
4334 
4335   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4336 
4337   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4338                                 MultiStmtArg Catch, Stmt *Finally);
4339 
4340   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4341   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4342                                   Scope *CurScope);
4343   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4344                                             Expr *operand);
4345   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4346                                          Expr *SynchExpr,
4347                                          Stmt *SynchBody);
4348 
4349   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4350 
4351   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4352                                      SourceLocation StartLoc,
4353                                      SourceLocation IdLoc,
4354                                      IdentifierInfo *Id);
4355 
4356   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4357 
4358   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4359                                 Decl *ExDecl, Stmt *HandlerBlock);
4360   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4361                               ArrayRef<Stmt *> Handlers);
4362 
4363   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4364                               SourceLocation TryLoc, Stmt *TryBlock,
4365                               Stmt *Handler);
4366   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4367                                  Expr *FilterExpr,
4368                                  Stmt *Block);
4369   void ActOnStartSEHFinallyBlock();
4370   void ActOnAbortSEHFinallyBlock();
4371   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4372   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4373 
4374   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4375 
4376   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4377 
4378   /// If it's a file scoped decl that must warn if not used, keep track
4379   /// of it.
4380   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4381 
4382   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4383   /// whose result is unused, warn.
4384   void DiagnoseUnusedExprResult(const Stmt *S);
4385   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4386   void DiagnoseUnusedDecl(const NamedDecl *ND);
4387 
4388   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4389   /// statement as a \p Body, and it is located on the same line.
4390   ///
4391   /// This helps prevent bugs due to typos, such as:
4392   ///     if (condition);
4393   ///       do_stuff();
4394   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4395                              const Stmt *Body,
4396                              unsigned DiagID);
4397 
4398   /// Warn if a for/while loop statement \p S, which is followed by
4399   /// \p PossibleBody, has a suspicious null statement as a body.
4400   void DiagnoseEmptyLoopBody(const Stmt *S,
4401                              const Stmt *PossibleBody);
4402 
4403   /// Warn if a value is moved to itself.
4404   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4405                         SourceLocation OpLoc);
4406 
4407   /// Warn if we're implicitly casting from a _Nullable pointer type to a
4408   /// _Nonnull one.
4409   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4410                                            SourceLocation Loc);
4411 
4412   /// Warn when implicitly casting 0 to nullptr.
4413   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4414 
4415   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4416     return DelayedDiagnostics.push(pool);
4417   }
4418   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4419 
4420   typedef ProcessingContextState ParsingClassState;
4421   ParsingClassState PushParsingClass() {
4422     ParsingClassDepth++;
4423     return DelayedDiagnostics.pushUndelayed();
4424   }
4425   void PopParsingClass(ParsingClassState state) {
4426     ParsingClassDepth--;
4427     DelayedDiagnostics.popUndelayed(state);
4428   }
4429 
4430   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4431 
4432   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4433                                   const ObjCInterfaceDecl *UnknownObjCClass,
4434                                   bool ObjCPropertyAccess,
4435                                   bool AvoidPartialAvailabilityChecks = false,
4436                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
4437 
4438   bool makeUnavailableInSystemHeader(SourceLocation loc,
4439                                      UnavailableAttr::ImplicitReason reason);
4440 
4441   /// Issue any -Wunguarded-availability warnings in \c FD
4442   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4443 
4444   //===--------------------------------------------------------------------===//
4445   // Expression Parsing Callbacks: SemaExpr.cpp.
4446 
4447   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4448   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4449                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4450                          bool ObjCPropertyAccess = false,
4451                          bool AvoidPartialAvailabilityChecks = false,
4452                          ObjCInterfaceDecl *ClassReciever = nullptr);
4453   void NoteDeletedFunction(FunctionDecl *FD);
4454   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4455   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4456                                         ObjCMethodDecl *Getter,
4457                                         SourceLocation Loc);
4458   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4459                              ArrayRef<Expr *> Args);
4460 
4461   void PushExpressionEvaluationContext(
4462       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4463       ExpressionEvaluationContextRecord::ExpressionKind Type =
4464           ExpressionEvaluationContextRecord::EK_Other);
4465   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4466   void PushExpressionEvaluationContext(
4467       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4468       ExpressionEvaluationContextRecord::ExpressionKind Type =
4469           ExpressionEvaluationContextRecord::EK_Other);
4470   void PopExpressionEvaluationContext();
4471 
4472   void DiscardCleanupsInEvaluationContext();
4473 
4474   ExprResult TransformToPotentiallyEvaluated(Expr *E);
4475   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4476 
4477   ExprResult CheckUnevaluatedOperand(Expr *E);
4478   void CheckUnusedVolatileAssignment(Expr *E);
4479 
4480   ExprResult ActOnConstantExpression(ExprResult Res);
4481 
4482   // Functions for marking a declaration referenced.  These functions also
4483   // contain the relevant logic for marking if a reference to a function or
4484   // variable is an odr-use (in the C++11 sense).  There are separate variants
4485   // for expressions referring to a decl; these exist because odr-use marking
4486   // needs to be delayed for some constant variables when we build one of the
4487   // named expressions.
4488   //
4489   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4490   // should usually be true. This only needs to be set to false if the lack of
4491   // odr-use cannot be determined from the current context (for instance,
4492   // because the name denotes a virtual function and was written without an
4493   // explicit nested-name-specifier).
4494   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4495   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4496                               bool MightBeOdrUse = true);
4497   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4498   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4499   void MarkMemberReferenced(MemberExpr *E);
4500   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4501   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4502                                          unsigned CapturingScopeIndex);
4503 
4504   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4505   void CleanupVarDeclMarking();
4506 
4507   enum TryCaptureKind {
4508     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4509   };
4510 
4511   /// Try to capture the given variable.
4512   ///
4513   /// \param Var The variable to capture.
4514   ///
4515   /// \param Loc The location at which the capture occurs.
4516   ///
4517   /// \param Kind The kind of capture, which may be implicit (for either a
4518   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4519   ///
4520   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4521   /// an explicit lambda capture.
4522   ///
4523   /// \param BuildAndDiagnose Whether we are actually supposed to add the
4524   /// captures or diagnose errors. If false, this routine merely check whether
4525   /// the capture can occur without performing the capture itself or complaining
4526   /// if the variable cannot be captured.
4527   ///
4528   /// \param CaptureType Will be set to the type of the field used to capture
4529   /// this variable in the innermost block or lambda. Only valid when the
4530   /// variable can be captured.
4531   ///
4532   /// \param DeclRefType Will be set to the type of a reference to the capture
4533   /// from within the current scope. Only valid when the variable can be
4534   /// captured.
4535   ///
4536   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4537   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4538   /// This is useful when enclosing lambdas must speculatively capture
4539   /// variables that may or may not be used in certain specializations of
4540   /// a nested generic lambda.
4541   ///
4542   /// \returns true if an error occurred (i.e., the variable cannot be
4543   /// captured) and false if the capture succeeded.
4544   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4545                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4546                           QualType &CaptureType,
4547                           QualType &DeclRefType,
4548                           const unsigned *const FunctionScopeIndexToStopAt);
4549 
4550   /// Try to capture the given variable.
4551   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4552                           TryCaptureKind Kind = TryCapture_Implicit,
4553                           SourceLocation EllipsisLoc = SourceLocation());
4554 
4555   /// Checks if the variable must be captured.
4556   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4557 
4558   /// Given a variable, determine the type that a reference to that
4559   /// variable will have in the given scope.
4560   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4561 
4562   /// Mark all of the declarations referenced within a particular AST node as
4563   /// referenced. Used when template instantiation instantiates a non-dependent
4564   /// type -- entities referenced by the type are now referenced.
4565   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4566   void MarkDeclarationsReferencedInExpr(Expr *E,
4567                                         bool SkipLocalVariables = false);
4568 
4569   /// Try to recover by turning the given expression into a
4570   /// call.  Returns true if recovery was attempted or an error was
4571   /// emitted; this may also leave the ExprResult invalid.
4572   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4573                             bool ForceComplain = false,
4574                             bool (*IsPlausibleResult)(QualType) = nullptr);
4575 
4576   /// Figure out if an expression could be turned into a call.
4577   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4578                      UnresolvedSetImpl &NonTemplateOverloads);
4579 
4580   /// Conditionally issue a diagnostic based on the current
4581   /// evaluation context.
4582   ///
4583   /// \param Statement If Statement is non-null, delay reporting the
4584   /// diagnostic until the function body is parsed, and then do a basic
4585   /// reachability analysis to determine if the statement is reachable.
4586   /// If it is unreachable, the diagnostic will not be emitted.
4587   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4588                            const PartialDiagnostic &PD);
4589   /// Similar, but diagnostic is only produced if all the specified statements
4590   /// are reachable.
4591   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4592                            const PartialDiagnostic &PD);
4593 
4594   // Primary Expressions.
4595   SourceRange getExprRange(Expr *E) const;
4596 
4597   ExprResult ActOnIdExpression(
4598       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4599       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4600       CorrectionCandidateCallback *CCC = nullptr,
4601       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4602 
4603   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4604                               TemplateArgumentListInfo &Buffer,
4605                               DeclarationNameInfo &NameInfo,
4606                               const TemplateArgumentListInfo *&TemplateArgs);
4607 
4608   bool
4609   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4610                       CorrectionCandidateCallback &CCC,
4611                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4612                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4613 
4614   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4615                                     IdentifierInfo *II);
4616   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4617 
4618   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4619                                 IdentifierInfo *II,
4620                                 bool AllowBuiltinCreation=false);
4621 
4622   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4623                                         SourceLocation TemplateKWLoc,
4624                                         const DeclarationNameInfo &NameInfo,
4625                                         bool isAddressOfOperand,
4626                                 const TemplateArgumentListInfo *TemplateArgs);
4627 
4628   /// If \p D cannot be odr-used in the current expression evaluation context,
4629   /// return a reason explaining why. Otherwise, return NOUR_None.
4630   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4631 
4632   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4633                                 SourceLocation Loc,
4634                                 const CXXScopeSpec *SS = nullptr);
4635   DeclRefExpr *
4636   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4637                    const DeclarationNameInfo &NameInfo,
4638                    const CXXScopeSpec *SS = nullptr,
4639                    NamedDecl *FoundD = nullptr,
4640                    SourceLocation TemplateKWLoc = SourceLocation(),
4641                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4642   DeclRefExpr *
4643   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4644                    const DeclarationNameInfo &NameInfo,
4645                    NestedNameSpecifierLoc NNS,
4646                    NamedDecl *FoundD = nullptr,
4647                    SourceLocation TemplateKWLoc = SourceLocation(),
4648                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4649 
4650   ExprResult
4651   BuildAnonymousStructUnionMemberReference(
4652       const CXXScopeSpec &SS,
4653       SourceLocation nameLoc,
4654       IndirectFieldDecl *indirectField,
4655       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4656       Expr *baseObjectExpr = nullptr,
4657       SourceLocation opLoc = SourceLocation());
4658 
4659   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4660                                              SourceLocation TemplateKWLoc,
4661                                              LookupResult &R,
4662                                 const TemplateArgumentListInfo *TemplateArgs,
4663                                              const Scope *S);
4664   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4665                                      SourceLocation TemplateKWLoc,
4666                                      LookupResult &R,
4667                                 const TemplateArgumentListInfo *TemplateArgs,
4668                                      bool IsDefiniteInstance,
4669                                      const Scope *S);
4670   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4671                                   const LookupResult &R,
4672                                   bool HasTrailingLParen);
4673 
4674   ExprResult
4675   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4676                                     const DeclarationNameInfo &NameInfo,
4677                                     bool IsAddressOfOperand, const Scope *S,
4678                                     TypeSourceInfo **RecoveryTSI = nullptr);
4679 
4680   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4681                                        SourceLocation TemplateKWLoc,
4682                                 const DeclarationNameInfo &NameInfo,
4683                                 const TemplateArgumentListInfo *TemplateArgs);
4684 
4685   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4686                                       LookupResult &R,
4687                                       bool NeedsADL,
4688                                       bool AcceptInvalidDecl = false);
4689   ExprResult BuildDeclarationNameExpr(
4690       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4691       NamedDecl *FoundD = nullptr,
4692       const TemplateArgumentListInfo *TemplateArgs = nullptr,
4693       bool AcceptInvalidDecl = false);
4694 
4695   ExprResult BuildLiteralOperatorCall(LookupResult &R,
4696                       DeclarationNameInfo &SuffixInfo,
4697                       ArrayRef<Expr *> Args,
4698                       SourceLocation LitEndLoc,
4699                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4700 
4701   ExprResult BuildPredefinedExpr(SourceLocation Loc,
4702                                  PredefinedExpr::IdentKind IK);
4703   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4704   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4705 
4706   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4707 
4708   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4709   ExprResult ActOnCharacterConstant(const Token &Tok,
4710                                     Scope *UDLScope = nullptr);
4711   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4712   ExprResult ActOnParenListExpr(SourceLocation L,
4713                                 SourceLocation R,
4714                                 MultiExprArg Val);
4715 
4716   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4717   /// fragments (e.g. "foo" "bar" L"baz").
4718   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4719                                 Scope *UDLScope = nullptr);
4720 
4721   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4722                                        SourceLocation DefaultLoc,
4723                                        SourceLocation RParenLoc,
4724                                        Expr *ControllingExpr,
4725                                        ArrayRef<ParsedType> ArgTypes,
4726                                        ArrayRef<Expr *> ArgExprs);
4727   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4728                                         SourceLocation DefaultLoc,
4729                                         SourceLocation RParenLoc,
4730                                         Expr *ControllingExpr,
4731                                         ArrayRef<TypeSourceInfo *> Types,
4732                                         ArrayRef<Expr *> Exprs);
4733 
4734   // Binary/Unary Operators.  'Tok' is the token for the operator.
4735   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4736                                   Expr *InputExpr);
4737   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4738                           UnaryOperatorKind Opc, Expr *Input);
4739   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4740                           tok::TokenKind Op, Expr *Input);
4741 
4742   bool isQualifiedMemberAccess(Expr *E);
4743   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4744 
4745   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4746                                             SourceLocation OpLoc,
4747                                             UnaryExprOrTypeTrait ExprKind,
4748                                             SourceRange R);
4749   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4750                                             UnaryExprOrTypeTrait ExprKind);
4751   ExprResult
4752     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4753                                   UnaryExprOrTypeTrait ExprKind,
4754                                   bool IsType, void *TyOrEx,
4755                                   SourceRange ArgRange);
4756 
4757   ExprResult CheckPlaceholderExpr(Expr *E);
4758   bool CheckVecStepExpr(Expr *E);
4759 
4760   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4761   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4762                                         SourceRange ExprRange,
4763                                         UnaryExprOrTypeTrait ExprKind);
4764   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4765                                           SourceLocation OpLoc,
4766                                           IdentifierInfo &Name,
4767                                           SourceLocation NameLoc,
4768                                           SourceLocation RParenLoc);
4769   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4770                                  tok::TokenKind Kind, Expr *Input);
4771 
4772   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4773                                      Expr *Idx, SourceLocation RLoc);
4774   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4775                                              Expr *Idx, SourceLocation RLoc);
4776   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4777                                       Expr *LowerBound, SourceLocation ColonLoc,
4778                                       Expr *Length, SourceLocation RBLoc);
4779 
4780   // This struct is for use by ActOnMemberAccess to allow
4781   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4782   // changing the access operator from a '.' to a '->' (to see if that is the
4783   // change needed to fix an error about an unknown member, e.g. when the class
4784   // defines a custom operator->).
4785   struct ActOnMemberAccessExtraArgs {
4786     Scope *S;
4787     UnqualifiedId &Id;
4788     Decl *ObjCImpDecl;
4789   };
4790 
4791   ExprResult BuildMemberReferenceExpr(
4792       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4793       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4794       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4795       const TemplateArgumentListInfo *TemplateArgs,
4796       const Scope *S,
4797       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4798 
4799   ExprResult
4800   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4801                            bool IsArrow, const CXXScopeSpec &SS,
4802                            SourceLocation TemplateKWLoc,
4803                            NamedDecl *FirstQualifierInScope, LookupResult &R,
4804                            const TemplateArgumentListInfo *TemplateArgs,
4805                            const Scope *S,
4806                            bool SuppressQualifierCheck = false,
4807                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4808 
4809   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4810                                      SourceLocation OpLoc,
4811                                      const CXXScopeSpec &SS, FieldDecl *Field,
4812                                      DeclAccessPair FoundDecl,
4813                                      const DeclarationNameInfo &MemberNameInfo);
4814 
4815   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4816 
4817   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4818                                      const CXXScopeSpec &SS,
4819                                      const LookupResult &R);
4820 
4821   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4822                                       bool IsArrow, SourceLocation OpLoc,
4823                                       const CXXScopeSpec &SS,
4824                                       SourceLocation TemplateKWLoc,
4825                                       NamedDecl *FirstQualifierInScope,
4826                                const DeclarationNameInfo &NameInfo,
4827                                const TemplateArgumentListInfo *TemplateArgs);
4828 
4829   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4830                                    SourceLocation OpLoc,
4831                                    tok::TokenKind OpKind,
4832                                    CXXScopeSpec &SS,
4833                                    SourceLocation TemplateKWLoc,
4834                                    UnqualifiedId &Member,
4835                                    Decl *ObjCImpDecl);
4836 
4837   MemberExpr *
4838   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4839                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4840                   ValueDecl *Member, DeclAccessPair FoundDecl,
4841                   bool HadMultipleCandidates,
4842                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4843                   ExprValueKind VK, ExprObjectKind OK,
4844                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
4845   MemberExpr *
4846   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4847                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4848                   ValueDecl *Member, DeclAccessPair FoundDecl,
4849                   bool HadMultipleCandidates,
4850                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4851                   ExprValueKind VK, ExprObjectKind OK,
4852                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
4853 
4854   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4855   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4856                                FunctionDecl *FDecl,
4857                                const FunctionProtoType *Proto,
4858                                ArrayRef<Expr *> Args,
4859                                SourceLocation RParenLoc,
4860                                bool ExecConfig = false);
4861   void CheckStaticArrayArgument(SourceLocation CallLoc,
4862                                 ParmVarDecl *Param,
4863                                 const Expr *ArgExpr);
4864 
4865   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4866   /// This provides the location of the left/right parens and a list of comma
4867   /// locations.
4868   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4869                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4870                            Expr *ExecConfig = nullptr);
4871   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4872                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4873                            Expr *ExecConfig = nullptr,
4874                            bool IsExecConfig = false);
4875   enum class AtomicArgumentOrder { API, AST };
4876   ExprResult
4877   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4878                   SourceLocation RParenLoc, MultiExprArg Args,
4879                   AtomicExpr::AtomicOp Op,
4880                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4881   ExprResult
4882   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4883                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4884                         Expr *Config = nullptr, bool IsExecConfig = false,
4885                         ADLCallKind UsesADL = ADLCallKind::NotADL);
4886 
4887   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4888                                      MultiExprArg ExecConfig,
4889                                      SourceLocation GGGLoc);
4890 
4891   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4892                            Declarator &D, ParsedType &Ty,
4893                            SourceLocation RParenLoc, Expr *CastExpr);
4894   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4895                                  TypeSourceInfo *Ty,
4896                                  SourceLocation RParenLoc,
4897                                  Expr *Op);
4898   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4899 
4900   /// Build an altivec or OpenCL literal.
4901   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4902                                 SourceLocation RParenLoc, Expr *E,
4903                                 TypeSourceInfo *TInfo);
4904 
4905   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4906 
4907   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4908                                   ParsedType Ty,
4909                                   SourceLocation RParenLoc,
4910                                   Expr *InitExpr);
4911 
4912   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4913                                       TypeSourceInfo *TInfo,
4914                                       SourceLocation RParenLoc,
4915                                       Expr *LiteralExpr);
4916 
4917   ExprResult ActOnInitList(SourceLocation LBraceLoc,
4918                            MultiExprArg InitArgList,
4919                            SourceLocation RBraceLoc);
4920 
4921   ExprResult BuildInitList(SourceLocation LBraceLoc,
4922                            MultiExprArg InitArgList,
4923                            SourceLocation RBraceLoc);
4924 
4925   ExprResult ActOnDesignatedInitializer(Designation &Desig,
4926                                         SourceLocation EqualOrColonLoc,
4927                                         bool GNUSyntax,
4928                                         ExprResult Init);
4929 
4930 private:
4931   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4932 
4933 public:
4934   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4935                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4936   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4937                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4938   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4939                                 Expr *LHSExpr, Expr *RHSExpr);
4940 
4941   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4942 
4943   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4944   /// in the case of a the GNU conditional expr extension.
4945   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4946                                 SourceLocation ColonLoc,
4947                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4948 
4949   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4950   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4951                             LabelDecl *TheDecl);
4952 
4953   void ActOnStartStmtExpr();
4954   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
4955                            SourceLocation RPLoc);
4956   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4957                            SourceLocation RPLoc, unsigned TemplateDepth);
4958   // Handle the final expression in a statement expression.
4959   ExprResult ActOnStmtExprResult(ExprResult E);
4960   void ActOnStmtExprError();
4961 
4962   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4963   struct OffsetOfComponent {
4964     SourceLocation LocStart, LocEnd;
4965     bool isBrackets;  // true if [expr], false if .ident
4966     union {
4967       IdentifierInfo *IdentInfo;
4968       Expr *E;
4969     } U;
4970   };
4971 
4972   /// __builtin_offsetof(type, a.b[123][456].c)
4973   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4974                                   TypeSourceInfo *TInfo,
4975                                   ArrayRef<OffsetOfComponent> Components,
4976                                   SourceLocation RParenLoc);
4977   ExprResult ActOnBuiltinOffsetOf(Scope *S,
4978                                   SourceLocation BuiltinLoc,
4979                                   SourceLocation TypeLoc,
4980                                   ParsedType ParsedArgTy,
4981                                   ArrayRef<OffsetOfComponent> Components,
4982                                   SourceLocation RParenLoc);
4983 
4984   // __builtin_choose_expr(constExpr, expr1, expr2)
4985   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4986                              Expr *CondExpr, Expr *LHSExpr,
4987                              Expr *RHSExpr, SourceLocation RPLoc);
4988 
4989   // __builtin_va_arg(expr, type)
4990   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4991                         SourceLocation RPLoc);
4992   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4993                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
4994 
4995   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4996   // __builtin_COLUMN()
4997   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4998                                 SourceLocation BuiltinLoc,
4999                                 SourceLocation RPLoc);
5000 
5001   // Build a potentially resolved SourceLocExpr.
5002   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5003                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5004                                 DeclContext *ParentContext);
5005 
5006   // __null
5007   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5008 
5009   bool CheckCaseExpression(Expr *E);
5010 
5011   /// Describes the result of an "if-exists" condition check.
5012   enum IfExistsResult {
5013     /// The symbol exists.
5014     IER_Exists,
5015 
5016     /// The symbol does not exist.
5017     IER_DoesNotExist,
5018 
5019     /// The name is a dependent name, so the results will differ
5020     /// from one instantiation to the next.
5021     IER_Dependent,
5022 
5023     /// An error occurred.
5024     IER_Error
5025   };
5026 
5027   IfExistsResult
5028   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5029                                const DeclarationNameInfo &TargetNameInfo);
5030 
5031   IfExistsResult
5032   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5033                                bool IsIfExists, CXXScopeSpec &SS,
5034                                UnqualifiedId &Name);
5035 
5036   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5037                                         bool IsIfExists,
5038                                         NestedNameSpecifierLoc QualifierLoc,
5039                                         DeclarationNameInfo NameInfo,
5040                                         Stmt *Nested);
5041   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5042                                         bool IsIfExists,
5043                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5044                                         Stmt *Nested);
5045 
5046   //===------------------------- "Block" Extension ------------------------===//
5047 
5048   /// ActOnBlockStart - This callback is invoked when a block literal is
5049   /// started.
5050   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5051 
5052   /// ActOnBlockArguments - This callback allows processing of block arguments.
5053   /// If there are no arguments, this is still invoked.
5054   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5055                            Scope *CurScope);
5056 
5057   /// ActOnBlockError - If there is an error parsing a block, this callback
5058   /// is invoked to pop the information about the block from the action impl.
5059   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5060 
5061   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5062   /// literal was successfully completed.  ^(int x){...}
5063   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5064                                 Scope *CurScope);
5065 
5066   //===---------------------------- Clang Extensions ----------------------===//
5067 
5068   /// __builtin_convertvector(...)
5069   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5070                                     SourceLocation BuiltinLoc,
5071                                     SourceLocation RParenLoc);
5072 
5073   //===---------------------------- OpenCL Features -----------------------===//
5074 
5075   /// __builtin_astype(...)
5076   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5077                              SourceLocation BuiltinLoc,
5078                              SourceLocation RParenLoc);
5079 
5080   //===---------------------------- C++ Features --------------------------===//
5081 
5082   // Act on C++ namespaces
5083   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5084                                SourceLocation NamespaceLoc,
5085                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5086                                SourceLocation LBrace,
5087                                const ParsedAttributesView &AttrList,
5088                                UsingDirectiveDecl *&UsingDecl);
5089   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5090 
5091   NamespaceDecl *getStdNamespace() const;
5092   NamespaceDecl *getOrCreateStdNamespace();
5093 
5094   NamespaceDecl *lookupStdExperimentalNamespace();
5095 
5096   CXXRecordDecl *getStdBadAlloc() const;
5097   EnumDecl *getStdAlignValT() const;
5098 
5099 private:
5100   // A cache representing if we've fully checked the various comparison category
5101   // types stored in ASTContext. The bit-index corresponds to the integer value
5102   // of a ComparisonCategoryType enumerator.
5103   llvm::SmallBitVector FullyCheckedComparisonCategories;
5104 
5105   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5106                                          CXXScopeSpec &SS,
5107                                          ParsedType TemplateTypeTy,
5108                                          IdentifierInfo *MemberOrBase);
5109 
5110 public:
5111   enum class ComparisonCategoryUsage {
5112     /// The '<=>' operator was used in an expression and a builtin operator
5113     /// was selected.
5114     OperatorInExpression,
5115     /// A defaulted 'operator<=>' needed the comparison category. This
5116     /// typically only applies to 'std::strong_ordering', due to the implicit
5117     /// fallback return value.
5118     DefaultedOperator,
5119   };
5120 
5121   /// Lookup the specified comparison category types in the standard
5122   ///   library, an check the VarDecls possibly returned by the operator<=>
5123   ///   builtins for that type.
5124   ///
5125   /// \return The type of the comparison category type corresponding to the
5126   ///   specified Kind, or a null type if an error occurs
5127   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5128                                        SourceLocation Loc,
5129                                        ComparisonCategoryUsage Usage);
5130 
5131   /// Tests whether Ty is an instance of std::initializer_list and, if
5132   /// it is and Element is not NULL, assigns the element type to Element.
5133   bool isStdInitializerList(QualType Ty, QualType *Element);
5134 
5135   /// Looks for the std::initializer_list template and instantiates it
5136   /// with Element, or emits an error if it's not found.
5137   ///
5138   /// \returns The instantiated template, or null on error.
5139   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5140 
5141   /// Determine whether Ctor is an initializer-list constructor, as
5142   /// defined in [dcl.init.list]p2.
5143   bool isInitListConstructor(const FunctionDecl *Ctor);
5144 
5145   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5146                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5147                             SourceLocation IdentLoc,
5148                             IdentifierInfo *NamespcName,
5149                             const ParsedAttributesView &AttrList);
5150 
5151   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5152 
5153   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5154                                SourceLocation NamespaceLoc,
5155                                SourceLocation AliasLoc,
5156                                IdentifierInfo *Alias,
5157                                CXXScopeSpec &SS,
5158                                SourceLocation IdentLoc,
5159                                IdentifierInfo *Ident);
5160 
5161   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5162   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5163                             const LookupResult &PreviousDecls,
5164                             UsingShadowDecl *&PrevShadow);
5165   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5166                                         NamedDecl *Target,
5167                                         UsingShadowDecl *PrevDecl);
5168 
5169   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5170                                    bool HasTypenameKeyword,
5171                                    const CXXScopeSpec &SS,
5172                                    SourceLocation NameLoc,
5173                                    const LookupResult &Previous);
5174   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5175                                bool HasTypename,
5176                                const CXXScopeSpec &SS,
5177                                const DeclarationNameInfo &NameInfo,
5178                                SourceLocation NameLoc);
5179 
5180   NamedDecl *BuildUsingDeclaration(
5181       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5182       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5183       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5184       const ParsedAttributesView &AttrList, bool IsInstantiation);
5185   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5186                                 ArrayRef<NamedDecl *> Expansions);
5187 
5188   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5189 
5190   /// Given a derived-class using shadow declaration for a constructor and the
5191   /// correspnding base class constructor, find or create the implicit
5192   /// synthesized derived class constructor to use for this initialization.
5193   CXXConstructorDecl *
5194   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5195                             ConstructorUsingShadowDecl *DerivedShadow);
5196 
5197   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5198                               SourceLocation UsingLoc,
5199                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5200                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5201                               const ParsedAttributesView &AttrList);
5202   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5203                               MultiTemplateParamsArg TemplateParams,
5204                               SourceLocation UsingLoc, UnqualifiedId &Name,
5205                               const ParsedAttributesView &AttrList,
5206                               TypeResult Type, Decl *DeclFromDeclSpec);
5207 
5208   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5209   /// including handling of its default argument expressions.
5210   ///
5211   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5212   ExprResult
5213   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5214                         NamedDecl *FoundDecl,
5215                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5216                         bool HadMultipleCandidates, bool IsListInitialization,
5217                         bool IsStdInitListInitialization,
5218                         bool RequiresZeroInit, unsigned ConstructKind,
5219                         SourceRange ParenRange);
5220 
5221   /// Build a CXXConstructExpr whose constructor has already been resolved if
5222   /// it denotes an inherited constructor.
5223   ExprResult
5224   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5225                         CXXConstructorDecl *Constructor, bool Elidable,
5226                         MultiExprArg Exprs,
5227                         bool HadMultipleCandidates, bool IsListInitialization,
5228                         bool IsStdInitListInitialization,
5229                         bool RequiresZeroInit, unsigned ConstructKind,
5230                         SourceRange ParenRange);
5231 
5232   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5233   // the constructor can be elidable?
5234   ExprResult
5235   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5236                         NamedDecl *FoundDecl,
5237                         CXXConstructorDecl *Constructor, bool Elidable,
5238                         MultiExprArg Exprs, bool HadMultipleCandidates,
5239                         bool IsListInitialization,
5240                         bool IsStdInitListInitialization, bool RequiresZeroInit,
5241                         unsigned ConstructKind, SourceRange ParenRange);
5242 
5243   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5244 
5245 
5246   /// Instantiate or parse a C++ default argument expression as necessary.
5247   /// Return true on error.
5248   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5249                               ParmVarDecl *Param);
5250 
5251   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5252   /// the default expr if needed.
5253   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5254                                     FunctionDecl *FD,
5255                                     ParmVarDecl *Param);
5256 
5257   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5258   /// constructed variable.
5259   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5260 
5261   /// Helper class that collects exception specifications for
5262   /// implicitly-declared special member functions.
5263   class ImplicitExceptionSpecification {
5264     // Pointer to allow copying
5265     Sema *Self;
5266     // We order exception specifications thus:
5267     // noexcept is the most restrictive, but is only used in C++11.
5268     // throw() comes next.
5269     // Then a throw(collected exceptions)
5270     // Finally no specification, which is expressed as noexcept(false).
5271     // throw(...) is used instead if any called function uses it.
5272     ExceptionSpecificationType ComputedEST;
5273     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5274     SmallVector<QualType, 4> Exceptions;
5275 
5276     void ClearExceptions() {
5277       ExceptionsSeen.clear();
5278       Exceptions.clear();
5279     }
5280 
5281   public:
5282     explicit ImplicitExceptionSpecification(Sema &Self)
5283       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5284       if (!Self.getLangOpts().CPlusPlus11)
5285         ComputedEST = EST_DynamicNone;
5286     }
5287 
5288     /// Get the computed exception specification type.
5289     ExceptionSpecificationType getExceptionSpecType() const {
5290       assert(!isComputedNoexcept(ComputedEST) &&
5291              "noexcept(expr) should not be a possible result");
5292       return ComputedEST;
5293     }
5294 
5295     /// The number of exceptions in the exception specification.
5296     unsigned size() const { return Exceptions.size(); }
5297 
5298     /// The set of exceptions in the exception specification.
5299     const QualType *data() const { return Exceptions.data(); }
5300 
5301     /// Integrate another called method into the collected data.
5302     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5303 
5304     /// Integrate an invoked expression into the collected data.
5305     void CalledExpr(Expr *E) { CalledStmt(E); }
5306 
5307     /// Integrate an invoked statement into the collected data.
5308     void CalledStmt(Stmt *S);
5309 
5310     /// Overwrite an EPI's exception specification with this
5311     /// computed exception specification.
5312     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5313       FunctionProtoType::ExceptionSpecInfo ESI;
5314       ESI.Type = getExceptionSpecType();
5315       if (ESI.Type == EST_Dynamic) {
5316         ESI.Exceptions = Exceptions;
5317       } else if (ESI.Type == EST_None) {
5318         /// C++11 [except.spec]p14:
5319         ///   The exception-specification is noexcept(false) if the set of
5320         ///   potential exceptions of the special member function contains "any"
5321         ESI.Type = EST_NoexceptFalse;
5322         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5323                                                      tok::kw_false).get();
5324       }
5325       return ESI;
5326     }
5327   };
5328 
5329   /// Determine what sort of exception specification a defaulted
5330   /// copy constructor of a class will have.
5331   ImplicitExceptionSpecification
5332   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5333                                            CXXMethodDecl *MD);
5334 
5335   /// Determine what sort of exception specification a defaulted
5336   /// default constructor of a class will have, and whether the parameter
5337   /// will be const.
5338   ImplicitExceptionSpecification
5339   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5340 
5341   /// Determine what sort of exception specification a defaulted
5342   /// copy assignment operator of a class will have, and whether the
5343   /// parameter will be const.
5344   ImplicitExceptionSpecification
5345   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5346 
5347   /// Determine what sort of exception specification a defaulted move
5348   /// constructor of a class will have.
5349   ImplicitExceptionSpecification
5350   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5351 
5352   /// Determine what sort of exception specification a defaulted move
5353   /// assignment operator of a class will have.
5354   ImplicitExceptionSpecification
5355   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5356 
5357   /// Determine what sort of exception specification a defaulted
5358   /// destructor of a class will have.
5359   ImplicitExceptionSpecification
5360   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5361 
5362   /// Determine what sort of exception specification an inheriting
5363   /// constructor of a class will have.
5364   ImplicitExceptionSpecification
5365   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5366                                      CXXConstructorDecl *CD);
5367 
5368   /// Evaluate the implicit exception specification for a defaulted
5369   /// special member function.
5370   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5371 
5372   /// Check the given noexcept-specifier, convert its expression, and compute
5373   /// the appropriate ExceptionSpecificationType.
5374   ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5375                                ExceptionSpecificationType &EST);
5376 
5377   /// Check the given exception-specification and update the
5378   /// exception specification information with the results.
5379   void checkExceptionSpecification(bool IsTopLevel,
5380                                    ExceptionSpecificationType EST,
5381                                    ArrayRef<ParsedType> DynamicExceptions,
5382                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5383                                    Expr *NoexceptExpr,
5384                                    SmallVectorImpl<QualType> &Exceptions,
5385                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5386 
5387   /// Determine if we're in a case where we need to (incorrectly) eagerly
5388   /// parse an exception specification to work around a libstdc++ bug.
5389   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5390 
5391   /// Add an exception-specification to the given member function
5392   /// (or member function template). The exception-specification was parsed
5393   /// after the method itself was declared.
5394   void actOnDelayedExceptionSpecification(Decl *Method,
5395          ExceptionSpecificationType EST,
5396          SourceRange SpecificationRange,
5397          ArrayRef<ParsedType> DynamicExceptions,
5398          ArrayRef<SourceRange> DynamicExceptionRanges,
5399          Expr *NoexceptExpr);
5400 
5401   class InheritedConstructorInfo;
5402 
5403   /// Determine if a special member function should have a deleted
5404   /// definition when it is defaulted.
5405   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5406                                  InheritedConstructorInfo *ICI = nullptr,
5407                                  bool Diagnose = false);
5408 
5409   /// Produce notes explaining why a defaulted function was defined as deleted.
5410   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5411 
5412   /// Declare the implicit default constructor for the given class.
5413   ///
5414   /// \param ClassDecl The class declaration into which the implicit
5415   /// default constructor will be added.
5416   ///
5417   /// \returns The implicitly-declared default constructor.
5418   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5419                                                      CXXRecordDecl *ClassDecl);
5420 
5421   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5422   /// defining this constructor as the default constructor.
5423   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5424                                         CXXConstructorDecl *Constructor);
5425 
5426   /// Declare the implicit destructor for the given class.
5427   ///
5428   /// \param ClassDecl The class declaration into which the implicit
5429   /// destructor will be added.
5430   ///
5431   /// \returns The implicitly-declared destructor.
5432   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5433 
5434   /// DefineImplicitDestructor - Checks for feasibility of
5435   /// defining this destructor as the default destructor.
5436   void DefineImplicitDestructor(SourceLocation CurrentLocation,
5437                                 CXXDestructorDecl *Destructor);
5438 
5439   /// Build an exception spec for destructors that don't have one.
5440   ///
5441   /// C++11 says that user-defined destructors with no exception spec get one
5442   /// that looks as if the destructor was implicitly declared.
5443   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5444 
5445   /// Define the specified inheriting constructor.
5446   void DefineInheritingConstructor(SourceLocation UseLoc,
5447                                    CXXConstructorDecl *Constructor);
5448 
5449   /// Declare the implicit copy constructor for the given class.
5450   ///
5451   /// \param ClassDecl The class declaration into which the implicit
5452   /// copy constructor will be added.
5453   ///
5454   /// \returns The implicitly-declared copy constructor.
5455   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5456 
5457   /// DefineImplicitCopyConstructor - Checks for feasibility of
5458   /// defining this constructor as the copy constructor.
5459   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5460                                      CXXConstructorDecl *Constructor);
5461 
5462   /// Declare the implicit move constructor for the given class.
5463   ///
5464   /// \param ClassDecl The Class declaration into which the implicit
5465   /// move constructor will be added.
5466   ///
5467   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5468   /// declared.
5469   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5470 
5471   /// DefineImplicitMoveConstructor - Checks for feasibility of
5472   /// defining this constructor as the move constructor.
5473   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5474                                      CXXConstructorDecl *Constructor);
5475 
5476   /// Declare the implicit copy assignment operator for the given class.
5477   ///
5478   /// \param ClassDecl The class declaration into which the implicit
5479   /// copy assignment operator will be added.
5480   ///
5481   /// \returns The implicitly-declared copy assignment operator.
5482   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5483 
5484   /// Defines an implicitly-declared copy assignment operator.
5485   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5486                                     CXXMethodDecl *MethodDecl);
5487 
5488   /// Declare the implicit move assignment operator for the given class.
5489   ///
5490   /// \param ClassDecl The Class declaration into which the implicit
5491   /// move assignment operator will be added.
5492   ///
5493   /// \returns The implicitly-declared move assignment operator, or NULL if it
5494   /// wasn't declared.
5495   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5496 
5497   /// Defines an implicitly-declared move assignment operator.
5498   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5499                                     CXXMethodDecl *MethodDecl);
5500 
5501   /// Force the declaration of any implicitly-declared members of this
5502   /// class.
5503   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5504 
5505   /// Check a completed declaration of an implicit special member.
5506   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5507 
5508   /// Determine whether the given function is an implicitly-deleted
5509   /// special member function.
5510   bool isImplicitlyDeleted(FunctionDecl *FD);
5511 
5512   /// Check whether 'this' shows up in the type of a static member
5513   /// function after the (naturally empty) cv-qualifier-seq would be.
5514   ///
5515   /// \returns true if an error occurred.
5516   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5517 
5518   /// Whether this' shows up in the exception specification of a static
5519   /// member function.
5520   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5521 
5522   /// Check whether 'this' shows up in the attributes of the given
5523   /// static member function.
5524   ///
5525   /// \returns true if an error occurred.
5526   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5527 
5528   /// MaybeBindToTemporary - If the passed in expression has a record type with
5529   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5530   /// it simply returns the passed in expression.
5531   ExprResult MaybeBindToTemporary(Expr *E);
5532 
5533   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5534                                MultiExprArg ArgsPtr,
5535                                SourceLocation Loc,
5536                                SmallVectorImpl<Expr*> &ConvertedArgs,
5537                                bool AllowExplicit = false,
5538                                bool IsListInitialization = false);
5539 
5540   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5541                                           SourceLocation NameLoc,
5542                                           IdentifierInfo &Name);
5543 
5544   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5545                                 Scope *S, CXXScopeSpec &SS,
5546                                 bool EnteringContext);
5547   ParsedType getDestructorName(SourceLocation TildeLoc,
5548                                IdentifierInfo &II, SourceLocation NameLoc,
5549                                Scope *S, CXXScopeSpec &SS,
5550                                ParsedType ObjectType,
5551                                bool EnteringContext);
5552 
5553   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5554                                           ParsedType ObjectType);
5555 
5556   // Checks that reinterpret casts don't have undefined behavior.
5557   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5558                                       bool IsDereference, SourceRange Range);
5559 
5560   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5561   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5562                                tok::TokenKind Kind,
5563                                SourceLocation LAngleBracketLoc,
5564                                Declarator &D,
5565                                SourceLocation RAngleBracketLoc,
5566                                SourceLocation LParenLoc,
5567                                Expr *E,
5568                                SourceLocation RParenLoc);
5569 
5570   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5571                                tok::TokenKind Kind,
5572                                TypeSourceInfo *Ty,
5573                                Expr *E,
5574                                SourceRange AngleBrackets,
5575                                SourceRange Parens);
5576 
5577   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5578                                      ExprResult Operand,
5579                                      SourceLocation RParenLoc);
5580 
5581   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5582                                      Expr *Operand, SourceLocation RParenLoc);
5583 
5584   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5585                             SourceLocation TypeidLoc,
5586                             TypeSourceInfo *Operand,
5587                             SourceLocation RParenLoc);
5588   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5589                             SourceLocation TypeidLoc,
5590                             Expr *Operand,
5591                             SourceLocation RParenLoc);
5592 
5593   /// ActOnCXXTypeid - Parse typeid( something ).
5594   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5595                             SourceLocation LParenLoc, bool isType,
5596                             void *TyOrExpr,
5597                             SourceLocation RParenLoc);
5598 
5599   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5600                             SourceLocation TypeidLoc,
5601                             TypeSourceInfo *Operand,
5602                             SourceLocation RParenLoc);
5603   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5604                             SourceLocation TypeidLoc,
5605                             Expr *Operand,
5606                             SourceLocation RParenLoc);
5607 
5608   /// ActOnCXXUuidof - Parse __uuidof( something ).
5609   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5610                             SourceLocation LParenLoc, bool isType,
5611                             void *TyOrExpr,
5612                             SourceLocation RParenLoc);
5613 
5614   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5615   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5616                               tok::TokenKind Operator,
5617                               SourceLocation EllipsisLoc, Expr *RHS,
5618                               SourceLocation RParenLoc);
5619   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5620                               BinaryOperatorKind Operator,
5621                               SourceLocation EllipsisLoc, Expr *RHS,
5622                               SourceLocation RParenLoc,
5623                               Optional<unsigned> NumExpansions);
5624   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5625                                    BinaryOperatorKind Operator);
5626 
5627   //// ActOnCXXThis -  Parse 'this' pointer.
5628   ExprResult ActOnCXXThis(SourceLocation loc);
5629 
5630   /// Build a CXXThisExpr and mark it referenced in the current context.
5631   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5632   void MarkThisReferenced(CXXThisExpr *This);
5633 
5634   /// Try to retrieve the type of the 'this' pointer.
5635   ///
5636   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5637   QualType getCurrentThisType();
5638 
5639   /// When non-NULL, the C++ 'this' expression is allowed despite the
5640   /// current context not being a non-static member function. In such cases,
5641   /// this provides the type used for 'this'.
5642   QualType CXXThisTypeOverride;
5643 
5644   /// RAII object used to temporarily allow the C++ 'this' expression
5645   /// to be used, with the given qualifiers on the current class type.
5646   class CXXThisScopeRAII {
5647     Sema &S;
5648     QualType OldCXXThisTypeOverride;
5649     bool Enabled;
5650 
5651   public:
5652     /// Introduce a new scope where 'this' may be allowed (when enabled),
5653     /// using the given declaration (which is either a class template or a
5654     /// class) along with the given qualifiers.
5655     /// along with the qualifiers placed on '*this'.
5656     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5657                      bool Enabled = true);
5658 
5659     ~CXXThisScopeRAII();
5660   };
5661 
5662   /// Make sure the value of 'this' is actually available in the current
5663   /// context, if it is a potentially evaluated context.
5664   ///
5665   /// \param Loc The location at which the capture of 'this' occurs.
5666   ///
5667   /// \param Explicit Whether 'this' is explicitly captured in a lambda
5668   /// capture list.
5669   ///
5670   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5671   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5672   /// This is useful when enclosing lambdas must speculatively capture
5673   /// 'this' that may or may not be used in certain specializations of
5674   /// a nested generic lambda (depending on whether the name resolves to
5675   /// a non-static member function or a static function).
5676   /// \return returns 'true' if failed, 'false' if success.
5677   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5678       bool BuildAndDiagnose = true,
5679       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5680       bool ByCopy = false);
5681 
5682   /// Determine whether the given type is the type of *this that is used
5683   /// outside of the body of a member function for a type that is currently
5684   /// being defined.
5685   bool isThisOutsideMemberFunctionBody(QualType BaseType);
5686 
5687   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5688   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5689 
5690 
5691   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5692   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5693 
5694   ExprResult
5695   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5696                                  SourceLocation AtLoc, SourceLocation RParen);
5697 
5698   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5699   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5700 
5701   //// ActOnCXXThrow -  Parse throw expressions.
5702   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5703   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5704                            bool IsThrownVarInScope);
5705   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5706 
5707   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5708   /// Can be interpreted either as function-style casting ("int(x)")
5709   /// or class type construction ("ClassType(x,y,z)")
5710   /// or creation of a value-initialized type ("int()").
5711   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5712                                        SourceLocation LParenOrBraceLoc,
5713                                        MultiExprArg Exprs,
5714                                        SourceLocation RParenOrBraceLoc,
5715                                        bool ListInitialization);
5716 
5717   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5718                                        SourceLocation LParenLoc,
5719                                        MultiExprArg Exprs,
5720                                        SourceLocation RParenLoc,
5721                                        bool ListInitialization);
5722 
5723   /// ActOnCXXNew - Parsed a C++ 'new' expression.
5724   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5725                          SourceLocation PlacementLParen,
5726                          MultiExprArg PlacementArgs,
5727                          SourceLocation PlacementRParen,
5728                          SourceRange TypeIdParens, Declarator &D,
5729                          Expr *Initializer);
5730   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5731                          SourceLocation PlacementLParen,
5732                          MultiExprArg PlacementArgs,
5733                          SourceLocation PlacementRParen,
5734                          SourceRange TypeIdParens,
5735                          QualType AllocType,
5736                          TypeSourceInfo *AllocTypeInfo,
5737                          Optional<Expr *> ArraySize,
5738                          SourceRange DirectInitRange,
5739                          Expr *Initializer);
5740 
5741   /// Determine whether \p FD is an aligned allocation or deallocation
5742   /// function that is unavailable.
5743   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5744 
5745   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5746   /// function that is unavailable.
5747   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5748                                             SourceLocation Loc);
5749 
5750   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5751                           SourceRange R);
5752 
5753   /// The scope in which to find allocation functions.
5754   enum AllocationFunctionScope {
5755     /// Only look for allocation functions in the global scope.
5756     AFS_Global,
5757     /// Only look for allocation functions in the scope of the
5758     /// allocated class.
5759     AFS_Class,
5760     /// Look for allocation functions in both the global scope
5761     /// and in the scope of the allocated class.
5762     AFS_Both
5763   };
5764 
5765   /// Finds the overloads of operator new and delete that are appropriate
5766   /// for the allocation.
5767   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5768                                AllocationFunctionScope NewScope,
5769                                AllocationFunctionScope DeleteScope,
5770                                QualType AllocType, bool IsArray,
5771                                bool &PassAlignment, MultiExprArg PlaceArgs,
5772                                FunctionDecl *&OperatorNew,
5773                                FunctionDecl *&OperatorDelete,
5774                                bool Diagnose = true);
5775   void DeclareGlobalNewDelete();
5776   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5777                                        ArrayRef<QualType> Params);
5778 
5779   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5780                                 DeclarationName Name, FunctionDecl* &Operator,
5781                                 bool Diagnose = true);
5782   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5783                                               bool CanProvideSize,
5784                                               bool Overaligned,
5785                                               DeclarationName Name);
5786   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5787                                                       CXXRecordDecl *RD);
5788 
5789   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5790   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5791                             bool UseGlobal, bool ArrayForm,
5792                             Expr *Operand);
5793   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5794                             bool IsDelete, bool CallCanBeVirtual,
5795                             bool WarnOnNonAbstractTypes,
5796                             SourceLocation DtorLoc);
5797 
5798   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5799                                Expr *Operand, SourceLocation RParen);
5800   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5801                                   SourceLocation RParen);
5802 
5803   /// Parsed one of the type trait support pseudo-functions.
5804   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5805                             ArrayRef<ParsedType> Args,
5806                             SourceLocation RParenLoc);
5807   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5808                             ArrayRef<TypeSourceInfo *> Args,
5809                             SourceLocation RParenLoc);
5810 
5811   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5812   /// pseudo-functions.
5813   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5814                                  SourceLocation KWLoc,
5815                                  ParsedType LhsTy,
5816                                  Expr *DimExpr,
5817                                  SourceLocation RParen);
5818 
5819   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5820                                  SourceLocation KWLoc,
5821                                  TypeSourceInfo *TSInfo,
5822                                  Expr *DimExpr,
5823                                  SourceLocation RParen);
5824 
5825   /// ActOnExpressionTrait - Parsed one of the unary type trait support
5826   /// pseudo-functions.
5827   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5828                                   SourceLocation KWLoc,
5829                                   Expr *Queried,
5830                                   SourceLocation RParen);
5831 
5832   ExprResult BuildExpressionTrait(ExpressionTrait OET,
5833                                   SourceLocation KWLoc,
5834                                   Expr *Queried,
5835                                   SourceLocation RParen);
5836 
5837   ExprResult ActOnStartCXXMemberReference(Scope *S,
5838                                           Expr *Base,
5839                                           SourceLocation OpLoc,
5840                                           tok::TokenKind OpKind,
5841                                           ParsedType &ObjectType,
5842                                           bool &MayBePseudoDestructor);
5843 
5844   ExprResult BuildPseudoDestructorExpr(Expr *Base,
5845                                        SourceLocation OpLoc,
5846                                        tok::TokenKind OpKind,
5847                                        const CXXScopeSpec &SS,
5848                                        TypeSourceInfo *ScopeType,
5849                                        SourceLocation CCLoc,
5850                                        SourceLocation TildeLoc,
5851                                      PseudoDestructorTypeStorage DestroyedType);
5852 
5853   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5854                                        SourceLocation OpLoc,
5855                                        tok::TokenKind OpKind,
5856                                        CXXScopeSpec &SS,
5857                                        UnqualifiedId &FirstTypeName,
5858                                        SourceLocation CCLoc,
5859                                        SourceLocation TildeLoc,
5860                                        UnqualifiedId &SecondTypeName);
5861 
5862   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5863                                        SourceLocation OpLoc,
5864                                        tok::TokenKind OpKind,
5865                                        SourceLocation TildeLoc,
5866                                        const DeclSpec& DS);
5867 
5868   /// MaybeCreateExprWithCleanups - If the current full-expression
5869   /// requires any cleanups, surround it with a ExprWithCleanups node.
5870   /// Otherwise, just returns the passed-in expression.
5871   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5872   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5873   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5874 
5875   MaterializeTemporaryExpr *
5876   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5877                                  bool BoundToLvalueReference);
5878 
5879   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
5880     return ActOnFinishFullExpr(
5881         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
5882   }
5883   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5884                                  bool DiscardedValue, bool IsConstexpr = false);
5885   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5886 
5887   // Marks SS invalid if it represents an incomplete type.
5888   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5889 
5890   DeclContext *computeDeclContext(QualType T);
5891   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5892                                   bool EnteringContext = false);
5893   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5894   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5895 
5896   /// The parser has parsed a global nested-name-specifier '::'.
5897   ///
5898   /// \param CCLoc The location of the '::'.
5899   ///
5900   /// \param SS The nested-name-specifier, which will be updated in-place
5901   /// to reflect the parsed nested-name-specifier.
5902   ///
5903   /// \returns true if an error occurred, false otherwise.
5904   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5905 
5906   /// The parser has parsed a '__super' nested-name-specifier.
5907   ///
5908   /// \param SuperLoc The location of the '__super' keyword.
5909   ///
5910   /// \param ColonColonLoc The location of the '::'.
5911   ///
5912   /// \param SS The nested-name-specifier, which will be updated in-place
5913   /// to reflect the parsed nested-name-specifier.
5914   ///
5915   /// \returns true if an error occurred, false otherwise.
5916   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5917                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5918 
5919   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5920                                        bool *CanCorrect = nullptr);
5921   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5922 
5923   /// Keeps information about an identifier in a nested-name-spec.
5924   ///
5925   struct NestedNameSpecInfo {
5926     /// The type of the object, if we're parsing nested-name-specifier in
5927     /// a member access expression.
5928     ParsedType ObjectType;
5929 
5930     /// The identifier preceding the '::'.
5931     IdentifierInfo *Identifier;
5932 
5933     /// The location of the identifier.
5934     SourceLocation IdentifierLoc;
5935 
5936     /// The location of the '::'.
5937     SourceLocation CCLoc;
5938 
5939     /// Creates info object for the most typical case.
5940     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5941              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5942       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5943         CCLoc(ColonColonLoc) {
5944     }
5945 
5946     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5947                        SourceLocation ColonColonLoc, QualType ObjectType)
5948       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5949         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5950     }
5951   };
5952 
5953   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5954                                     NestedNameSpecInfo &IdInfo);
5955 
5956   bool BuildCXXNestedNameSpecifier(Scope *S,
5957                                    NestedNameSpecInfo &IdInfo,
5958                                    bool EnteringContext,
5959                                    CXXScopeSpec &SS,
5960                                    NamedDecl *ScopeLookupResult,
5961                                    bool ErrorRecoveryLookup,
5962                                    bool *IsCorrectedToColon = nullptr,
5963                                    bool OnlyNamespace = false);
5964 
5965   /// The parser has parsed a nested-name-specifier 'identifier::'.
5966   ///
5967   /// \param S The scope in which this nested-name-specifier occurs.
5968   ///
5969   /// \param IdInfo Parser information about an identifier in the
5970   /// nested-name-spec.
5971   ///
5972   /// \param EnteringContext Whether we're entering the context nominated by
5973   /// this nested-name-specifier.
5974   ///
5975   /// \param SS The nested-name-specifier, which is both an input
5976   /// parameter (the nested-name-specifier before this type) and an
5977   /// output parameter (containing the full nested-name-specifier,
5978   /// including this new type).
5979   ///
5980   /// \param ErrorRecoveryLookup If true, then this method is called to improve
5981   /// error recovery. In this case do not emit error message.
5982   ///
5983   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5984   /// are allowed.  The bool value pointed by this parameter is set to 'true'
5985   /// if the identifier is treated as if it was followed by ':', not '::'.
5986   ///
5987   /// \param OnlyNamespace If true, only considers namespaces in lookup.
5988   ///
5989   /// \returns true if an error occurred, false otherwise.
5990   bool ActOnCXXNestedNameSpecifier(Scope *S,
5991                                    NestedNameSpecInfo &IdInfo,
5992                                    bool EnteringContext,
5993                                    CXXScopeSpec &SS,
5994                                    bool ErrorRecoveryLookup = false,
5995                                    bool *IsCorrectedToColon = nullptr,
5996                                    bool OnlyNamespace = false);
5997 
5998   ExprResult ActOnDecltypeExpression(Expr *E);
5999 
6000   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6001                                            const DeclSpec &DS,
6002                                            SourceLocation ColonColonLoc);
6003 
6004   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6005                                  NestedNameSpecInfo &IdInfo,
6006                                  bool EnteringContext);
6007 
6008   /// The parser has parsed a nested-name-specifier
6009   /// 'template[opt] template-name < template-args >::'.
6010   ///
6011   /// \param S The scope in which this nested-name-specifier occurs.
6012   ///
6013   /// \param SS The nested-name-specifier, which is both an input
6014   /// parameter (the nested-name-specifier before this type) and an
6015   /// output parameter (containing the full nested-name-specifier,
6016   /// including this new type).
6017   ///
6018   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6019   /// \param TemplateName the template name.
6020   /// \param TemplateNameLoc The location of the template name.
6021   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6022   /// \param TemplateArgs The template arguments.
6023   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6024   /// \param CCLoc The location of the '::'.
6025   ///
6026   /// \param EnteringContext Whether we're entering the context of the
6027   /// nested-name-specifier.
6028   ///
6029   ///
6030   /// \returns true if an error occurred, false otherwise.
6031   bool ActOnCXXNestedNameSpecifier(Scope *S,
6032                                    CXXScopeSpec &SS,
6033                                    SourceLocation TemplateKWLoc,
6034                                    TemplateTy TemplateName,
6035                                    SourceLocation TemplateNameLoc,
6036                                    SourceLocation LAngleLoc,
6037                                    ASTTemplateArgsPtr TemplateArgs,
6038                                    SourceLocation RAngleLoc,
6039                                    SourceLocation CCLoc,
6040                                    bool EnteringContext);
6041 
6042   /// Given a C++ nested-name-specifier, produce an annotation value
6043   /// that the parser can use later to reconstruct the given
6044   /// nested-name-specifier.
6045   ///
6046   /// \param SS A nested-name-specifier.
6047   ///
6048   /// \returns A pointer containing all of the information in the
6049   /// nested-name-specifier \p SS.
6050   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6051 
6052   /// Given an annotation pointer for a nested-name-specifier, restore
6053   /// the nested-name-specifier structure.
6054   ///
6055   /// \param Annotation The annotation pointer, produced by
6056   /// \c SaveNestedNameSpecifierAnnotation().
6057   ///
6058   /// \param AnnotationRange The source range corresponding to the annotation.
6059   ///
6060   /// \param SS The nested-name-specifier that will be updated with the contents
6061   /// of the annotation pointer.
6062   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6063                                             SourceRange AnnotationRange,
6064                                             CXXScopeSpec &SS);
6065 
6066   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6067 
6068   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6069   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6070   /// After this method is called, according to [C++ 3.4.3p3], names should be
6071   /// looked up in the declarator-id's scope, until the declarator is parsed and
6072   /// ActOnCXXExitDeclaratorScope is called.
6073   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6074   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6075 
6076   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6077   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6078   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6079   /// Used to indicate that names should revert to being looked up in the
6080   /// defining scope.
6081   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6082 
6083   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6084   /// initializer for the declaration 'Dcl'.
6085   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6086   /// static data member of class X, names should be looked up in the scope of
6087   /// class X.
6088   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6089 
6090   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6091   /// initializer for the declaration 'Dcl'.
6092   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6093 
6094   /// Create a new lambda closure type.
6095   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6096                                          TypeSourceInfo *Info,
6097                                          bool KnownDependent,
6098                                          LambdaCaptureDefault CaptureDefault);
6099 
6100   /// Start the definition of a lambda expression.
6101   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6102                                        SourceRange IntroducerRange,
6103                                        TypeSourceInfo *MethodType,
6104                                        SourceLocation EndLoc,
6105                                        ArrayRef<ParmVarDecl *> Params,
6106                                        ConstexprSpecKind ConstexprKind,
6107                                        Expr *TrailingRequiresClause);
6108 
6109   /// Number lambda for linkage purposes if necessary.
6110   void handleLambdaNumbering(
6111       CXXRecordDecl *Class, CXXMethodDecl *Method,
6112       Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6113 
6114   /// Endow the lambda scope info with the relevant properties.
6115   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6116                         CXXMethodDecl *CallOperator,
6117                         SourceRange IntroducerRange,
6118                         LambdaCaptureDefault CaptureDefault,
6119                         SourceLocation CaptureDefaultLoc,
6120                         bool ExplicitParams,
6121                         bool ExplicitResultType,
6122                         bool Mutable);
6123 
6124   /// Perform initialization analysis of the init-capture and perform
6125   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6126   /// not being used to initialize a reference.
6127   ParsedType actOnLambdaInitCaptureInitialization(
6128       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6129       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6130     return ParsedType::make(buildLambdaInitCaptureInitialization(
6131         Loc, ByRef, EllipsisLoc, None, Id,
6132         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6133   }
6134   QualType buildLambdaInitCaptureInitialization(
6135       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6136       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6137       Expr *&Init);
6138 
6139   /// Create a dummy variable within the declcontext of the lambda's
6140   ///  call operator, for name lookup purposes for a lambda init capture.
6141   ///
6142   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6143   ///  variables appropriately.
6144   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6145                                           QualType InitCaptureType,
6146                                           SourceLocation EllipsisLoc,
6147                                           IdentifierInfo *Id,
6148                                           unsigned InitStyle, Expr *Init);
6149 
6150   /// Add an init-capture to a lambda scope.
6151   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6152 
6153   /// Note that we have finished the explicit captures for the
6154   /// given lambda.
6155   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6156 
6157   /// \brief This is called after parsing the explicit template parameter list
6158   /// on a lambda (if it exists) in C++2a.
6159   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6160                                                 ArrayRef<NamedDecl *> TParams,
6161                                                 SourceLocation RAngleLoc);
6162 
6163   /// Introduce the lambda parameters into scope.
6164   void addLambdaParameters(
6165       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6166       CXXMethodDecl *CallOperator, Scope *CurScope);
6167 
6168   /// Deduce a block or lambda's return type based on the return
6169   /// statements present in the body.
6170   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6171 
6172   /// ActOnStartOfLambdaDefinition - This is called just before we start
6173   /// parsing the body of a lambda; it analyzes the explicit captures and
6174   /// arguments, and sets up various data-structures for the body of the
6175   /// lambda.
6176   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6177                                     Declarator &ParamInfo, Scope *CurScope);
6178 
6179   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6180   /// is invoked to pop the information about the lambda.
6181   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6182                         bool IsInstantiation = false);
6183 
6184   /// ActOnLambdaExpr - This is called when the body of a lambda expression
6185   /// was successfully completed.
6186   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6187                              Scope *CurScope);
6188 
6189   /// Does copying/destroying the captured variable have side effects?
6190   bool CaptureHasSideEffects(const sema::Capture &From);
6191 
6192   /// Diagnose if an explicit lambda capture is unused. Returns true if a
6193   /// diagnostic is emitted.
6194   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6195                                    const sema::Capture &From);
6196 
6197   /// Build a FieldDecl suitable to hold the given capture.
6198   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6199 
6200   /// Initialize the given capture with a suitable expression.
6201   ExprResult BuildCaptureInit(const sema::Capture &Capture,
6202                               SourceLocation ImplicitCaptureLoc,
6203                               bool IsOpenMPMapping = false);
6204 
6205   /// Complete a lambda-expression having processed and attached the
6206   /// lambda body.
6207   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6208                              sema::LambdaScopeInfo *LSI);
6209 
6210   /// Get the return type to use for a lambda's conversion function(s) to
6211   /// function pointer type, given the type of the call operator.
6212   QualType
6213   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6214 
6215   /// Define the "body" of the conversion from a lambda object to a
6216   /// function pointer.
6217   ///
6218   /// This routine doesn't actually define a sensible body; rather, it fills
6219   /// in the initialization expression needed to copy the lambda object into
6220   /// the block, and IR generation actually generates the real body of the
6221   /// block pointer conversion.
6222   void DefineImplicitLambdaToFunctionPointerConversion(
6223          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6224 
6225   /// Define the "body" of the conversion from a lambda object to a
6226   /// block pointer.
6227   ///
6228   /// This routine doesn't actually define a sensible body; rather, it fills
6229   /// in the initialization expression needed to copy the lambda object into
6230   /// the block, and IR generation actually generates the real body of the
6231   /// block pointer conversion.
6232   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6233                                                     CXXConversionDecl *Conv);
6234 
6235   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6236                                            SourceLocation ConvLocation,
6237                                            CXXConversionDecl *Conv,
6238                                            Expr *Src);
6239 
6240   /// Check whether the given expression is a valid constraint expression.
6241   /// A diagnostic is emitted if it is not, false is returned, and
6242   /// PossibleNonPrimary will be set to true if the failure might be due to a
6243   /// non-primary expression being used as an atomic constraint.
6244   bool CheckConstraintExpression(Expr *CE, Token NextToken = Token(),
6245                                  bool *PossibleNonPrimary = nullptr,
6246                                  bool IsTrailingRequiresClause = false);
6247 
6248   /// Check whether the given type-dependent expression will be the name of a
6249   /// function or another callable function-like entity (e.g. a function
6250   // template or overload set) for any substitution.
6251   bool IsDependentFunctionNameExpr(Expr *E);
6252 
6253 private:
6254   /// Caches pairs of template-like decls whose associated constraints were
6255   /// checked for subsumption and whether or not the first's constraints did in
6256   /// fact subsume the second's.
6257   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6258   /// Caches the normalized associated constraints of declarations (concepts or
6259   /// constrained declarations). If an error occurred while normalizing the
6260   /// associated constraints of the template or concept, nullptr will be cached
6261   /// here.
6262   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6263       NormalizationCache;
6264 
6265   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6266       SatisfactionCache;
6267 
6268 public:
6269   const NormalizedConstraint *
6270   getNormalizedAssociatedConstraints(
6271       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6272 
6273   /// \brief Check whether the given declaration's associated constraints are
6274   /// at least as constrained than another declaration's according to the
6275   /// partial ordering of constraints.
6276   ///
6277   /// \param Result If no error occurred, receives the result of true if D1 is
6278   /// at least constrained than D2, and false otherwise.
6279   ///
6280   /// \returns true if an error occurred, false otherwise.
6281   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6282                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
6283                               bool &Result);
6284 
6285   /// If D1 was not at least as constrained as D2, but would've been if a pair
6286   /// of atomic constraints involved had been declared in a concept and not
6287   /// repeated in two separate places in code.
6288   /// \returns true if such a diagnostic was emitted, false otherwise.
6289   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6290       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6291 
6292   /// \brief Check whether the given list of constraint expressions are
6293   /// satisfied (as if in a 'conjunction') given template arguments.
6294   /// \param Template the template-like entity that triggered the constraints
6295   /// check (either a concept or a constrained entity).
6296   /// \param ConstraintExprs a list of constraint expressions, treated as if
6297   /// they were 'AND'ed together.
6298   /// \param TemplateArgs the list of template arguments to substitute into the
6299   /// constraint expression.
6300   /// \param TemplateIDRange The source range of the template id that
6301   /// caused the constraints check.
6302   /// \param Satisfaction if true is returned, will contain details of the
6303   /// satisfaction, with enough information to diagnose an unsatisfied
6304   /// expression.
6305   /// \returns true if an error occurred and satisfaction could not be checked,
6306   /// false otherwise.
6307   bool CheckConstraintSatisfaction(
6308       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6309       ArrayRef<TemplateArgument> TemplateArgs,
6310       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6311 
6312   /// \brief Check whether the given non-dependent constraint expression is
6313   /// satisfied. Returns false and updates Satisfaction with the satisfaction
6314   /// verdict if successful, emits a diagnostic and returns true if an error
6315   /// occured and satisfaction could not be determined.
6316   ///
6317   /// \returns true if an error occurred, false otherwise.
6318   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6319                                    ConstraintSatisfaction &Satisfaction);
6320 
6321   /// Check whether the given function decl's trailing requires clause is
6322   /// satisfied, if any. Returns false and updates Satisfaction with the
6323   /// satisfaction verdict if successful, emits a diagnostic and returns true if
6324   /// an error occured and satisfaction could not be determined.
6325   ///
6326   /// \returns true if an error occurred, false otherwise.
6327   bool CheckFunctionConstraints(const FunctionDecl *FD,
6328                                 ConstraintSatisfaction &Satisfaction,
6329                                 SourceLocation UsageLoc = SourceLocation());
6330 
6331 
6332   /// \brief Ensure that the given template arguments satisfy the constraints
6333   /// associated with the given template, emitting a diagnostic if they do not.
6334   ///
6335   /// \param Template The template to which the template arguments are being
6336   /// provided.
6337   ///
6338   /// \param TemplateArgs The converted, canonicalized template arguments.
6339   ///
6340   /// \param TemplateIDRange The source range of the template id that
6341   /// caused the constraints check.
6342   ///
6343   /// \returns true if the constrains are not satisfied or could not be checked
6344   /// for satisfaction, false if the constraints are satisfied.
6345   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6346                                        ArrayRef<TemplateArgument> TemplateArgs,
6347                                              SourceRange TemplateIDRange);
6348 
6349   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6350   /// unsatisfied.
6351   /// \param First whether this is the first time an unsatisfied constraint is
6352   /// diagnosed for this error.
6353   void
6354   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6355                                 bool First = true);
6356 
6357   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6358   /// unsatisfied.
6359   void
6360   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6361                                 bool First = true);
6362 
6363   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6364   /// unsatisfied because it was ill-formed.
6365   void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
6366                                               StringRef Diagnostic);
6367 
6368   void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
6369                                                SourceLocation New);
6370 
6371   // ParseObjCStringLiteral - Parse Objective-C string literals.
6372   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6373                                     ArrayRef<Expr *> Strings);
6374 
6375   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6376 
6377   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6378   /// numeric literal expression. Type of the expression will be "NSNumber *"
6379   /// or "id" if NSNumber is unavailable.
6380   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6381   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6382                                   bool Value);
6383   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6384 
6385   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6386   /// '@' prefixed parenthesized expression. The type of the expression will
6387   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6388   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6389   /// "const char *" or C structure with attribute 'objc_boxable'.
6390   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6391 
6392   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6393                                           Expr *IndexExpr,
6394                                           ObjCMethodDecl *getterMethod,
6395                                           ObjCMethodDecl *setterMethod);
6396 
6397   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6398                                MutableArrayRef<ObjCDictionaryElement> Elements);
6399 
6400   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6401                                   TypeSourceInfo *EncodedTypeInfo,
6402                                   SourceLocation RParenLoc);
6403   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6404                                     CXXConversionDecl *Method,
6405                                     bool HadMultipleCandidates);
6406 
6407   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6408                                        SourceLocation EncodeLoc,
6409                                        SourceLocation LParenLoc,
6410                                        ParsedType Ty,
6411                                        SourceLocation RParenLoc);
6412 
6413   /// ParseObjCSelectorExpression - Build selector expression for \@selector
6414   ExprResult ParseObjCSelectorExpression(Selector Sel,
6415                                          SourceLocation AtLoc,
6416                                          SourceLocation SelLoc,
6417                                          SourceLocation LParenLoc,
6418                                          SourceLocation RParenLoc,
6419                                          bool WarnMultipleSelectors);
6420 
6421   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6422   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6423                                          SourceLocation AtLoc,
6424                                          SourceLocation ProtoLoc,
6425                                          SourceLocation LParenLoc,
6426                                          SourceLocation ProtoIdLoc,
6427                                          SourceLocation RParenLoc);
6428 
6429   //===--------------------------------------------------------------------===//
6430   // C++ Declarations
6431   //
6432   Decl *ActOnStartLinkageSpecification(Scope *S,
6433                                        SourceLocation ExternLoc,
6434                                        Expr *LangStr,
6435                                        SourceLocation LBraceLoc);
6436   Decl *ActOnFinishLinkageSpecification(Scope *S,
6437                                         Decl *LinkageSpec,
6438                                         SourceLocation RBraceLoc);
6439 
6440 
6441   //===--------------------------------------------------------------------===//
6442   // C++ Classes
6443   //
6444   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6445   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6446                           const CXXScopeSpec *SS = nullptr);
6447   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6448 
6449   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6450                             SourceLocation ColonLoc,
6451                             const ParsedAttributesView &Attrs);
6452 
6453   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6454                                  Declarator &D,
6455                                  MultiTemplateParamsArg TemplateParameterLists,
6456                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
6457                                  InClassInitStyle InitStyle);
6458 
6459   void ActOnStartCXXInClassMemberInitializer();
6460   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6461                                               SourceLocation EqualLoc,
6462                                               Expr *Init);
6463 
6464   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6465                                     Scope *S,
6466                                     CXXScopeSpec &SS,
6467                                     IdentifierInfo *MemberOrBase,
6468                                     ParsedType TemplateTypeTy,
6469                                     const DeclSpec &DS,
6470                                     SourceLocation IdLoc,
6471                                     SourceLocation LParenLoc,
6472                                     ArrayRef<Expr *> Args,
6473                                     SourceLocation RParenLoc,
6474                                     SourceLocation EllipsisLoc);
6475 
6476   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6477                                     Scope *S,
6478                                     CXXScopeSpec &SS,
6479                                     IdentifierInfo *MemberOrBase,
6480                                     ParsedType TemplateTypeTy,
6481                                     const DeclSpec &DS,
6482                                     SourceLocation IdLoc,
6483                                     Expr *InitList,
6484                                     SourceLocation EllipsisLoc);
6485 
6486   MemInitResult BuildMemInitializer(Decl *ConstructorD,
6487                                     Scope *S,
6488                                     CXXScopeSpec &SS,
6489                                     IdentifierInfo *MemberOrBase,
6490                                     ParsedType TemplateTypeTy,
6491                                     const DeclSpec &DS,
6492                                     SourceLocation IdLoc,
6493                                     Expr *Init,
6494                                     SourceLocation EllipsisLoc);
6495 
6496   MemInitResult BuildMemberInitializer(ValueDecl *Member,
6497                                        Expr *Init,
6498                                        SourceLocation IdLoc);
6499 
6500   MemInitResult BuildBaseInitializer(QualType BaseType,
6501                                      TypeSourceInfo *BaseTInfo,
6502                                      Expr *Init,
6503                                      CXXRecordDecl *ClassDecl,
6504                                      SourceLocation EllipsisLoc);
6505 
6506   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6507                                            Expr *Init,
6508                                            CXXRecordDecl *ClassDecl);
6509 
6510   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6511                                 CXXCtorInitializer *Initializer);
6512 
6513   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6514                            ArrayRef<CXXCtorInitializer *> Initializers = None);
6515 
6516   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6517 
6518 
6519   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6520   /// mark all the non-trivial destructors of its members and bases as
6521   /// referenced.
6522   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6523                                               CXXRecordDecl *Record);
6524 
6525   /// The list of classes whose vtables have been used within
6526   /// this translation unit, and the source locations at which the
6527   /// first use occurred.
6528   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6529 
6530   /// The list of vtables that are required but have not yet been
6531   /// materialized.
6532   SmallVector<VTableUse, 16> VTableUses;
6533 
6534   /// The set of classes whose vtables have been used within
6535   /// this translation unit, and a bit that will be true if the vtable is
6536   /// required to be emitted (otherwise, it should be emitted only if needed
6537   /// by code generation).
6538   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6539 
6540   /// Load any externally-stored vtable uses.
6541   void LoadExternalVTableUses();
6542 
6543   /// Note that the vtable for the given class was used at the
6544   /// given location.
6545   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6546                       bool DefinitionRequired = false);
6547 
6548   /// Mark the exception specifications of all virtual member functions
6549   /// in the given class as needed.
6550   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6551                                              const CXXRecordDecl *RD);
6552 
6553   /// MarkVirtualMembersReferenced - Will mark all members of the given
6554   /// CXXRecordDecl referenced.
6555   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6556                                     bool ConstexprOnly = false);
6557 
6558   /// Define all of the vtables that have been used in this
6559   /// translation unit and reference any virtual members used by those
6560   /// vtables.
6561   ///
6562   /// \returns true if any work was done, false otherwise.
6563   bool DefineUsedVTables();
6564 
6565   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6566 
6567   void ActOnMemInitializers(Decl *ConstructorDecl,
6568                             SourceLocation ColonLoc,
6569                             ArrayRef<CXXCtorInitializer*> MemInits,
6570                             bool AnyErrors);
6571 
6572   /// Check class-level dllimport/dllexport attribute. The caller must
6573   /// ensure that referenceDLLExportedClassMethods is called some point later
6574   /// when all outer classes of Class are complete.
6575   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6576   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6577 
6578   void referenceDLLExportedClassMethods();
6579 
6580   void propagateDLLAttrToBaseClassTemplate(
6581       CXXRecordDecl *Class, Attr *ClassAttr,
6582       ClassTemplateSpecializationDecl *BaseTemplateSpec,
6583       SourceLocation BaseLoc);
6584 
6585   /// Add gsl::Pointer attribute to std::container::iterator
6586   /// \param ND The declaration that introduces the name
6587   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6588   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6589 
6590   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6591   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6592 
6593   /// Add [[gsl::Pointer]] attributes for std:: types.
6594   void inferGslPointerAttribute(TypedefNameDecl *TD);
6595 
6596   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6597 
6598   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6599   /// conditions that are needed for the attribute to have an effect.
6600   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6601 
6602   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6603                                          Decl *TagDecl, SourceLocation LBrac,
6604                                          SourceLocation RBrac,
6605                                          const ParsedAttributesView &AttrList);
6606   void ActOnFinishCXXMemberDecls();
6607   void ActOnFinishCXXNonNestedClass();
6608 
6609   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6610   unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
6611   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6612   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6613   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6614   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6615   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6616   void ActOnFinishDelayedMemberInitializers(Decl *Record);
6617   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6618                                 CachedTokens &Toks);
6619   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6620   bool IsInsideALocalClassWithinATemplateFunction();
6621 
6622   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6623                                      Expr *AssertExpr,
6624                                      Expr *AssertMessageExpr,
6625                                      SourceLocation RParenLoc);
6626   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6627                                      Expr *AssertExpr,
6628                                      StringLiteral *AssertMessageExpr,
6629                                      SourceLocation RParenLoc,
6630                                      bool Failed);
6631 
6632   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6633                                   SourceLocation FriendLoc,
6634                                   TypeSourceInfo *TSInfo);
6635   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6636                             MultiTemplateParamsArg TemplateParams);
6637   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6638                                      MultiTemplateParamsArg TemplateParams);
6639 
6640   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6641                                       StorageClass& SC);
6642   void CheckConstructor(CXXConstructorDecl *Constructor);
6643   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6644                                      StorageClass& SC);
6645   bool CheckDestructor(CXXDestructorDecl *Destructor);
6646   void CheckConversionDeclarator(Declarator &D, QualType &R,
6647                                  StorageClass& SC);
6648   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6649   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6650                                      StorageClass &SC);
6651   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6652 
6653   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6654 
6655   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6656                                              CXXSpecialMember CSM);
6657   void CheckDelayedMemberExceptionSpecs();
6658 
6659   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6660                                           DefaultedComparisonKind DCK);
6661   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6662                                          FunctionDecl *Spaceship);
6663   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6664                                  DefaultedComparisonKind DCK);
6665 
6666   //===--------------------------------------------------------------------===//
6667   // C++ Derived Classes
6668   //
6669 
6670   /// ActOnBaseSpecifier - Parsed a base specifier
6671   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6672                                        SourceRange SpecifierRange,
6673                                        bool Virtual, AccessSpecifier Access,
6674                                        TypeSourceInfo *TInfo,
6675                                        SourceLocation EllipsisLoc);
6676 
6677   BaseResult ActOnBaseSpecifier(Decl *classdecl,
6678                                 SourceRange SpecifierRange,
6679                                 ParsedAttributes &Attrs,
6680                                 bool Virtual, AccessSpecifier Access,
6681                                 ParsedType basetype,
6682                                 SourceLocation BaseLoc,
6683                                 SourceLocation EllipsisLoc);
6684 
6685   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6686                             MutableArrayRef<CXXBaseSpecifier *> Bases);
6687   void ActOnBaseSpecifiers(Decl *ClassDecl,
6688                            MutableArrayRef<CXXBaseSpecifier *> Bases);
6689 
6690   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6691   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6692                      CXXBasePaths &Paths);
6693 
6694   // FIXME: I don't like this name.
6695   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6696 
6697   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6698                                     SourceLocation Loc, SourceRange Range,
6699                                     CXXCastPath *BasePath = nullptr,
6700                                     bool IgnoreAccess = false);
6701   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6702                                     unsigned InaccessibleBaseID,
6703                                     unsigned AmbigiousBaseConvID,
6704                                     SourceLocation Loc, SourceRange Range,
6705                                     DeclarationName Name,
6706                                     CXXCastPath *BasePath,
6707                                     bool IgnoreAccess = false);
6708 
6709   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6710 
6711   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6712                                          const CXXMethodDecl *Old);
6713 
6714   /// CheckOverridingFunctionReturnType - Checks whether the return types are
6715   /// covariant, according to C++ [class.virtual]p5.
6716   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6717                                          const CXXMethodDecl *Old);
6718 
6719   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6720   /// spec is a subset of base spec.
6721   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6722                                             const CXXMethodDecl *Old);
6723 
6724   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6725 
6726   /// CheckOverrideControl - Check C++11 override control semantics.
6727   void CheckOverrideControl(NamedDecl *D);
6728 
6729   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6730   /// not used in the declaration of an overriding method.
6731   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
6732 
6733   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6734   /// overrides a virtual member function marked 'final', according to
6735   /// C++11 [class.virtual]p4.
6736   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6737                                               const CXXMethodDecl *Old);
6738 
6739 
6740   //===--------------------------------------------------------------------===//
6741   // C++ Access Control
6742   //
6743 
6744   enum AccessResult {
6745     AR_accessible,
6746     AR_inaccessible,
6747     AR_dependent,
6748     AR_delayed
6749   };
6750 
6751   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6752                                 NamedDecl *PrevMemberDecl,
6753                                 AccessSpecifier LexicalAS);
6754 
6755   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6756                                            DeclAccessPair FoundDecl);
6757   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6758                                            DeclAccessPair FoundDecl);
6759   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6760                                      SourceRange PlacementRange,
6761                                      CXXRecordDecl *NamingClass,
6762                                      DeclAccessPair FoundDecl,
6763                                      bool Diagnose = true);
6764   AccessResult CheckConstructorAccess(SourceLocation Loc,
6765                                       CXXConstructorDecl *D,
6766                                       DeclAccessPair FoundDecl,
6767                                       const InitializedEntity &Entity,
6768                                       bool IsCopyBindingRefToTemp = false);
6769   AccessResult CheckConstructorAccess(SourceLocation Loc,
6770                                       CXXConstructorDecl *D,
6771                                       DeclAccessPair FoundDecl,
6772                                       const InitializedEntity &Entity,
6773                                       const PartialDiagnostic &PDiag);
6774   AccessResult CheckDestructorAccess(SourceLocation Loc,
6775                                      CXXDestructorDecl *Dtor,
6776                                      const PartialDiagnostic &PDiag,
6777                                      QualType objectType = QualType());
6778   AccessResult CheckFriendAccess(NamedDecl *D);
6779   AccessResult CheckMemberAccess(SourceLocation UseLoc,
6780                                  CXXRecordDecl *NamingClass,
6781                                  DeclAccessPair Found);
6782   AccessResult
6783   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
6784                                      CXXRecordDecl *DecomposedClass,
6785                                      DeclAccessPair Field);
6786   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6787                                          Expr *ObjectExpr,
6788                                          Expr *ArgExpr,
6789                                          DeclAccessPair FoundDecl);
6790   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6791                                           DeclAccessPair FoundDecl);
6792   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6793                                     QualType Base, QualType Derived,
6794                                     const CXXBasePath &Path,
6795                                     unsigned DiagID,
6796                                     bool ForceCheck = false,
6797                                     bool ForceUnprivileged = false);
6798   void CheckLookupAccess(const LookupResult &R);
6799   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
6800                           QualType BaseType);
6801   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
6802                                      DeclAccessPair Found, QualType ObjectType,
6803                                      SourceLocation Loc,
6804                                      const PartialDiagnostic &Diag);
6805   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
6806                                      DeclAccessPair Found,
6807                                      QualType ObjectType) {
6808     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
6809                                          SourceLocation(), PDiag());
6810   }
6811 
6812   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6813                          const MultiLevelTemplateArgumentList &TemplateArgs);
6814   void PerformDependentDiagnostics(const DeclContext *Pattern,
6815                         const MultiLevelTemplateArgumentList &TemplateArgs);
6816 
6817   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6818 
6819   /// When true, access checking violations are treated as SFINAE
6820   /// failures rather than hard errors.
6821   bool AccessCheckingSFINAE;
6822 
6823   enum AbstractDiagSelID {
6824     AbstractNone = -1,
6825     AbstractReturnType,
6826     AbstractParamType,
6827     AbstractVariableType,
6828     AbstractFieldType,
6829     AbstractIvarType,
6830     AbstractSynthesizedIvarType,
6831     AbstractArrayType
6832   };
6833 
6834   bool isAbstractType(SourceLocation Loc, QualType T);
6835   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6836                               TypeDiagnoser &Diagnoser);
6837   template <typename... Ts>
6838   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6839                               const Ts &...Args) {
6840     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6841     return RequireNonAbstractType(Loc, T, Diagnoser);
6842   }
6843 
6844   void DiagnoseAbstractType(const CXXRecordDecl *RD);
6845 
6846   //===--------------------------------------------------------------------===//
6847   // C++ Overloaded Operators [C++ 13.5]
6848   //
6849 
6850   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6851 
6852   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6853 
6854   //===--------------------------------------------------------------------===//
6855   // C++ Templates [C++ 14]
6856   //
6857   void FilterAcceptableTemplateNames(LookupResult &R,
6858                                      bool AllowFunctionTemplates = true,
6859                                      bool AllowDependent = true);
6860   bool hasAnyAcceptableTemplateNames(LookupResult &R,
6861                                      bool AllowFunctionTemplates = true,
6862                                      bool AllowDependent = true,
6863                                      bool AllowNonTemplateFunctions = false);
6864   /// Try to interpret the lookup result D as a template-name.
6865   ///
6866   /// \param D A declaration found by name lookup.
6867   /// \param AllowFunctionTemplates Whether function templates should be
6868   ///        considered valid results.
6869   /// \param AllowDependent Whether unresolved using declarations (that might
6870   ///        name templates) should be considered valid results.
6871   NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
6872                                    bool AllowFunctionTemplates = true,
6873                                    bool AllowDependent = true);
6874 
6875   enum class AssumedTemplateKind {
6876     /// This is not assumed to be a template name.
6877     None,
6878     /// This is assumed to be a template name because lookup found nothing.
6879     FoundNothing,
6880     /// This is assumed to be a template name because lookup found one or more
6881     /// functions (but no function templates).
6882     FoundFunctions,
6883   };
6884   bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6885                           QualType ObjectType, bool EnteringContext,
6886                           bool &MemberOfUnknownSpecialization,
6887                           SourceLocation TemplateKWLoc = SourceLocation(),
6888                           AssumedTemplateKind *ATK = nullptr,
6889                           bool Disambiguation = false);
6890 
6891   TemplateNameKind isTemplateName(Scope *S,
6892                                   CXXScopeSpec &SS,
6893                                   bool hasTemplateKeyword,
6894                                   const UnqualifiedId &Name,
6895                                   ParsedType ObjectType,
6896                                   bool EnteringContext,
6897                                   TemplateTy &Template,
6898                                   bool &MemberOfUnknownSpecialization,
6899                                   bool Disambiguation = false);
6900 
6901   /// Try to resolve an undeclared template name as a type template.
6902   ///
6903   /// Sets II to the identifier corresponding to the template name, and updates
6904   /// Name to a corresponding (typo-corrected) type template name and TNK to
6905   /// the corresponding kind, if possible.
6906   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
6907                                        TemplateNameKind &TNK,
6908                                        SourceLocation NameLoc,
6909                                        IdentifierInfo *&II);
6910 
6911   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
6912                                         SourceLocation NameLoc,
6913                                         bool Diagnose = true);
6914 
6915   /// Determine whether a particular identifier might be the name in a C++1z
6916   /// deduction-guide declaration.
6917   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6918                             SourceLocation NameLoc,
6919                             ParsedTemplateTy *Template = nullptr);
6920 
6921   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6922                                    SourceLocation IILoc,
6923                                    Scope *S,
6924                                    const CXXScopeSpec *SS,
6925                                    TemplateTy &SuggestedTemplate,
6926                                    TemplateNameKind &SuggestedKind);
6927 
6928   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6929                                       NamedDecl *Instantiation,
6930                                       bool InstantiatedFromMember,
6931                                       const NamedDecl *Pattern,
6932                                       const NamedDecl *PatternDef,
6933                                       TemplateSpecializationKind TSK,
6934                                       bool Complain = true);
6935 
6936   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6937   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6938 
6939   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6940                                 SourceLocation EllipsisLoc,
6941                                 SourceLocation KeyLoc,
6942                                 IdentifierInfo *ParamName,
6943                                 SourceLocation ParamNameLoc,
6944                                 unsigned Depth, unsigned Position,
6945                                 SourceLocation EqualLoc,
6946                                 ParsedType DefaultArg, bool HasTypeConstraint);
6947 
6948   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
6949                            TemplateIdAnnotation *TypeConstraint,
6950                            TemplateTypeParmDecl *ConstrainedParameter,
6951                            SourceLocation EllipsisLoc);
6952 
6953   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
6954                             DeclarationNameInfo NameInfo,
6955                             ConceptDecl *NamedConcept,
6956                             const TemplateArgumentListInfo *TemplateArgs,
6957                             TemplateTypeParmDecl *ConstrainedParameter,
6958                             SourceLocation EllipsisLoc);
6959 
6960   bool AttachTypeConstraint(AutoTypeLoc TL,
6961                             NonTypeTemplateParmDecl *ConstrainedParameter,
6962                             SourceLocation EllipsisLoc);
6963 
6964   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6965                                              SourceLocation Loc);
6966   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6967 
6968   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6969                                       unsigned Depth,
6970                                       unsigned Position,
6971                                       SourceLocation EqualLoc,
6972                                       Expr *DefaultArg);
6973   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6974                                        SourceLocation TmpLoc,
6975                                        TemplateParameterList *Params,
6976                                        SourceLocation EllipsisLoc,
6977                                        IdentifierInfo *ParamName,
6978                                        SourceLocation ParamNameLoc,
6979                                        unsigned Depth,
6980                                        unsigned Position,
6981                                        SourceLocation EqualLoc,
6982                                        ParsedTemplateArgument DefaultArg);
6983 
6984   TemplateParameterList *
6985   ActOnTemplateParameterList(unsigned Depth,
6986                              SourceLocation ExportLoc,
6987                              SourceLocation TemplateLoc,
6988                              SourceLocation LAngleLoc,
6989                              ArrayRef<NamedDecl *> Params,
6990                              SourceLocation RAngleLoc,
6991                              Expr *RequiresClause);
6992 
6993   /// The context in which we are checking a template parameter list.
6994   enum TemplateParamListContext {
6995     TPC_ClassTemplate,
6996     TPC_VarTemplate,
6997     TPC_FunctionTemplate,
6998     TPC_ClassTemplateMember,
6999     TPC_FriendClassTemplate,
7000     TPC_FriendFunctionTemplate,
7001     TPC_FriendFunctionTemplateDefinition,
7002     TPC_TypeAliasTemplate
7003   };
7004 
7005   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7006                                   TemplateParameterList *OldParams,
7007                                   TemplateParamListContext TPC,
7008                                   SkipBodyInfo *SkipBody = nullptr);
7009   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7010       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7011       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7012       ArrayRef<TemplateParameterList *> ParamLists,
7013       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7014       bool SuppressDiagnostic = false);
7015 
7016   DeclResult CheckClassTemplate(
7017       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7018       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7019       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7020       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7021       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7022       TemplateParameterList **OuterTemplateParamLists,
7023       SkipBodyInfo *SkipBody = nullptr);
7024 
7025   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7026                                                     QualType NTTPType,
7027                                                     SourceLocation Loc);
7028 
7029   /// Get a template argument mapping the given template parameter to itself,
7030   /// e.g. for X in \c template<int X>, this would return an expression template
7031   /// argument referencing X.
7032   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7033                                                      SourceLocation Location);
7034 
7035   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7036                                   TemplateArgumentListInfo &Out);
7037 
7038   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7039 
7040   void NoteAllFoundTemplates(TemplateName Name);
7041 
7042   QualType CheckTemplateIdType(TemplateName Template,
7043                                SourceLocation TemplateLoc,
7044                               TemplateArgumentListInfo &TemplateArgs);
7045 
7046   TypeResult
7047   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7048                       TemplateTy Template, IdentifierInfo *TemplateII,
7049                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7050                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7051                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7052 
7053   /// Parsed an elaborated-type-specifier that refers to a template-id,
7054   /// such as \c class T::template apply<U>.
7055   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7056                                     TypeSpecifierType TagSpec,
7057                                     SourceLocation TagLoc,
7058                                     CXXScopeSpec &SS,
7059                                     SourceLocation TemplateKWLoc,
7060                                     TemplateTy TemplateD,
7061                                     SourceLocation TemplateLoc,
7062                                     SourceLocation LAngleLoc,
7063                                     ASTTemplateArgsPtr TemplateArgsIn,
7064                                     SourceLocation RAngleLoc);
7065 
7066   DeclResult ActOnVarTemplateSpecialization(
7067       Scope *S, Declarator &D, TypeSourceInfo *DI,
7068       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7069       StorageClass SC, bool IsPartialSpecialization);
7070 
7071   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7072                                 SourceLocation TemplateLoc,
7073                                 SourceLocation TemplateNameLoc,
7074                                 const TemplateArgumentListInfo &TemplateArgs);
7075 
7076   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7077                                 const DeclarationNameInfo &NameInfo,
7078                                 VarTemplateDecl *Template,
7079                                 SourceLocation TemplateLoc,
7080                                 const TemplateArgumentListInfo *TemplateArgs);
7081 
7082   ExprResult
7083   CheckConceptTemplateId(const CXXScopeSpec &SS,
7084                          SourceLocation TemplateKWLoc,
7085                          const DeclarationNameInfo &ConceptNameInfo,
7086                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7087                          const TemplateArgumentListInfo *TemplateArgs);
7088 
7089   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7090 
7091   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7092                                  SourceLocation TemplateKWLoc,
7093                                  LookupResult &R,
7094                                  bool RequiresADL,
7095                                const TemplateArgumentListInfo *TemplateArgs);
7096 
7097   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7098                                           SourceLocation TemplateKWLoc,
7099                                const DeclarationNameInfo &NameInfo,
7100                                const TemplateArgumentListInfo *TemplateArgs);
7101 
7102   TemplateNameKind ActOnDependentTemplateName(
7103       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7104       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7105       TemplateTy &Template, bool AllowInjectedClassName = false);
7106 
7107   DeclResult ActOnClassTemplateSpecialization(
7108       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7109       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7110       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7111       MultiTemplateParamsArg TemplateParameterLists,
7112       SkipBodyInfo *SkipBody = nullptr);
7113 
7114   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7115                                               TemplateDecl *PrimaryTemplate,
7116                                               unsigned NumExplicitArgs,
7117                                               ArrayRef<TemplateArgument> Args);
7118   void CheckTemplatePartialSpecialization(
7119       ClassTemplatePartialSpecializationDecl *Partial);
7120   void CheckTemplatePartialSpecialization(
7121       VarTemplatePartialSpecializationDecl *Partial);
7122 
7123   Decl *ActOnTemplateDeclarator(Scope *S,
7124                                 MultiTemplateParamsArg TemplateParameterLists,
7125                                 Declarator &D);
7126 
7127   bool
7128   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7129                                          TemplateSpecializationKind NewTSK,
7130                                          NamedDecl *PrevDecl,
7131                                          TemplateSpecializationKind PrevTSK,
7132                                          SourceLocation PrevPtOfInstantiation,
7133                                          bool &SuppressNew);
7134 
7135   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7136                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
7137                                                     LookupResult &Previous);
7138 
7139   bool CheckFunctionTemplateSpecialization(
7140       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7141       LookupResult &Previous, bool QualifiedFriend = false);
7142   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7143   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7144 
7145   DeclResult ActOnExplicitInstantiation(
7146       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7147       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7148       TemplateTy Template, SourceLocation TemplateNameLoc,
7149       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7150       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7151 
7152   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7153                                         SourceLocation TemplateLoc,
7154                                         unsigned TagSpec, SourceLocation KWLoc,
7155                                         CXXScopeSpec &SS, IdentifierInfo *Name,
7156                                         SourceLocation NameLoc,
7157                                         const ParsedAttributesView &Attr);
7158 
7159   DeclResult ActOnExplicitInstantiation(Scope *S,
7160                                         SourceLocation ExternLoc,
7161                                         SourceLocation TemplateLoc,
7162                                         Declarator &D);
7163 
7164   TemplateArgumentLoc
7165   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7166                                           SourceLocation TemplateLoc,
7167                                           SourceLocation RAngleLoc,
7168                                           Decl *Param,
7169                                           SmallVectorImpl<TemplateArgument>
7170                                             &Converted,
7171                                           bool &HasDefaultArg);
7172 
7173   /// Specifies the context in which a particular template
7174   /// argument is being checked.
7175   enum CheckTemplateArgumentKind {
7176     /// The template argument was specified in the code or was
7177     /// instantiated with some deduced template arguments.
7178     CTAK_Specified,
7179 
7180     /// The template argument was deduced via template argument
7181     /// deduction.
7182     CTAK_Deduced,
7183 
7184     /// The template argument was deduced from an array bound
7185     /// via template argument deduction.
7186     CTAK_DeducedFromArrayBound
7187   };
7188 
7189   bool CheckTemplateArgument(NamedDecl *Param,
7190                              TemplateArgumentLoc &Arg,
7191                              NamedDecl *Template,
7192                              SourceLocation TemplateLoc,
7193                              SourceLocation RAngleLoc,
7194                              unsigned ArgumentPackIndex,
7195                            SmallVectorImpl<TemplateArgument> &Converted,
7196                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
7197 
7198   /// Check that the given template arguments can be be provided to
7199   /// the given template, converting the arguments along the way.
7200   ///
7201   /// \param Template The template to which the template arguments are being
7202   /// provided.
7203   ///
7204   /// \param TemplateLoc The location of the template name in the source.
7205   ///
7206   /// \param TemplateArgs The list of template arguments. If the template is
7207   /// a template template parameter, this function may extend the set of
7208   /// template arguments to also include substituted, defaulted template
7209   /// arguments.
7210   ///
7211   /// \param PartialTemplateArgs True if the list of template arguments is
7212   /// intentionally partial, e.g., because we're checking just the initial
7213   /// set of template arguments.
7214   ///
7215   /// \param Converted Will receive the converted, canonicalized template
7216   /// arguments.
7217   ///
7218   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7219   /// contain the converted forms of the template arguments as written.
7220   /// Otherwise, \p TemplateArgs will not be modified.
7221   ///
7222   /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7223   /// receive true if the cause for the error is the associated constraints of
7224   /// the template not being satisfied by the template arguments.
7225   ///
7226   /// \returns true if an error occurred, false otherwise.
7227   bool CheckTemplateArgumentList(TemplateDecl *Template,
7228                                  SourceLocation TemplateLoc,
7229                                  TemplateArgumentListInfo &TemplateArgs,
7230                                  bool PartialTemplateArgs,
7231                                  SmallVectorImpl<TemplateArgument> &Converted,
7232                                  bool UpdateArgsWithConversions = true,
7233                                  bool *ConstraintsNotSatisfied = nullptr);
7234 
7235   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7236                                  TemplateArgumentLoc &Arg,
7237                            SmallVectorImpl<TemplateArgument> &Converted);
7238 
7239   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7240                              TypeSourceInfo *Arg);
7241   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7242                                    QualType InstantiatedParamType, Expr *Arg,
7243                                    TemplateArgument &Converted,
7244                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
7245   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7246                                      TemplateParameterList *Params,
7247                                      TemplateArgumentLoc &Arg);
7248 
7249   ExprResult
7250   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7251                                           QualType ParamType,
7252                                           SourceLocation Loc);
7253   ExprResult
7254   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7255                                               SourceLocation Loc);
7256 
7257   /// Enumeration describing how template parameter lists are compared
7258   /// for equality.
7259   enum TemplateParameterListEqualKind {
7260     /// We are matching the template parameter lists of two templates
7261     /// that might be redeclarations.
7262     ///
7263     /// \code
7264     /// template<typename T> struct X;
7265     /// template<typename T> struct X;
7266     /// \endcode
7267     TPL_TemplateMatch,
7268 
7269     /// We are matching the template parameter lists of two template
7270     /// template parameters as part of matching the template parameter lists
7271     /// of two templates that might be redeclarations.
7272     ///
7273     /// \code
7274     /// template<template<int I> class TT> struct X;
7275     /// template<template<int Value> class Other> struct X;
7276     /// \endcode
7277     TPL_TemplateTemplateParmMatch,
7278 
7279     /// We are matching the template parameter lists of a template
7280     /// template argument against the template parameter lists of a template
7281     /// template parameter.
7282     ///
7283     /// \code
7284     /// template<template<int Value> class Metafun> struct X;
7285     /// template<int Value> struct integer_c;
7286     /// X<integer_c> xic;
7287     /// \endcode
7288     TPL_TemplateTemplateArgumentMatch
7289   };
7290 
7291   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7292                                       TemplateParameterList *Old,
7293                                       bool Complain,
7294                                       TemplateParameterListEqualKind Kind,
7295                                       SourceLocation TemplateArgLoc
7296                                         = SourceLocation());
7297 
7298   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7299 
7300   /// Called when the parser has parsed a C++ typename
7301   /// specifier, e.g., "typename T::type".
7302   ///
7303   /// \param S The scope in which this typename type occurs.
7304   /// \param TypenameLoc the location of the 'typename' keyword
7305   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7306   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7307   /// \param IdLoc the location of the identifier.
7308   TypeResult
7309   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7310                     const CXXScopeSpec &SS, const IdentifierInfo &II,
7311                     SourceLocation IdLoc);
7312 
7313   /// Called when the parser has parsed a C++ typename
7314   /// specifier that ends in a template-id, e.g.,
7315   /// "typename MetaFun::template apply<T1, T2>".
7316   ///
7317   /// \param S The scope in which this typename type occurs.
7318   /// \param TypenameLoc the location of the 'typename' keyword
7319   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7320   /// \param TemplateLoc the location of the 'template' keyword, if any.
7321   /// \param TemplateName The template name.
7322   /// \param TemplateII The identifier used to name the template.
7323   /// \param TemplateIILoc The location of the template name.
7324   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7325   /// \param TemplateArgs The template arguments.
7326   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7327   TypeResult
7328   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7329                     const CXXScopeSpec &SS,
7330                     SourceLocation TemplateLoc,
7331                     TemplateTy TemplateName,
7332                     IdentifierInfo *TemplateII,
7333                     SourceLocation TemplateIILoc,
7334                     SourceLocation LAngleLoc,
7335                     ASTTemplateArgsPtr TemplateArgs,
7336                     SourceLocation RAngleLoc);
7337 
7338   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7339                              SourceLocation KeywordLoc,
7340                              NestedNameSpecifierLoc QualifierLoc,
7341                              const IdentifierInfo &II,
7342                              SourceLocation IILoc,
7343                              TypeSourceInfo **TSI,
7344                              bool DeducedTSTContext);
7345 
7346   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7347                              SourceLocation KeywordLoc,
7348                              NestedNameSpecifierLoc QualifierLoc,
7349                              const IdentifierInfo &II,
7350                              SourceLocation IILoc,
7351                              bool DeducedTSTContext = true);
7352 
7353 
7354   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7355                                                     SourceLocation Loc,
7356                                                     DeclarationName Name);
7357   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7358 
7359   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7360   bool RebuildTemplateParamsInCurrentInstantiation(
7361                                                 TemplateParameterList *Params);
7362 
7363   std::string
7364   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7365                                   const TemplateArgumentList &Args);
7366 
7367   std::string
7368   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7369                                   const TemplateArgument *Args,
7370                                   unsigned NumArgs);
7371 
7372   //===--------------------------------------------------------------------===//
7373   // C++ Concepts
7374   //===--------------------------------------------------------------------===//
7375   Decl *ActOnConceptDefinition(
7376       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7377       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7378 
7379   RequiresExprBodyDecl *
7380   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7381                          ArrayRef<ParmVarDecl *> LocalParameters,
7382                          Scope *BodyScope);
7383   void ActOnFinishRequiresExpr();
7384   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7385   concepts::Requirement *ActOnTypeRequirement(
7386       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7387       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7388   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7389                                                   SourceLocation NoexceptLoc);
7390   concepts::Requirement *
7391   ActOnCompoundRequirement(
7392       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7393       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7394   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7395   concepts::ExprRequirement *
7396   BuildExprRequirement(
7397       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7398       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7399   concepts::ExprRequirement *
7400   BuildExprRequirement(
7401       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7402       bool IsSatisfied, SourceLocation NoexceptLoc,
7403       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7404   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7405   concepts::TypeRequirement *
7406   BuildTypeRequirement(
7407       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7408   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
7409   concepts::NestedRequirement *
7410   BuildNestedRequirement(
7411       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7412   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
7413                                RequiresExprBodyDecl *Body,
7414                                ArrayRef<ParmVarDecl *> LocalParameters,
7415                                ArrayRef<concepts::Requirement *> Requirements,
7416                                SourceLocation ClosingBraceLoc);
7417 
7418   //===--------------------------------------------------------------------===//
7419   // C++ Variadic Templates (C++0x [temp.variadic])
7420   //===--------------------------------------------------------------------===//
7421 
7422   /// Determine whether an unexpanded parameter pack might be permitted in this
7423   /// location. Useful for error recovery.
7424   bool isUnexpandedParameterPackPermitted();
7425 
7426   /// The context in which an unexpanded parameter pack is
7427   /// being diagnosed.
7428   ///
7429   /// Note that the values of this enumeration line up with the first
7430   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7431   enum UnexpandedParameterPackContext {
7432     /// An arbitrary expression.
7433     UPPC_Expression = 0,
7434 
7435     /// The base type of a class type.
7436     UPPC_BaseType,
7437 
7438     /// The type of an arbitrary declaration.
7439     UPPC_DeclarationType,
7440 
7441     /// The type of a data member.
7442     UPPC_DataMemberType,
7443 
7444     /// The size of a bit-field.
7445     UPPC_BitFieldWidth,
7446 
7447     /// The expression in a static assertion.
7448     UPPC_StaticAssertExpression,
7449 
7450     /// The fixed underlying type of an enumeration.
7451     UPPC_FixedUnderlyingType,
7452 
7453     /// The enumerator value.
7454     UPPC_EnumeratorValue,
7455 
7456     /// A using declaration.
7457     UPPC_UsingDeclaration,
7458 
7459     /// A friend declaration.
7460     UPPC_FriendDeclaration,
7461 
7462     /// A declaration qualifier.
7463     UPPC_DeclarationQualifier,
7464 
7465     /// An initializer.
7466     UPPC_Initializer,
7467 
7468     /// A default argument.
7469     UPPC_DefaultArgument,
7470 
7471     /// The type of a non-type template parameter.
7472     UPPC_NonTypeTemplateParameterType,
7473 
7474     /// The type of an exception.
7475     UPPC_ExceptionType,
7476 
7477     /// Partial specialization.
7478     UPPC_PartialSpecialization,
7479 
7480     /// Microsoft __if_exists.
7481     UPPC_IfExists,
7482 
7483     /// Microsoft __if_not_exists.
7484     UPPC_IfNotExists,
7485 
7486     /// Lambda expression.
7487     UPPC_Lambda,
7488 
7489     /// Block expression,
7490     UPPC_Block,
7491 
7492     /// A type constraint,
7493     UPPC_TypeConstraint
7494   };
7495 
7496   /// Diagnose unexpanded parameter packs.
7497   ///
7498   /// \param Loc The location at which we should emit the diagnostic.
7499   ///
7500   /// \param UPPC The context in which we are diagnosing unexpanded
7501   /// parameter packs.
7502   ///
7503   /// \param Unexpanded the set of unexpanded parameter packs.
7504   ///
7505   /// \returns true if an error occurred, false otherwise.
7506   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7507                                         UnexpandedParameterPackContext UPPC,
7508                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
7509 
7510   /// If the given type contains an unexpanded parameter pack,
7511   /// diagnose the error.
7512   ///
7513   /// \param Loc The source location where a diagnostc should be emitted.
7514   ///
7515   /// \param T The type that is being checked for unexpanded parameter
7516   /// packs.
7517   ///
7518   /// \returns true if an error occurred, false otherwise.
7519   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7520                                        UnexpandedParameterPackContext UPPC);
7521 
7522   /// If the given expression contains an unexpanded parameter
7523   /// pack, diagnose the error.
7524   ///
7525   /// \param E The expression that is being checked for unexpanded
7526   /// parameter packs.
7527   ///
7528   /// \returns true if an error occurred, false otherwise.
7529   bool DiagnoseUnexpandedParameterPack(Expr *E,
7530                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
7531 
7532   /// If the given nested-name-specifier contains an unexpanded
7533   /// parameter pack, diagnose the error.
7534   ///
7535   /// \param SS The nested-name-specifier that is being checked for
7536   /// unexpanded parameter packs.
7537   ///
7538   /// \returns true if an error occurred, false otherwise.
7539   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7540                                        UnexpandedParameterPackContext UPPC);
7541 
7542   /// If the given name contains an unexpanded parameter pack,
7543   /// diagnose the error.
7544   ///
7545   /// \param NameInfo The name (with source location information) that
7546   /// is being checked for unexpanded parameter packs.
7547   ///
7548   /// \returns true if an error occurred, false otherwise.
7549   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7550                                        UnexpandedParameterPackContext UPPC);
7551 
7552   /// If the given template name contains an unexpanded parameter pack,
7553   /// diagnose the error.
7554   ///
7555   /// \param Loc The location of the template name.
7556   ///
7557   /// \param Template The template name that is being checked for unexpanded
7558   /// parameter packs.
7559   ///
7560   /// \returns true if an error occurred, false otherwise.
7561   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7562                                        TemplateName Template,
7563                                        UnexpandedParameterPackContext UPPC);
7564 
7565   /// If the given template argument contains an unexpanded parameter
7566   /// pack, diagnose the error.
7567   ///
7568   /// \param Arg The template argument that is being checked for unexpanded
7569   /// parameter packs.
7570   ///
7571   /// \returns true if an error occurred, false otherwise.
7572   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7573                                        UnexpandedParameterPackContext UPPC);
7574 
7575   /// Collect the set of unexpanded parameter packs within the given
7576   /// template argument.
7577   ///
7578   /// \param Arg The template argument that will be traversed to find
7579   /// unexpanded parameter packs.
7580   void collectUnexpandedParameterPacks(TemplateArgument Arg,
7581                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7582 
7583   /// Collect the set of unexpanded parameter packs within the given
7584   /// template argument.
7585   ///
7586   /// \param Arg The template argument that will be traversed to find
7587   /// unexpanded parameter packs.
7588   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7589                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7590 
7591   /// Collect the set of unexpanded parameter packs within the given
7592   /// type.
7593   ///
7594   /// \param T The type that will be traversed to find
7595   /// unexpanded parameter packs.
7596   void collectUnexpandedParameterPacks(QualType T,
7597                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7598 
7599   /// Collect the set of unexpanded parameter packs within the given
7600   /// type.
7601   ///
7602   /// \param TL The type that will be traversed to find
7603   /// unexpanded parameter packs.
7604   void collectUnexpandedParameterPacks(TypeLoc TL,
7605                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7606 
7607   /// Collect the set of unexpanded parameter packs within the given
7608   /// nested-name-specifier.
7609   ///
7610   /// \param NNS The nested-name-specifier that will be traversed to find
7611   /// unexpanded parameter packs.
7612   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7613                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7614 
7615   /// Collect the set of unexpanded parameter packs within the given
7616   /// name.
7617   ///
7618   /// \param NameInfo The name that will be traversed to find
7619   /// unexpanded parameter packs.
7620   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7621                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7622 
7623   /// Invoked when parsing a template argument followed by an
7624   /// ellipsis, which creates a pack expansion.
7625   ///
7626   /// \param Arg The template argument preceding the ellipsis, which
7627   /// may already be invalid.
7628   ///
7629   /// \param EllipsisLoc The location of the ellipsis.
7630   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7631                                             SourceLocation EllipsisLoc);
7632 
7633   /// Invoked when parsing a type followed by an ellipsis, which
7634   /// creates a pack expansion.
7635   ///
7636   /// \param Type The type preceding the ellipsis, which will become
7637   /// the pattern of the pack expansion.
7638   ///
7639   /// \param EllipsisLoc The location of the ellipsis.
7640   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7641 
7642   /// Construct a pack expansion type from the pattern of the pack
7643   /// expansion.
7644   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7645                                      SourceLocation EllipsisLoc,
7646                                      Optional<unsigned> NumExpansions);
7647 
7648   /// Construct a pack expansion type from the pattern of the pack
7649   /// expansion.
7650   QualType CheckPackExpansion(QualType Pattern,
7651                               SourceRange PatternRange,
7652                               SourceLocation EllipsisLoc,
7653                               Optional<unsigned> NumExpansions);
7654 
7655   /// Invoked when parsing an expression followed by an ellipsis, which
7656   /// creates a pack expansion.
7657   ///
7658   /// \param Pattern The expression preceding the ellipsis, which will become
7659   /// the pattern of the pack expansion.
7660   ///
7661   /// \param EllipsisLoc The location of the ellipsis.
7662   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7663 
7664   /// Invoked when parsing an expression followed by an ellipsis, which
7665   /// creates a pack expansion.
7666   ///
7667   /// \param Pattern The expression preceding the ellipsis, which will become
7668   /// the pattern of the pack expansion.
7669   ///
7670   /// \param EllipsisLoc The location of the ellipsis.
7671   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7672                                 Optional<unsigned> NumExpansions);
7673 
7674   /// Determine whether we could expand a pack expansion with the
7675   /// given set of parameter packs into separate arguments by repeatedly
7676   /// transforming the pattern.
7677   ///
7678   /// \param EllipsisLoc The location of the ellipsis that identifies the
7679   /// pack expansion.
7680   ///
7681   /// \param PatternRange The source range that covers the entire pattern of
7682   /// the pack expansion.
7683   ///
7684   /// \param Unexpanded The set of unexpanded parameter packs within the
7685   /// pattern.
7686   ///
7687   /// \param ShouldExpand Will be set to \c true if the transformer should
7688   /// expand the corresponding pack expansions into separate arguments. When
7689   /// set, \c NumExpansions must also be set.
7690   ///
7691   /// \param RetainExpansion Whether the caller should add an unexpanded
7692   /// pack expansion after all of the expanded arguments. This is used
7693   /// when extending explicitly-specified template argument packs per
7694   /// C++0x [temp.arg.explicit]p9.
7695   ///
7696   /// \param NumExpansions The number of separate arguments that will be in
7697   /// the expanded form of the corresponding pack expansion. This is both an
7698   /// input and an output parameter, which can be set by the caller if the
7699   /// number of expansions is known a priori (e.g., due to a prior substitution)
7700   /// and will be set by the callee when the number of expansions is known.
7701   /// The callee must set this value when \c ShouldExpand is \c true; it may
7702   /// set this value in other cases.
7703   ///
7704   /// \returns true if an error occurred (e.g., because the parameter packs
7705   /// are to be instantiated with arguments of different lengths), false
7706   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7707   /// must be set.
7708   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7709                                        SourceRange PatternRange,
7710                              ArrayRef<UnexpandedParameterPack> Unexpanded,
7711                              const MultiLevelTemplateArgumentList &TemplateArgs,
7712                                        bool &ShouldExpand,
7713                                        bool &RetainExpansion,
7714                                        Optional<unsigned> &NumExpansions);
7715 
7716   /// Determine the number of arguments in the given pack expansion
7717   /// type.
7718   ///
7719   /// This routine assumes that the number of arguments in the expansion is
7720   /// consistent across all of the unexpanded parameter packs in its pattern.
7721   ///
7722   /// Returns an empty Optional if the type can't be expanded.
7723   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7724       const MultiLevelTemplateArgumentList &TemplateArgs);
7725 
7726   /// Determine whether the given declarator contains any unexpanded
7727   /// parameter packs.
7728   ///
7729   /// This routine is used by the parser to disambiguate function declarators
7730   /// with an ellipsis prior to the ')', e.g.,
7731   ///
7732   /// \code
7733   ///   void f(T...);
7734   /// \endcode
7735   ///
7736   /// To determine whether we have an (unnamed) function parameter pack or
7737   /// a variadic function.
7738   ///
7739   /// \returns true if the declarator contains any unexpanded parameter packs,
7740   /// false otherwise.
7741   bool containsUnexpandedParameterPacks(Declarator &D);
7742 
7743   /// Returns the pattern of the pack expansion for a template argument.
7744   ///
7745   /// \param OrigLoc The template argument to expand.
7746   ///
7747   /// \param Ellipsis Will be set to the location of the ellipsis.
7748   ///
7749   /// \param NumExpansions Will be set to the number of expansions that will
7750   /// be generated from this pack expansion, if known a priori.
7751   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
7752       TemplateArgumentLoc OrigLoc,
7753       SourceLocation &Ellipsis,
7754       Optional<unsigned> &NumExpansions) const;
7755 
7756   /// Given a template argument that contains an unexpanded parameter pack, but
7757   /// which has already been substituted, attempt to determine the number of
7758   /// elements that will be produced once this argument is fully-expanded.
7759   ///
7760   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
7761   /// avoid actually expanding the pack where possible.
7762   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
7763 
7764   //===--------------------------------------------------------------------===//
7765   // C++ Template Argument Deduction (C++ [temp.deduct])
7766   //===--------------------------------------------------------------------===//
7767 
7768   /// Adjust the type \p ArgFunctionType to match the calling convention,
7769   /// noreturn, and optionally the exception specification of \p FunctionType.
7770   /// Deduction often wants to ignore these properties when matching function
7771   /// types.
7772   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
7773                                bool AdjustExceptionSpec = false);
7774 
7775   /// Describes the result of template argument deduction.
7776   ///
7777   /// The TemplateDeductionResult enumeration describes the result of
7778   /// template argument deduction, as returned from
7779   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
7780   /// structure provides additional information about the results of
7781   /// template argument deduction, e.g., the deduced template argument
7782   /// list (if successful) or the specific template parameters or
7783   /// deduced arguments that were involved in the failure.
7784   enum TemplateDeductionResult {
7785     /// Template argument deduction was successful.
7786     TDK_Success = 0,
7787     /// The declaration was invalid; do nothing.
7788     TDK_Invalid,
7789     /// Template argument deduction exceeded the maximum template
7790     /// instantiation depth (which has already been diagnosed).
7791     TDK_InstantiationDepth,
7792     /// Template argument deduction did not deduce a value
7793     /// for every template parameter.
7794     TDK_Incomplete,
7795     /// Template argument deduction did not deduce a value for every
7796     /// expansion of an expanded template parameter pack.
7797     TDK_IncompletePack,
7798     /// Template argument deduction produced inconsistent
7799     /// deduced values for the given template parameter.
7800     TDK_Inconsistent,
7801     /// Template argument deduction failed due to inconsistent
7802     /// cv-qualifiers on a template parameter type that would
7803     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
7804     /// but were given a non-const "X".
7805     TDK_Underqualified,
7806     /// Substitution of the deduced template argument values
7807     /// resulted in an error.
7808     TDK_SubstitutionFailure,
7809     /// After substituting deduced template arguments, a dependent
7810     /// parameter type did not match the corresponding argument.
7811     TDK_DeducedMismatch,
7812     /// After substituting deduced template arguments, an element of
7813     /// a dependent parameter type did not match the corresponding element
7814     /// of the corresponding argument (when deducing from an initializer list).
7815     TDK_DeducedMismatchNested,
7816     /// A non-depnedent component of the parameter did not match the
7817     /// corresponding component of the argument.
7818     TDK_NonDeducedMismatch,
7819     /// When performing template argument deduction for a function
7820     /// template, there were too many call arguments.
7821     TDK_TooManyArguments,
7822     /// When performing template argument deduction for a function
7823     /// template, there were too few call arguments.
7824     TDK_TooFewArguments,
7825     /// The explicitly-specified template arguments were not valid
7826     /// template arguments for the given template.
7827     TDK_InvalidExplicitArguments,
7828     /// Checking non-dependent argument conversions failed.
7829     TDK_NonDependentConversionFailure,
7830     /// The deduced arguments did not satisfy the constraints associated
7831     /// with the template.
7832     TDK_ConstraintsNotSatisfied,
7833     /// Deduction failed; that's all we know.
7834     TDK_MiscellaneousDeductionFailure,
7835     /// CUDA Target attributes do not match.
7836     TDK_CUDATargetMismatch
7837   };
7838 
7839   TemplateDeductionResult
7840   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
7841                           const TemplateArgumentList &TemplateArgs,
7842                           sema::TemplateDeductionInfo &Info);
7843 
7844   TemplateDeductionResult
7845   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
7846                           const TemplateArgumentList &TemplateArgs,
7847                           sema::TemplateDeductionInfo &Info);
7848 
7849   TemplateDeductionResult SubstituteExplicitTemplateArguments(
7850       FunctionTemplateDecl *FunctionTemplate,
7851       TemplateArgumentListInfo &ExplicitTemplateArgs,
7852       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7853       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
7854       sema::TemplateDeductionInfo &Info);
7855 
7856   /// brief A function argument from which we performed template argument
7857   // deduction for a call.
7858   struct OriginalCallArg {
7859     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
7860                     unsigned ArgIdx, QualType OriginalArgType)
7861         : OriginalParamType(OriginalParamType),
7862           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
7863           OriginalArgType(OriginalArgType) {}
7864 
7865     QualType OriginalParamType;
7866     bool DecomposedParam;
7867     unsigned ArgIdx;
7868     QualType OriginalArgType;
7869   };
7870 
7871   TemplateDeductionResult FinishTemplateArgumentDeduction(
7872       FunctionTemplateDecl *FunctionTemplate,
7873       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7874       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
7875       sema::TemplateDeductionInfo &Info,
7876       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
7877       bool PartialOverloading = false,
7878       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
7879 
7880   TemplateDeductionResult DeduceTemplateArguments(
7881       FunctionTemplateDecl *FunctionTemplate,
7882       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7883       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7884       bool PartialOverloading,
7885       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7886 
7887   TemplateDeductionResult
7888   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7889                           TemplateArgumentListInfo *ExplicitTemplateArgs,
7890                           QualType ArgFunctionType,
7891                           FunctionDecl *&Specialization,
7892                           sema::TemplateDeductionInfo &Info,
7893                           bool IsAddressOfFunction = false);
7894 
7895   TemplateDeductionResult
7896   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7897                           QualType ToType,
7898                           CXXConversionDecl *&Specialization,
7899                           sema::TemplateDeductionInfo &Info);
7900 
7901   TemplateDeductionResult
7902   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7903                           TemplateArgumentListInfo *ExplicitTemplateArgs,
7904                           FunctionDecl *&Specialization,
7905                           sema::TemplateDeductionInfo &Info,
7906                           bool IsAddressOfFunction = false);
7907 
7908   /// Substitute Replacement for \p auto in \p TypeWithAuto
7909   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7910   /// Substitute Replacement for auto in TypeWithAuto
7911   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7912                                           QualType Replacement);
7913   /// Completely replace the \c auto in \p TypeWithAuto by
7914   /// \p Replacement. This does not retain any \c auto type sugar.
7915   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7916 
7917   /// Result type of DeduceAutoType.
7918   enum DeduceAutoResult {
7919     DAR_Succeeded,
7920     DAR_Failed,
7921     DAR_FailedAlreadyDiagnosed
7922   };
7923 
7924   DeduceAutoResult
7925   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7926                  Optional<unsigned> DependentDeductionDepth = None,
7927                  bool IgnoreConstraints = false);
7928   DeduceAutoResult
7929   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7930                  Optional<unsigned> DependentDeductionDepth = None,
7931                  bool IgnoreConstraints = false);
7932   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7933   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7934                         bool Diagnose = true);
7935 
7936   /// Declare implicit deduction guides for a class template if we've
7937   /// not already done so.
7938   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7939                                       SourceLocation Loc);
7940 
7941   QualType DeduceTemplateSpecializationFromInitializer(
7942       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7943       const InitializationKind &Kind, MultiExprArg Init);
7944 
7945   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7946                                         QualType Type, TypeSourceInfo *TSI,
7947                                         SourceRange Range, bool DirectInit,
7948                                         Expr *Init);
7949 
7950   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7951 
7952   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7953                                         SourceLocation ReturnLoc,
7954                                         Expr *&RetExpr, AutoType *AT);
7955 
7956   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7957                                                    FunctionTemplateDecl *FT2,
7958                                                    SourceLocation Loc,
7959                                            TemplatePartialOrderingContext TPOC,
7960                                                    unsigned NumCallArguments1,
7961                                                    unsigned NumCallArguments2);
7962   UnresolvedSetIterator
7963   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7964                      TemplateSpecCandidateSet &FailedCandidates,
7965                      SourceLocation Loc,
7966                      const PartialDiagnostic &NoneDiag,
7967                      const PartialDiagnostic &AmbigDiag,
7968                      const PartialDiagnostic &CandidateDiag,
7969                      bool Complain = true, QualType TargetType = QualType());
7970 
7971   ClassTemplatePartialSpecializationDecl *
7972   getMoreSpecializedPartialSpecialization(
7973                                   ClassTemplatePartialSpecializationDecl *PS1,
7974                                   ClassTemplatePartialSpecializationDecl *PS2,
7975                                   SourceLocation Loc);
7976 
7977   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7978                                     sema::TemplateDeductionInfo &Info);
7979 
7980   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7981       VarTemplatePartialSpecializationDecl *PS1,
7982       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7983 
7984   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7985                                     sema::TemplateDeductionInfo &Info);
7986 
7987   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7988       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
7989 
7990   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7991                                   unsigned Depth, llvm::SmallBitVector &Used);
7992 
7993   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7994                                   bool OnlyDeduced,
7995                                   unsigned Depth,
7996                                   llvm::SmallBitVector &Used);
7997   void MarkDeducedTemplateParameters(
7998                                   const FunctionTemplateDecl *FunctionTemplate,
7999                                   llvm::SmallBitVector &Deduced) {
8000     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8001   }
8002   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8003                                   const FunctionTemplateDecl *FunctionTemplate,
8004                                   llvm::SmallBitVector &Deduced);
8005 
8006   //===--------------------------------------------------------------------===//
8007   // C++ Template Instantiation
8008   //
8009 
8010   MultiLevelTemplateArgumentList
8011   getTemplateInstantiationArgs(NamedDecl *D,
8012                                const TemplateArgumentList *Innermost = nullptr,
8013                                bool RelativeToPrimary = false,
8014                                const FunctionDecl *Pattern = nullptr);
8015 
8016   /// A context in which code is being synthesized (where a source location
8017   /// alone is not sufficient to identify the context). This covers template
8018   /// instantiation and various forms of implicitly-generated functions.
8019   struct CodeSynthesisContext {
8020     /// The kind of template instantiation we are performing
8021     enum SynthesisKind {
8022       /// We are instantiating a template declaration. The entity is
8023       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8024       TemplateInstantiation,
8025 
8026       /// We are instantiating a default argument for a template
8027       /// parameter. The Entity is the template parameter whose argument is
8028       /// being instantiated, the Template is the template, and the
8029       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8030       /// specified.
8031       DefaultTemplateArgumentInstantiation,
8032 
8033       /// We are instantiating a default argument for a function.
8034       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8035       /// provides the template arguments as specified.
8036       DefaultFunctionArgumentInstantiation,
8037 
8038       /// We are substituting explicit template arguments provided for
8039       /// a function template. The entity is a FunctionTemplateDecl.
8040       ExplicitTemplateArgumentSubstitution,
8041 
8042       /// We are substituting template argument determined as part of
8043       /// template argument deduction for either a class template
8044       /// partial specialization or a function template. The
8045       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8046       /// a TemplateDecl.
8047       DeducedTemplateArgumentSubstitution,
8048 
8049       /// We are substituting prior template arguments into a new
8050       /// template parameter. The template parameter itself is either a
8051       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8052       PriorTemplateArgumentSubstitution,
8053 
8054       /// We are checking the validity of a default template argument that
8055       /// has been used when naming a template-id.
8056       DefaultTemplateArgumentChecking,
8057 
8058       /// We are computing the exception specification for a defaulted special
8059       /// member function.
8060       ExceptionSpecEvaluation,
8061 
8062       /// We are instantiating the exception specification for a function
8063       /// template which was deferred until it was needed.
8064       ExceptionSpecInstantiation,
8065 
8066       /// We are instantiating a requirement of a requires expression.
8067       RequirementInstantiation,
8068 
8069       /// We are checking the satisfaction of a nested requirement of a requires
8070       /// expression.
8071       NestedRequirementConstraintsCheck,
8072 
8073       /// We are declaring an implicit special member function.
8074       DeclaringSpecialMember,
8075 
8076       /// We are declaring an implicit 'operator==' for a defaulted
8077       /// 'operator<=>'.
8078       DeclaringImplicitEqualityComparison,
8079 
8080       /// We are defining a synthesized function (such as a defaulted special
8081       /// member).
8082       DefiningSynthesizedFunction,
8083 
8084       // We are checking the constraints associated with a constrained entity or
8085       // the constraint expression of a concept. This includes the checks that
8086       // atomic constraints have the type 'bool' and that they can be constant
8087       // evaluated.
8088       ConstraintsCheck,
8089 
8090       // We are substituting template arguments into a constraint expression.
8091       ConstraintSubstitution,
8092 
8093       // We are normalizing a constraint expression.
8094       ConstraintNormalization,
8095 
8096       // We are substituting into the parameter mapping of an atomic constraint
8097       // during normalization.
8098       ParameterMappingSubstitution,
8099 
8100       /// We are rewriting a comparison operator in terms of an operator<=>.
8101       RewritingOperatorAsSpaceship,
8102 
8103       /// Added for Template instantiation observation.
8104       /// Memoization means we are _not_ instantiating a template because
8105       /// it is already instantiated (but we entered a context where we
8106       /// would have had to if it was not already instantiated).
8107       Memoization
8108     } Kind;
8109 
8110     /// Was the enclosing context a non-instantiation SFINAE context?
8111     bool SavedInNonInstantiationSFINAEContext;
8112 
8113     /// The point of instantiation or synthesis within the source code.
8114     SourceLocation PointOfInstantiation;
8115 
8116     /// The entity that is being synthesized.
8117     Decl *Entity;
8118 
8119     /// The template (or partial specialization) in which we are
8120     /// performing the instantiation, for substitutions of prior template
8121     /// arguments.
8122     NamedDecl *Template;
8123 
8124     /// The list of template arguments we are substituting, if they
8125     /// are not part of the entity.
8126     const TemplateArgument *TemplateArgs;
8127 
8128     // FIXME: Wrap this union around more members, or perhaps store the
8129     // kind-specific members in the RAII object owning the context.
8130     union {
8131       /// The number of template arguments in TemplateArgs.
8132       unsigned NumTemplateArgs;
8133 
8134       /// The special member being declared or defined.
8135       CXXSpecialMember SpecialMember;
8136     };
8137 
8138     ArrayRef<TemplateArgument> template_arguments() const {
8139       assert(Kind != DeclaringSpecialMember);
8140       return {TemplateArgs, NumTemplateArgs};
8141     }
8142 
8143     /// The template deduction info object associated with the
8144     /// substitution or checking of explicit or deduced template arguments.
8145     sema::TemplateDeductionInfo *DeductionInfo;
8146 
8147     /// The source range that covers the construct that cause
8148     /// the instantiation, e.g., the template-id that causes a class
8149     /// template instantiation.
8150     SourceRange InstantiationRange;
8151 
8152     CodeSynthesisContext()
8153         : Kind(TemplateInstantiation),
8154           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8155           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8156           DeductionInfo(nullptr) {}
8157 
8158     /// Determines whether this template is an actual instantiation
8159     /// that should be counted toward the maximum instantiation depth.
8160     bool isInstantiationRecord() const;
8161   };
8162 
8163   /// List of active code synthesis contexts.
8164   ///
8165   /// This vector is treated as a stack. As synthesis of one entity requires
8166   /// synthesis of another, additional contexts are pushed onto the stack.
8167   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8168 
8169   /// Specializations whose definitions are currently being instantiated.
8170   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8171 
8172   /// Non-dependent types used in templates that have already been instantiated
8173   /// by some template instantiation.
8174   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8175 
8176   /// Extra modules inspected when performing a lookup during a template
8177   /// instantiation. Computed lazily.
8178   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8179 
8180   /// Cache of additional modules that should be used for name lookup
8181   /// within the current template instantiation. Computed lazily; use
8182   /// getLookupModules() to get a complete set.
8183   llvm::DenseSet<Module*> LookupModulesCache;
8184 
8185   /// Get the set of additional modules that should be checked during
8186   /// name lookup. A module and its imports become visible when instanting a
8187   /// template defined within it.
8188   llvm::DenseSet<Module*> &getLookupModules();
8189 
8190   /// Map from the most recent declaration of a namespace to the most
8191   /// recent visible declaration of that namespace.
8192   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8193 
8194   /// Whether we are in a SFINAE context that is not associated with
8195   /// template instantiation.
8196   ///
8197   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8198   /// of a template instantiation or template argument deduction.
8199   bool InNonInstantiationSFINAEContext;
8200 
8201   /// The number of \p CodeSynthesisContexts that are not template
8202   /// instantiations and, therefore, should not be counted as part of the
8203   /// instantiation depth.
8204   ///
8205   /// When the instantiation depth reaches the user-configurable limit
8206   /// \p LangOptions::InstantiationDepth we will abort instantiation.
8207   // FIXME: Should we have a similar limit for other forms of synthesis?
8208   unsigned NonInstantiationEntries;
8209 
8210   /// The depth of the context stack at the point when the most recent
8211   /// error or warning was produced.
8212   ///
8213   /// This value is used to suppress printing of redundant context stacks
8214   /// when there are multiple errors or warnings in the same instantiation.
8215   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8216   unsigned LastEmittedCodeSynthesisContextDepth = 0;
8217 
8218   /// The template instantiation callbacks to trace or track
8219   /// instantiations (objects can be chained).
8220   ///
8221   /// This callbacks is used to print, trace or track template
8222   /// instantiations as they are being constructed.
8223   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8224       TemplateInstCallbacks;
8225 
8226   /// The current index into pack expansion arguments that will be
8227   /// used for substitution of parameter packs.
8228   ///
8229   /// The pack expansion index will be -1 to indicate that parameter packs
8230   /// should be instantiated as themselves. Otherwise, the index specifies
8231   /// which argument within the parameter pack will be used for substitution.
8232   int ArgumentPackSubstitutionIndex;
8233 
8234   /// RAII object used to change the argument pack substitution index
8235   /// within a \c Sema object.
8236   ///
8237   /// See \c ArgumentPackSubstitutionIndex for more information.
8238   class ArgumentPackSubstitutionIndexRAII {
8239     Sema &Self;
8240     int OldSubstitutionIndex;
8241 
8242   public:
8243     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8244       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8245       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8246     }
8247 
8248     ~ArgumentPackSubstitutionIndexRAII() {
8249       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8250     }
8251   };
8252 
8253   friend class ArgumentPackSubstitutionRAII;
8254 
8255   /// For each declaration that involved template argument deduction, the
8256   /// set of diagnostics that were suppressed during that template argument
8257   /// deduction.
8258   ///
8259   /// FIXME: Serialize this structure to the AST file.
8260   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8261     SuppressedDiagnosticsMap;
8262   SuppressedDiagnosticsMap SuppressedDiagnostics;
8263 
8264   /// A stack object to be created when performing template
8265   /// instantiation.
8266   ///
8267   /// Construction of an object of type \c InstantiatingTemplate
8268   /// pushes the current instantiation onto the stack of active
8269   /// instantiations. If the size of this stack exceeds the maximum
8270   /// number of recursive template instantiations, construction
8271   /// produces an error and evaluates true.
8272   ///
8273   /// Destruction of this object will pop the named instantiation off
8274   /// the stack.
8275   struct InstantiatingTemplate {
8276     /// Note that we are instantiating a class template,
8277     /// function template, variable template, alias template,
8278     /// or a member thereof.
8279     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8280                           Decl *Entity,
8281                           SourceRange InstantiationRange = SourceRange());
8282 
8283     struct ExceptionSpecification {};
8284     /// Note that we are instantiating an exception specification
8285     /// of a function template.
8286     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8287                           FunctionDecl *Entity, ExceptionSpecification,
8288                           SourceRange InstantiationRange = SourceRange());
8289 
8290     /// Note that we are instantiating a default argument in a
8291     /// template-id.
8292     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8293                           TemplateParameter Param, TemplateDecl *Template,
8294                           ArrayRef<TemplateArgument> TemplateArgs,
8295                           SourceRange InstantiationRange = SourceRange());
8296 
8297     /// Note that we are substituting either explicitly-specified or
8298     /// deduced template arguments during function template argument deduction.
8299     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8300                           FunctionTemplateDecl *FunctionTemplate,
8301                           ArrayRef<TemplateArgument> TemplateArgs,
8302                           CodeSynthesisContext::SynthesisKind Kind,
8303                           sema::TemplateDeductionInfo &DeductionInfo,
8304                           SourceRange InstantiationRange = SourceRange());
8305 
8306     /// Note that we are instantiating as part of template
8307     /// argument deduction for a class template declaration.
8308     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8309                           TemplateDecl *Template,
8310                           ArrayRef<TemplateArgument> TemplateArgs,
8311                           sema::TemplateDeductionInfo &DeductionInfo,
8312                           SourceRange InstantiationRange = SourceRange());
8313 
8314     /// Note that we are instantiating as part of template
8315     /// argument deduction for a class template partial
8316     /// specialization.
8317     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8318                           ClassTemplatePartialSpecializationDecl *PartialSpec,
8319                           ArrayRef<TemplateArgument> TemplateArgs,
8320                           sema::TemplateDeductionInfo &DeductionInfo,
8321                           SourceRange InstantiationRange = SourceRange());
8322 
8323     /// Note that we are instantiating as part of template
8324     /// argument deduction for a variable template partial
8325     /// specialization.
8326     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8327                           VarTemplatePartialSpecializationDecl *PartialSpec,
8328                           ArrayRef<TemplateArgument> TemplateArgs,
8329                           sema::TemplateDeductionInfo &DeductionInfo,
8330                           SourceRange InstantiationRange = SourceRange());
8331 
8332     /// Note that we are instantiating a default argument for a function
8333     /// parameter.
8334     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8335                           ParmVarDecl *Param,
8336                           ArrayRef<TemplateArgument> TemplateArgs,
8337                           SourceRange InstantiationRange = SourceRange());
8338 
8339     /// Note that we are substituting prior template arguments into a
8340     /// non-type parameter.
8341     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8342                           NamedDecl *Template,
8343                           NonTypeTemplateParmDecl *Param,
8344                           ArrayRef<TemplateArgument> TemplateArgs,
8345                           SourceRange InstantiationRange);
8346 
8347     /// Note that we are substituting prior template arguments into a
8348     /// template template parameter.
8349     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8350                           NamedDecl *Template,
8351                           TemplateTemplateParmDecl *Param,
8352                           ArrayRef<TemplateArgument> TemplateArgs,
8353                           SourceRange InstantiationRange);
8354 
8355     /// Note that we are checking the default template argument
8356     /// against the template parameter for a given template-id.
8357     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8358                           TemplateDecl *Template,
8359                           NamedDecl *Param,
8360                           ArrayRef<TemplateArgument> TemplateArgs,
8361                           SourceRange InstantiationRange);
8362 
8363     struct ConstraintsCheck {};
8364     /// \brief Note that we are checking the constraints associated with some
8365     /// constrained entity (a concept declaration or a template with associated
8366     /// constraints).
8367     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8368                           ConstraintsCheck, NamedDecl *Template,
8369                           ArrayRef<TemplateArgument> TemplateArgs,
8370                           SourceRange InstantiationRange);
8371 
8372     struct ConstraintSubstitution {};
8373     /// \brief Note that we are checking a constraint expression associated
8374     /// with a template declaration or as part of the satisfaction check of a
8375     /// concept.
8376     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8377                           ConstraintSubstitution, NamedDecl *Template,
8378                           sema::TemplateDeductionInfo &DeductionInfo,
8379                           SourceRange InstantiationRange);
8380 
8381     struct ConstraintNormalization {};
8382     /// \brief Note that we are normalizing a constraint expression.
8383     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8384                           ConstraintNormalization, NamedDecl *Template,
8385                           SourceRange InstantiationRange);
8386 
8387     struct ParameterMappingSubstitution {};
8388     /// \brief Note that we are subtituting into the parameter mapping of an
8389     /// atomic constraint during constraint normalization.
8390     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8391                           ParameterMappingSubstitution, NamedDecl *Template,
8392                           SourceRange InstantiationRange);
8393 
8394     /// \brief Note that we are substituting template arguments into a part of
8395     /// a requirement of a requires expression.
8396     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8397                           concepts::Requirement *Req,
8398                           sema::TemplateDeductionInfo &DeductionInfo,
8399                           SourceRange InstantiationRange = SourceRange());
8400 
8401     /// \brief Note that we are checking the satisfaction of the constraint
8402     /// expression inside of a nested requirement.
8403     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8404                           concepts::NestedRequirement *Req, ConstraintsCheck,
8405                           SourceRange InstantiationRange = SourceRange());
8406 
8407     /// Note that we have finished instantiating this template.
8408     void Clear();
8409 
8410     ~InstantiatingTemplate() { Clear(); }
8411 
8412     /// Determines whether we have exceeded the maximum
8413     /// recursive template instantiations.
8414     bool isInvalid() const { return Invalid; }
8415 
8416     /// Determine whether we are already instantiating this
8417     /// specialization in some surrounding active instantiation.
8418     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8419 
8420   private:
8421     Sema &SemaRef;
8422     bool Invalid;
8423     bool AlreadyInstantiating;
8424     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8425                                  SourceRange InstantiationRange);
8426 
8427     InstantiatingTemplate(
8428         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8429         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8430         Decl *Entity, NamedDecl *Template = nullptr,
8431         ArrayRef<TemplateArgument> TemplateArgs = None,
8432         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8433 
8434     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8435 
8436     InstantiatingTemplate&
8437     operator=(const InstantiatingTemplate&) = delete;
8438   };
8439 
8440   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8441   void popCodeSynthesisContext();
8442 
8443   /// Determine whether we are currently performing template instantiation.
8444   bool inTemplateInstantiation() const {
8445     return CodeSynthesisContexts.size() > NonInstantiationEntries;
8446   }
8447 
8448   void PrintContextStack() {
8449     if (!CodeSynthesisContexts.empty() &&
8450         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8451       PrintInstantiationStack();
8452       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8453     }
8454     if (PragmaAttributeCurrentTargetDecl)
8455       PrintPragmaAttributeInstantiationPoint();
8456   }
8457   void PrintInstantiationStack();
8458 
8459   void PrintPragmaAttributeInstantiationPoint();
8460 
8461   /// Determines whether we are currently in a context where
8462   /// template argument substitution failures are not considered
8463   /// errors.
8464   ///
8465   /// \returns An empty \c Optional if we're not in a SFINAE context.
8466   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8467   /// template-deduction context object, which can be used to capture
8468   /// diagnostics that will be suppressed.
8469   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8470 
8471   /// Determines whether we are currently in a context that
8472   /// is not evaluated as per C++ [expr] p5.
8473   bool isUnevaluatedContext() const {
8474     assert(!ExprEvalContexts.empty() &&
8475            "Must be in an expression evaluation context");
8476     return ExprEvalContexts.back().isUnevaluated();
8477   }
8478 
8479   /// RAII class used to determine whether SFINAE has
8480   /// trapped any errors that occur during template argument
8481   /// deduction.
8482   class SFINAETrap {
8483     Sema &SemaRef;
8484     unsigned PrevSFINAEErrors;
8485     bool PrevInNonInstantiationSFINAEContext;
8486     bool PrevAccessCheckingSFINAE;
8487     bool PrevLastDiagnosticIgnored;
8488 
8489   public:
8490     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
8491       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8492         PrevInNonInstantiationSFINAEContext(
8493                                       SemaRef.InNonInstantiationSFINAEContext),
8494         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8495         PrevLastDiagnosticIgnored(
8496             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8497     {
8498       if (!SemaRef.isSFINAEContext())
8499         SemaRef.InNonInstantiationSFINAEContext = true;
8500       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8501     }
8502 
8503     ~SFINAETrap() {
8504       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8505       SemaRef.InNonInstantiationSFINAEContext
8506         = PrevInNonInstantiationSFINAEContext;
8507       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8508       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8509           PrevLastDiagnosticIgnored);
8510     }
8511 
8512     /// Determine whether any SFINAE errors have been trapped.
8513     bool hasErrorOccurred() const {
8514       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8515     }
8516   };
8517 
8518   /// RAII class used to indicate that we are performing provisional
8519   /// semantic analysis to determine the validity of a construct, so
8520   /// typo-correction and diagnostics in the immediate context (not within
8521   /// implicitly-instantiated templates) should be suppressed.
8522   class TentativeAnalysisScope {
8523     Sema &SemaRef;
8524     // FIXME: Using a SFINAETrap for this is a hack.
8525     SFINAETrap Trap;
8526     bool PrevDisableTypoCorrection;
8527   public:
8528     explicit TentativeAnalysisScope(Sema &SemaRef)
8529         : SemaRef(SemaRef), Trap(SemaRef, true),
8530           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8531       SemaRef.DisableTypoCorrection = true;
8532     }
8533     ~TentativeAnalysisScope() {
8534       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8535     }
8536   };
8537 
8538   /// The current instantiation scope used to store local
8539   /// variables.
8540   LocalInstantiationScope *CurrentInstantiationScope;
8541 
8542   /// Tracks whether we are in a context where typo correction is
8543   /// disabled.
8544   bool DisableTypoCorrection;
8545 
8546   /// The number of typos corrected by CorrectTypo.
8547   unsigned TyposCorrected;
8548 
8549   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8550   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8551 
8552   /// A cache containing identifiers for which typo correction failed and
8553   /// their locations, so that repeated attempts to correct an identifier in a
8554   /// given location are ignored if typo correction already failed for it.
8555   IdentifierSourceLocations TypoCorrectionFailures;
8556 
8557   /// Worker object for performing CFG-based warnings.
8558   sema::AnalysisBasedWarnings AnalysisWarnings;
8559   threadSafety::BeforeSet *ThreadSafetyDeclCache;
8560 
8561   /// An entity for which implicit template instantiation is required.
8562   ///
8563   /// The source location associated with the declaration is the first place in
8564   /// the source code where the declaration was "used". It is not necessarily
8565   /// the point of instantiation (which will be either before or after the
8566   /// namespace-scope declaration that triggered this implicit instantiation),
8567   /// However, it is the location that diagnostics should generally refer to,
8568   /// because users will need to know what code triggered the instantiation.
8569   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8570 
8571   /// The queue of implicit template instantiations that are required
8572   /// but have not yet been performed.
8573   std::deque<PendingImplicitInstantiation> PendingInstantiations;
8574 
8575   /// Queue of implicit template instantiations that cannot be performed
8576   /// eagerly.
8577   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8578 
8579   class GlobalEagerInstantiationScope {
8580   public:
8581     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8582         : S(S), Enabled(Enabled) {
8583       if (!Enabled) return;
8584 
8585       SavedPendingInstantiations.swap(S.PendingInstantiations);
8586       SavedVTableUses.swap(S.VTableUses);
8587     }
8588 
8589     void perform() {
8590       if (Enabled) {
8591         S.DefineUsedVTables();
8592         S.PerformPendingInstantiations();
8593       }
8594     }
8595 
8596     ~GlobalEagerInstantiationScope() {
8597       if (!Enabled) return;
8598 
8599       // Restore the set of pending vtables.
8600       assert(S.VTableUses.empty() &&
8601              "VTableUses should be empty before it is discarded.");
8602       S.VTableUses.swap(SavedVTableUses);
8603 
8604       // Restore the set of pending implicit instantiations.
8605       assert(S.PendingInstantiations.empty() &&
8606              "PendingInstantiations should be empty before it is discarded.");
8607       S.PendingInstantiations.swap(SavedPendingInstantiations);
8608     }
8609 
8610   private:
8611     Sema &S;
8612     SmallVector<VTableUse, 16> SavedVTableUses;
8613     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8614     bool Enabled;
8615   };
8616 
8617   /// The queue of implicit template instantiations that are required
8618   /// and must be performed within the current local scope.
8619   ///
8620   /// This queue is only used for member functions of local classes in
8621   /// templates, which must be instantiated in the same scope as their
8622   /// enclosing function, so that they can reference function-local
8623   /// types, static variables, enumerators, etc.
8624   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8625 
8626   class LocalEagerInstantiationScope {
8627   public:
8628     LocalEagerInstantiationScope(Sema &S) : S(S) {
8629       SavedPendingLocalImplicitInstantiations.swap(
8630           S.PendingLocalImplicitInstantiations);
8631     }
8632 
8633     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8634 
8635     ~LocalEagerInstantiationScope() {
8636       assert(S.PendingLocalImplicitInstantiations.empty() &&
8637              "there shouldn't be any pending local implicit instantiations");
8638       SavedPendingLocalImplicitInstantiations.swap(
8639           S.PendingLocalImplicitInstantiations);
8640     }
8641 
8642   private:
8643     Sema &S;
8644     std::deque<PendingImplicitInstantiation>
8645         SavedPendingLocalImplicitInstantiations;
8646   };
8647 
8648   /// A helper class for building up ExtParameterInfos.
8649   class ExtParameterInfoBuilder {
8650     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8651     bool HasInteresting = false;
8652 
8653   public:
8654     /// Set the ExtParameterInfo for the parameter at the given index,
8655     ///
8656     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8657       assert(Infos.size() <= index);
8658       Infos.resize(index);
8659       Infos.push_back(info);
8660 
8661       if (!HasInteresting)
8662         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8663     }
8664 
8665     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8666     /// ExtParameterInfo array we've built up.
8667     const FunctionProtoType::ExtParameterInfo *
8668     getPointerOrNull(unsigned numParams) {
8669       if (!HasInteresting) return nullptr;
8670       Infos.resize(numParams);
8671       return Infos.data();
8672     }
8673   };
8674 
8675   void PerformPendingInstantiations(bool LocalOnly = false);
8676 
8677   TypeSourceInfo *SubstType(TypeSourceInfo *T,
8678                             const MultiLevelTemplateArgumentList &TemplateArgs,
8679                             SourceLocation Loc, DeclarationName Entity,
8680                             bool AllowDeducedTST = false);
8681 
8682   QualType SubstType(QualType T,
8683                      const MultiLevelTemplateArgumentList &TemplateArgs,
8684                      SourceLocation Loc, DeclarationName Entity);
8685 
8686   TypeSourceInfo *SubstType(TypeLoc TL,
8687                             const MultiLevelTemplateArgumentList &TemplateArgs,
8688                             SourceLocation Loc, DeclarationName Entity);
8689 
8690   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8691                             const MultiLevelTemplateArgumentList &TemplateArgs,
8692                                         SourceLocation Loc,
8693                                         DeclarationName Entity,
8694                                         CXXRecordDecl *ThisContext,
8695                                         Qualifiers ThisTypeQuals);
8696   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8697                           const MultiLevelTemplateArgumentList &Args);
8698   bool SubstExceptionSpec(SourceLocation Loc,
8699                           FunctionProtoType::ExceptionSpecInfo &ESI,
8700                           SmallVectorImpl<QualType> &ExceptionStorage,
8701                           const MultiLevelTemplateArgumentList &Args);
8702   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8703                             const MultiLevelTemplateArgumentList &TemplateArgs,
8704                                 int indexAdjustment,
8705                                 Optional<unsigned> NumExpansions,
8706                                 bool ExpectParameterPack);
8707   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8708                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8709                       const MultiLevelTemplateArgumentList &TemplateArgs,
8710                       SmallVectorImpl<QualType> &ParamTypes,
8711                       SmallVectorImpl<ParmVarDecl *> *OutParams,
8712                       ExtParameterInfoBuilder &ParamInfos);
8713   ExprResult SubstExpr(Expr *E,
8714                        const MultiLevelTemplateArgumentList &TemplateArgs);
8715 
8716   /// Substitute the given template arguments into a list of
8717   /// expressions, expanding pack expansions if required.
8718   ///
8719   /// \param Exprs The list of expressions to substitute into.
8720   ///
8721   /// \param IsCall Whether this is some form of call, in which case
8722   /// default arguments will be dropped.
8723   ///
8724   /// \param TemplateArgs The set of template arguments to substitute.
8725   ///
8726   /// \param Outputs Will receive all of the substituted arguments.
8727   ///
8728   /// \returns true if an error occurred, false otherwise.
8729   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
8730                   const MultiLevelTemplateArgumentList &TemplateArgs,
8731                   SmallVectorImpl<Expr *> &Outputs);
8732 
8733   StmtResult SubstStmt(Stmt *S,
8734                        const MultiLevelTemplateArgumentList &TemplateArgs);
8735 
8736   TemplateParameterList *
8737   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
8738                       const MultiLevelTemplateArgumentList &TemplateArgs);
8739 
8740   bool
8741   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
8742                          const MultiLevelTemplateArgumentList &TemplateArgs,
8743                          TemplateArgumentListInfo &Outputs);
8744 
8745 
8746   Decl *SubstDecl(Decl *D, DeclContext *Owner,
8747                   const MultiLevelTemplateArgumentList &TemplateArgs);
8748 
8749   /// Substitute the name and return type of a defaulted 'operator<=>' to form
8750   /// an implicit 'operator=='.
8751   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
8752                                            FunctionDecl *Spaceship);
8753 
8754   ExprResult SubstInitializer(Expr *E,
8755                        const MultiLevelTemplateArgumentList &TemplateArgs,
8756                        bool CXXDirectInit);
8757 
8758   bool
8759   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
8760                       CXXRecordDecl *Pattern,
8761                       const MultiLevelTemplateArgumentList &TemplateArgs);
8762 
8763   bool
8764   InstantiateClass(SourceLocation PointOfInstantiation,
8765                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
8766                    const MultiLevelTemplateArgumentList &TemplateArgs,
8767                    TemplateSpecializationKind TSK,
8768                    bool Complain = true);
8769 
8770   bool InstantiateEnum(SourceLocation PointOfInstantiation,
8771                        EnumDecl *Instantiation, EnumDecl *Pattern,
8772                        const MultiLevelTemplateArgumentList &TemplateArgs,
8773                        TemplateSpecializationKind TSK);
8774 
8775   bool InstantiateInClassInitializer(
8776       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
8777       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
8778 
8779   struct LateInstantiatedAttribute {
8780     const Attr *TmplAttr;
8781     LocalInstantiationScope *Scope;
8782     Decl *NewDecl;
8783 
8784     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
8785                               Decl *D)
8786       : TmplAttr(A), Scope(S), NewDecl(D)
8787     { }
8788   };
8789   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
8790 
8791   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
8792                         const Decl *Pattern, Decl *Inst,
8793                         LateInstantiatedAttrVec *LateAttrs = nullptr,
8794                         LocalInstantiationScope *OuterMostScope = nullptr);
8795 
8796   void
8797   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
8798                           const Decl *Pattern, Decl *Inst,
8799                           LateInstantiatedAttrVec *LateAttrs = nullptr,
8800                           LocalInstantiationScope *OuterMostScope = nullptr);
8801 
8802   bool usesPartialOrExplicitSpecialization(
8803       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
8804 
8805   bool
8806   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
8807                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
8808                            TemplateSpecializationKind TSK,
8809                            bool Complain = true);
8810 
8811   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
8812                                CXXRecordDecl *Instantiation,
8813                             const MultiLevelTemplateArgumentList &TemplateArgs,
8814                                TemplateSpecializationKind TSK);
8815 
8816   void InstantiateClassTemplateSpecializationMembers(
8817                                           SourceLocation PointOfInstantiation,
8818                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
8819                                                 TemplateSpecializationKind TSK);
8820 
8821   NestedNameSpecifierLoc
8822   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
8823                            const MultiLevelTemplateArgumentList &TemplateArgs);
8824 
8825   DeclarationNameInfo
8826   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
8827                            const MultiLevelTemplateArgumentList &TemplateArgs);
8828   TemplateName
8829   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
8830                     SourceLocation Loc,
8831                     const MultiLevelTemplateArgumentList &TemplateArgs);
8832   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
8833              TemplateArgumentListInfo &Result,
8834              const MultiLevelTemplateArgumentList &TemplateArgs);
8835 
8836   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
8837                                 FunctionDecl *Function);
8838   bool CheckInstantiatedFunctionTemplateConstraints(
8839       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
8840       ArrayRef<TemplateArgument> TemplateArgs,
8841       ConstraintSatisfaction &Satisfaction);
8842   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
8843                                                const TemplateArgumentList *Args,
8844                                                SourceLocation Loc);
8845   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
8846                                      FunctionDecl *Function,
8847                                      bool Recursive = false,
8848                                      bool DefinitionRequired = false,
8849                                      bool AtEndOfTU = false);
8850   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
8851       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
8852       const TemplateArgumentList &TemplateArgList,
8853       const TemplateArgumentListInfo &TemplateArgsInfo,
8854       SmallVectorImpl<TemplateArgument> &Converted,
8855       SourceLocation PointOfInstantiation, void *InsertPos,
8856       LateInstantiatedAttrVec *LateAttrs = nullptr,
8857       LocalInstantiationScope *StartingScope = nullptr);
8858   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
8859       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
8860       const MultiLevelTemplateArgumentList &TemplateArgs);
8861   void
8862   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
8863                              const MultiLevelTemplateArgumentList &TemplateArgs,
8864                              LateInstantiatedAttrVec *LateAttrs,
8865                              DeclContext *Owner,
8866                              LocalInstantiationScope *StartingScope,
8867                              bool InstantiatingVarTemplate = false,
8868                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
8869 
8870   VarDecl *getVarTemplateSpecialization(
8871       VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
8872       const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
8873 
8874   void InstantiateVariableInitializer(
8875       VarDecl *Var, VarDecl *OldVar,
8876       const MultiLevelTemplateArgumentList &TemplateArgs);
8877   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
8878                                      VarDecl *Var, bool Recursive = false,
8879                                      bool DefinitionRequired = false,
8880                                      bool AtEndOfTU = false);
8881 
8882   void InstantiateMemInitializers(CXXConstructorDecl *New,
8883                                   const CXXConstructorDecl *Tmpl,
8884                             const MultiLevelTemplateArgumentList &TemplateArgs);
8885 
8886   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
8887                           const MultiLevelTemplateArgumentList &TemplateArgs,
8888                           bool FindingInstantiatedContext = false);
8889   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
8890                           const MultiLevelTemplateArgumentList &TemplateArgs);
8891 
8892   // Objective-C declarations.
8893   enum ObjCContainerKind {
8894     OCK_None = -1,
8895     OCK_Interface = 0,
8896     OCK_Protocol,
8897     OCK_Category,
8898     OCK_ClassExtension,
8899     OCK_Implementation,
8900     OCK_CategoryImplementation
8901   };
8902   ObjCContainerKind getObjCContainerKind() const;
8903 
8904   DeclResult actOnObjCTypeParam(Scope *S,
8905                                 ObjCTypeParamVariance variance,
8906                                 SourceLocation varianceLoc,
8907                                 unsigned index,
8908                                 IdentifierInfo *paramName,
8909                                 SourceLocation paramLoc,
8910                                 SourceLocation colonLoc,
8911                                 ParsedType typeBound);
8912 
8913   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
8914                                             ArrayRef<Decl *> typeParams,
8915                                             SourceLocation rAngleLoc);
8916   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
8917 
8918   Decl *ActOnStartClassInterface(
8919       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8920       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8921       IdentifierInfo *SuperName, SourceLocation SuperLoc,
8922       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
8923       Decl *const *ProtoRefs, unsigned NumProtoRefs,
8924       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8925       const ParsedAttributesView &AttrList);
8926 
8927   void ActOnSuperClassOfClassInterface(Scope *S,
8928                                        SourceLocation AtInterfaceLoc,
8929                                        ObjCInterfaceDecl *IDecl,
8930                                        IdentifierInfo *ClassName,
8931                                        SourceLocation ClassLoc,
8932                                        IdentifierInfo *SuperName,
8933                                        SourceLocation SuperLoc,
8934                                        ArrayRef<ParsedType> SuperTypeArgs,
8935                                        SourceRange SuperTypeArgsRange);
8936 
8937   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
8938                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
8939                                IdentifierInfo *SuperName,
8940                                SourceLocation SuperLoc);
8941 
8942   Decl *ActOnCompatibilityAlias(
8943                     SourceLocation AtCompatibilityAliasLoc,
8944                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
8945                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
8946 
8947   bool CheckForwardProtocolDeclarationForCircularDependency(
8948     IdentifierInfo *PName,
8949     SourceLocation &PLoc, SourceLocation PrevLoc,
8950     const ObjCList<ObjCProtocolDecl> &PList);
8951 
8952   Decl *ActOnStartProtocolInterface(
8953       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
8954       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
8955       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
8956       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
8957 
8958   Decl *ActOnStartCategoryInterface(
8959       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8960       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8961       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
8962       Decl *const *ProtoRefs, unsigned NumProtoRefs,
8963       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8964       const ParsedAttributesView &AttrList);
8965 
8966   Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
8967                                       IdentifierInfo *ClassName,
8968                                       SourceLocation ClassLoc,
8969                                       IdentifierInfo *SuperClassname,
8970                                       SourceLocation SuperClassLoc,
8971                                       const ParsedAttributesView &AttrList);
8972 
8973   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
8974                                          IdentifierInfo *ClassName,
8975                                          SourceLocation ClassLoc,
8976                                          IdentifierInfo *CatName,
8977                                          SourceLocation CatLoc,
8978                                          const ParsedAttributesView &AttrList);
8979 
8980   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
8981                                                ArrayRef<Decl *> Decls);
8982 
8983   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
8984                    IdentifierInfo **IdentList,
8985                    SourceLocation *IdentLocs,
8986                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
8987                    unsigned NumElts);
8988 
8989   DeclGroupPtrTy
8990   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8991                                   ArrayRef<IdentifierLocPair> IdentList,
8992                                   const ParsedAttributesView &attrList);
8993 
8994   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8995                                ArrayRef<IdentifierLocPair> ProtocolId,
8996                                SmallVectorImpl<Decl *> &Protocols);
8997 
8998   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8999                                     SourceLocation ProtocolLoc,
9000                                     IdentifierInfo *TypeArgId,
9001                                     SourceLocation TypeArgLoc,
9002                                     bool SelectProtocolFirst = false);
9003 
9004   /// Given a list of identifiers (and their locations), resolve the
9005   /// names to either Objective-C protocol qualifiers or type
9006   /// arguments, as appropriate.
9007   void actOnObjCTypeArgsOrProtocolQualifiers(
9008          Scope *S,
9009          ParsedType baseType,
9010          SourceLocation lAngleLoc,
9011          ArrayRef<IdentifierInfo *> identifiers,
9012          ArrayRef<SourceLocation> identifierLocs,
9013          SourceLocation rAngleLoc,
9014          SourceLocation &typeArgsLAngleLoc,
9015          SmallVectorImpl<ParsedType> &typeArgs,
9016          SourceLocation &typeArgsRAngleLoc,
9017          SourceLocation &protocolLAngleLoc,
9018          SmallVectorImpl<Decl *> &protocols,
9019          SourceLocation &protocolRAngleLoc,
9020          bool warnOnIncompleteProtocols);
9021 
9022   /// Build a an Objective-C protocol-qualified 'id' type where no
9023   /// base type was specified.
9024   TypeResult actOnObjCProtocolQualifierType(
9025                SourceLocation lAngleLoc,
9026                ArrayRef<Decl *> protocols,
9027                ArrayRef<SourceLocation> protocolLocs,
9028                SourceLocation rAngleLoc);
9029 
9030   /// Build a specialized and/or protocol-qualified Objective-C type.
9031   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9032                Scope *S,
9033                SourceLocation Loc,
9034                ParsedType BaseType,
9035                SourceLocation TypeArgsLAngleLoc,
9036                ArrayRef<ParsedType> TypeArgs,
9037                SourceLocation TypeArgsRAngleLoc,
9038                SourceLocation ProtocolLAngleLoc,
9039                ArrayRef<Decl *> Protocols,
9040                ArrayRef<SourceLocation> ProtocolLocs,
9041                SourceLocation ProtocolRAngleLoc);
9042 
9043   /// Build an Objective-C type parameter type.
9044   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9045                                   SourceLocation ProtocolLAngleLoc,
9046                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9047                                   ArrayRef<SourceLocation> ProtocolLocs,
9048                                   SourceLocation ProtocolRAngleLoc,
9049                                   bool FailOnError = false);
9050 
9051   /// Build an Objective-C object pointer type.
9052   QualType BuildObjCObjectType(QualType BaseType,
9053                                SourceLocation Loc,
9054                                SourceLocation TypeArgsLAngleLoc,
9055                                ArrayRef<TypeSourceInfo *> TypeArgs,
9056                                SourceLocation TypeArgsRAngleLoc,
9057                                SourceLocation ProtocolLAngleLoc,
9058                                ArrayRef<ObjCProtocolDecl *> Protocols,
9059                                ArrayRef<SourceLocation> ProtocolLocs,
9060                                SourceLocation ProtocolRAngleLoc,
9061                                bool FailOnError = false);
9062 
9063   /// Ensure attributes are consistent with type.
9064   /// \param [in, out] Attributes The attributes to check; they will
9065   /// be modified to be consistent with \p PropertyTy.
9066   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9067                                    SourceLocation Loc,
9068                                    unsigned &Attributes,
9069                                    bool propertyInPrimaryClass);
9070 
9071   /// Process the specified property declaration and create decls for the
9072   /// setters and getters as needed.
9073   /// \param property The property declaration being processed
9074   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9075 
9076 
9077   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9078                                 ObjCPropertyDecl *SuperProperty,
9079                                 const IdentifierInfo *Name,
9080                                 bool OverridingProtocolProperty);
9081 
9082   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9083                                         ObjCInterfaceDecl *ID);
9084 
9085   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9086                    ArrayRef<Decl *> allMethods = None,
9087                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
9088 
9089   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9090                       SourceLocation LParenLoc,
9091                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
9092                       Selector GetterSel, Selector SetterSel,
9093                       tok::ObjCKeywordKind MethodImplKind,
9094                       DeclContext *lexicalDC = nullptr);
9095 
9096   Decl *ActOnPropertyImplDecl(Scope *S,
9097                               SourceLocation AtLoc,
9098                               SourceLocation PropertyLoc,
9099                               bool ImplKind,
9100                               IdentifierInfo *PropertyId,
9101                               IdentifierInfo *PropertyIvar,
9102                               SourceLocation PropertyIvarLoc,
9103                               ObjCPropertyQueryKind QueryKind);
9104 
9105   enum ObjCSpecialMethodKind {
9106     OSMK_None,
9107     OSMK_Alloc,
9108     OSMK_New,
9109     OSMK_Copy,
9110     OSMK_RetainingInit,
9111     OSMK_NonRetainingInit
9112   };
9113 
9114   struct ObjCArgInfo {
9115     IdentifierInfo *Name;
9116     SourceLocation NameLoc;
9117     // The Type is null if no type was specified, and the DeclSpec is invalid
9118     // in this case.
9119     ParsedType Type;
9120     ObjCDeclSpec DeclSpec;
9121 
9122     /// ArgAttrs - Attribute list for this argument.
9123     ParsedAttributesView ArgAttrs;
9124   };
9125 
9126   Decl *ActOnMethodDeclaration(
9127       Scope *S,
9128       SourceLocation BeginLoc, // location of the + or -.
9129       SourceLocation EndLoc,   // location of the ; or {.
9130       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9131       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9132       // optional arguments. The number of types/arguments is obtained
9133       // from the Sel.getNumArgs().
9134       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9135       unsigned CNumArgs, // c-style args
9136       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9137       bool isVariadic, bool MethodDefinition);
9138 
9139   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9140                                               const ObjCObjectPointerType *OPT,
9141                                               bool IsInstance);
9142   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9143                                            bool IsInstance);
9144 
9145   bool CheckARCMethodDecl(ObjCMethodDecl *method);
9146   bool inferObjCARCLifetime(ValueDecl *decl);
9147 
9148   void deduceOpenCLAddressSpace(ValueDecl *decl);
9149 
9150   ExprResult
9151   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9152                             Expr *BaseExpr,
9153                             SourceLocation OpLoc,
9154                             DeclarationName MemberName,
9155                             SourceLocation MemberLoc,
9156                             SourceLocation SuperLoc, QualType SuperType,
9157                             bool Super);
9158 
9159   ExprResult
9160   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9161                             IdentifierInfo &propertyName,
9162                             SourceLocation receiverNameLoc,
9163                             SourceLocation propertyNameLoc);
9164 
9165   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9166 
9167   /// Describes the kind of message expression indicated by a message
9168   /// send that starts with an identifier.
9169   enum ObjCMessageKind {
9170     /// The message is sent to 'super'.
9171     ObjCSuperMessage,
9172     /// The message is an instance message.
9173     ObjCInstanceMessage,
9174     /// The message is a class message, and the identifier is a type
9175     /// name.
9176     ObjCClassMessage
9177   };
9178 
9179   ObjCMessageKind getObjCMessageKind(Scope *S,
9180                                      IdentifierInfo *Name,
9181                                      SourceLocation NameLoc,
9182                                      bool IsSuper,
9183                                      bool HasTrailingDot,
9184                                      ParsedType &ReceiverType);
9185 
9186   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9187                                Selector Sel,
9188                                SourceLocation LBracLoc,
9189                                ArrayRef<SourceLocation> SelectorLocs,
9190                                SourceLocation RBracLoc,
9191                                MultiExprArg Args);
9192 
9193   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9194                                QualType ReceiverType,
9195                                SourceLocation SuperLoc,
9196                                Selector Sel,
9197                                ObjCMethodDecl *Method,
9198                                SourceLocation LBracLoc,
9199                                ArrayRef<SourceLocation> SelectorLocs,
9200                                SourceLocation RBracLoc,
9201                                MultiExprArg Args,
9202                                bool isImplicit = false);
9203 
9204   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9205                                        bool isSuperReceiver,
9206                                        SourceLocation Loc,
9207                                        Selector Sel,
9208                                        ObjCMethodDecl *Method,
9209                                        MultiExprArg Args);
9210 
9211   ExprResult ActOnClassMessage(Scope *S,
9212                                ParsedType Receiver,
9213                                Selector Sel,
9214                                SourceLocation LBracLoc,
9215                                ArrayRef<SourceLocation> SelectorLocs,
9216                                SourceLocation RBracLoc,
9217                                MultiExprArg Args);
9218 
9219   ExprResult BuildInstanceMessage(Expr *Receiver,
9220                                   QualType ReceiverType,
9221                                   SourceLocation SuperLoc,
9222                                   Selector Sel,
9223                                   ObjCMethodDecl *Method,
9224                                   SourceLocation LBracLoc,
9225                                   ArrayRef<SourceLocation> SelectorLocs,
9226                                   SourceLocation RBracLoc,
9227                                   MultiExprArg Args,
9228                                   bool isImplicit = false);
9229 
9230   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9231                                           QualType ReceiverType,
9232                                           SourceLocation Loc,
9233                                           Selector Sel,
9234                                           ObjCMethodDecl *Method,
9235                                           MultiExprArg Args);
9236 
9237   ExprResult ActOnInstanceMessage(Scope *S,
9238                                   Expr *Receiver,
9239                                   Selector Sel,
9240                                   SourceLocation LBracLoc,
9241                                   ArrayRef<SourceLocation> SelectorLocs,
9242                                   SourceLocation RBracLoc,
9243                                   MultiExprArg Args);
9244 
9245   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9246                                   ObjCBridgeCastKind Kind,
9247                                   SourceLocation BridgeKeywordLoc,
9248                                   TypeSourceInfo *TSInfo,
9249                                   Expr *SubExpr);
9250 
9251   ExprResult ActOnObjCBridgedCast(Scope *S,
9252                                   SourceLocation LParenLoc,
9253                                   ObjCBridgeCastKind Kind,
9254                                   SourceLocation BridgeKeywordLoc,
9255                                   ParsedType Type,
9256                                   SourceLocation RParenLoc,
9257                                   Expr *SubExpr);
9258 
9259   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9260 
9261   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9262 
9263   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9264                                      CastKind &Kind);
9265 
9266   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9267                                         QualType DestType, QualType SrcType,
9268                                         ObjCInterfaceDecl *&RelatedClass,
9269                                         ObjCMethodDecl *&ClassMethod,
9270                                         ObjCMethodDecl *&InstanceMethod,
9271                                         TypedefNameDecl *&TDNDecl,
9272                                         bool CfToNs, bool Diagnose = true);
9273 
9274   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9275                                          QualType DestType, QualType SrcType,
9276                                          Expr *&SrcExpr, bool Diagnose = true);
9277 
9278   bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
9279                                           bool Diagnose = true);
9280 
9281   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9282 
9283   /// Check whether the given new method is a valid override of the
9284   /// given overridden method, and set any properties that should be inherited.
9285   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9286                                const ObjCMethodDecl *Overridden);
9287 
9288   /// Describes the compatibility of a result type with its method.
9289   enum ResultTypeCompatibilityKind {
9290     RTC_Compatible,
9291     RTC_Incompatible,
9292     RTC_Unknown
9293   };
9294 
9295   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9296                                       ObjCMethodDecl *overridden);
9297 
9298   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9299                                 ObjCInterfaceDecl *CurrentClass,
9300                                 ResultTypeCompatibilityKind RTC);
9301 
9302   enum PragmaOptionsAlignKind {
9303     POAK_Native,  // #pragma options align=native
9304     POAK_Natural, // #pragma options align=natural
9305     POAK_Packed,  // #pragma options align=packed
9306     POAK_Power,   // #pragma options align=power
9307     POAK_Mac68k,  // #pragma options align=mac68k
9308     POAK_Reset    // #pragma options align=reset
9309   };
9310 
9311   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9312   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9313                                PragmaClangSectionAction Action,
9314                                PragmaClangSectionKind SecKind, StringRef SecName);
9315 
9316   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9317   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9318                                SourceLocation PragmaLoc);
9319 
9320   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9321   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9322                        StringRef SlotLabel, Expr *Alignment);
9323 
9324   enum class PragmaPackDiagnoseKind {
9325     NonDefaultStateAtInclude,
9326     ChangedStateAtExit
9327   };
9328 
9329   void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
9330                                     SourceLocation IncludeLoc);
9331   void DiagnoseUnterminatedPragmaPack();
9332 
9333   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9334   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9335 
9336   /// ActOnPragmaMSComment - Called on well formed
9337   /// \#pragma comment(kind, "arg").
9338   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9339                             StringRef Arg);
9340 
9341   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9342   /// pointers_to_members(representation method[, general purpose
9343   /// representation]).
9344   void ActOnPragmaMSPointersToMembers(
9345       LangOptions::PragmaMSPointersToMembersKind Kind,
9346       SourceLocation PragmaLoc);
9347 
9348   /// Called on well formed \#pragma vtordisp().
9349   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9350                              SourceLocation PragmaLoc,
9351                              MSVtorDispMode Value);
9352 
9353   enum PragmaSectionKind {
9354     PSK_DataSeg,
9355     PSK_BSSSeg,
9356     PSK_ConstSeg,
9357     PSK_CodeSeg,
9358   };
9359 
9360   bool UnifySection(StringRef SectionName,
9361                     int SectionFlags,
9362                     DeclaratorDecl *TheDecl);
9363   bool UnifySection(StringRef SectionName,
9364                     int SectionFlags,
9365                     SourceLocation PragmaSectionLocation);
9366 
9367   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9368   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9369                         PragmaMsStackAction Action,
9370                         llvm::StringRef StackSlotLabel,
9371                         StringLiteral *SegmentName,
9372                         llvm::StringRef PragmaName);
9373 
9374   /// Called on well formed \#pragma section().
9375   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9376                             int SectionFlags, StringLiteral *SegmentName);
9377 
9378   /// Called on well-formed \#pragma init_seg().
9379   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9380                             StringLiteral *SegmentName);
9381 
9382   /// Called on #pragma clang __debug dump II
9383   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9384 
9385   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9386   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9387                                  StringRef Value);
9388 
9389   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9390   void ActOnPragmaUnused(const Token &Identifier,
9391                          Scope *curScope,
9392                          SourceLocation PragmaLoc);
9393 
9394   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9395   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9396                              SourceLocation PragmaLoc);
9397 
9398   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9399                                  SourceLocation Loc);
9400   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9401 
9402   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9403   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9404                          SourceLocation PragmaLoc,
9405                          SourceLocation WeakNameLoc);
9406 
9407   /// ActOnPragmaRedefineExtname - Called on well formed
9408   /// \#pragma redefine_extname oldname newname.
9409   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9410                                   IdentifierInfo* AliasName,
9411                                   SourceLocation PragmaLoc,
9412                                   SourceLocation WeakNameLoc,
9413                                   SourceLocation AliasNameLoc);
9414 
9415   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9416   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9417                             IdentifierInfo* AliasName,
9418                             SourceLocation PragmaLoc,
9419                             SourceLocation WeakNameLoc,
9420                             SourceLocation AliasNameLoc);
9421 
9422   /// ActOnPragmaFPContract - Called on well formed
9423   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9424   /// \#pragma clang fp contract
9425   void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
9426 
9427   /// ActOnPragmaFenvAccess - Called on well formed
9428   /// \#pragma STDC FENV_ACCESS
9429   void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
9430 
9431   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9432   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9433   void AddAlignmentAttributesForRecord(RecordDecl *RD);
9434 
9435   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9436   void AddMsStructLayoutForRecord(RecordDecl *RD);
9437 
9438   /// FreePackedContext - Deallocate and null out PackContext.
9439   void FreePackedContext();
9440 
9441   /// PushNamespaceVisibilityAttr - Note that we've entered a
9442   /// namespace with a visibility attribute.
9443   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9444                                    SourceLocation Loc);
9445 
9446   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9447   /// add an appropriate visibility attribute.
9448   void AddPushedVisibilityAttribute(Decl *RD);
9449 
9450   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9451   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9452   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9453 
9454   /// FreeVisContext - Deallocate and null out VisContext.
9455   void FreeVisContext();
9456 
9457   /// AddCFAuditedAttribute - Check whether we're currently within
9458   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9459   /// the appropriate attribute.
9460   void AddCFAuditedAttribute(Decl *D);
9461 
9462   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9463                                      SourceLocation PragmaLoc,
9464                                      attr::ParsedSubjectMatchRuleSet Rules);
9465   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9466                                      const IdentifierInfo *Namespace);
9467 
9468   /// Called on well-formed '\#pragma clang attribute pop'.
9469   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9470                                const IdentifierInfo *Namespace);
9471 
9472   /// Adds the attributes that have been specified using the
9473   /// '\#pragma clang attribute push' directives to the given declaration.
9474   void AddPragmaAttributes(Scope *S, Decl *D);
9475 
9476   void DiagnoseUnterminatedPragmaAttribute();
9477 
9478   /// Called on well formed \#pragma clang optimize.
9479   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9480 
9481   /// Get the location for the currently active "\#pragma clang optimize
9482   /// off". If this location is invalid, then the state of the pragma is "on".
9483   SourceLocation getOptimizeOffPragmaLocation() const {
9484     return OptimizeOffPragmaLocation;
9485   }
9486 
9487   /// Only called on function definitions; if there is a pragma in scope
9488   /// with the effect of a range-based optnone, consider marking the function
9489   /// with attribute optnone.
9490   void AddRangeBasedOptnone(FunctionDecl *FD);
9491 
9492   /// Adds the 'optnone' attribute to the function declaration if there
9493   /// are no conflicts; Loc represents the location causing the 'optnone'
9494   /// attribute to be added (usually because of a pragma).
9495   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9496 
9497   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9498   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9499                       bool IsPackExpansion);
9500   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9501                       bool IsPackExpansion);
9502 
9503   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9504   /// declaration.
9505   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9506                             Expr *OE);
9507 
9508   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9509   /// declaration.
9510   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9511                          Expr *ParamExpr);
9512 
9513   /// AddAlignValueAttr - Adds an align_value attribute to a particular
9514   /// declaration.
9515   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9516 
9517   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
9518   /// declaration.
9519   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
9520                            Expr *MaxThreads, Expr *MinBlocks);
9521 
9522   /// AddModeAttr - Adds a mode attribute to a particular declaration.
9523   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9524                    bool InInstantiation = false);
9525 
9526   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9527                            ParameterABI ABI);
9528 
9529   enum class RetainOwnershipKind {NS, CF, OS};
9530   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9531                         RetainOwnershipKind K, bool IsTemplateInstantiation);
9532 
9533   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9534   /// attribute to a particular declaration.
9535   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9536                                       Expr *Min, Expr *Max);
9537 
9538   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9539   /// particular declaration.
9540   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9541                                Expr *Min, Expr *Max);
9542 
9543   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9544 
9545   //===--------------------------------------------------------------------===//
9546   // C++ Coroutines TS
9547   //
9548   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9549                                StringRef Keyword);
9550   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9551   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9552   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9553 
9554   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9555                                       bool IsImplicit = false);
9556   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9557                                         UnresolvedLookupExpr* Lookup);
9558   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9559   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9560                                bool IsImplicit = false);
9561   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9562   bool buildCoroutineParameterMoves(SourceLocation Loc);
9563   VarDecl *buildCoroutinePromise(SourceLocation Loc);
9564   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9565   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9566                                            SourceLocation FuncLoc);
9567 
9568   //===--------------------------------------------------------------------===//
9569   // OpenCL extensions.
9570   //
9571 private:
9572   std::string CurrOpenCLExtension;
9573   /// Extensions required by an OpenCL type.
9574   llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9575   /// Extensions required by an OpenCL declaration.
9576   llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9577 public:
9578   llvm::StringRef getCurrentOpenCLExtension() const {
9579     return CurrOpenCLExtension;
9580   }
9581 
9582   /// Check if a function declaration \p FD associates with any
9583   /// extensions present in OpenCLDeclExtMap and if so return the
9584   /// extension(s) name(s).
9585   std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9586 
9587   /// Check if a function type \p FT associates with any
9588   /// extensions present in OpenCLTypeExtMap and if so return the
9589   /// extension(s) name(s).
9590   std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9591 
9592   /// Find an extension in an appropriate extension map and return its name
9593   template<typename T, typename MapT>
9594   std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9595 
9596   void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9597     CurrOpenCLExtension = Ext;
9598   }
9599 
9600   /// Set OpenCL extensions for a type which can only be used when these
9601   /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9602   /// \param Exts A space separated list of OpenCL extensions.
9603   void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9604 
9605   /// Set OpenCL extensions for a declaration which can only be
9606   /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9607   /// nothing.
9608   /// \param Exts A space separated list of OpenCL extensions.
9609   void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9610 
9611   /// Set current OpenCL extensions for a type which can only be used
9612   /// when these OpenCL extensions are enabled. If current OpenCL extension is
9613   /// empty, do nothing.
9614   void setCurrentOpenCLExtensionForType(QualType T);
9615 
9616   /// Set current OpenCL extensions for a declaration which
9617   /// can only be used when these OpenCL extensions are enabled. If current
9618   /// OpenCL extension is empty, do nothing.
9619   void setCurrentOpenCLExtensionForDecl(Decl *FD);
9620 
9621   bool isOpenCLDisabledDecl(Decl *FD);
9622 
9623   /// Check if type \p T corresponding to declaration specifier \p DS
9624   /// is disabled due to required OpenCL extensions being disabled. If so,
9625   /// emit diagnostics.
9626   /// \return true if type is disabled.
9627   bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9628 
9629   /// Check if declaration \p D used by expression \p E
9630   /// is disabled due to required OpenCL extensions being disabled. If so,
9631   /// emit diagnostics.
9632   /// \return true if type is disabled.
9633   bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9634 
9635   //===--------------------------------------------------------------------===//
9636   // OpenMP directives and clauses.
9637   //
9638 private:
9639   void *VarDataSharingAttributesStack;
9640   /// Number of nested '#pragma omp declare target' directives.
9641   unsigned DeclareTargetNestingLevel = 0;
9642   /// Initialization of data-sharing attributes stack.
9643   void InitDataSharingAttributesStack();
9644   void DestroyDataSharingAttributesStack();
9645   ExprResult
9646   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9647                                         bool StrictlyPositive = true);
9648   /// Returns OpenMP nesting level for current directive.
9649   unsigned getOpenMPNestingLevel() const;
9650 
9651   /// Adjusts the function scopes index for the target-based regions.
9652   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9653                                     unsigned Level) const;
9654 
9655   /// Returns the number of scopes associated with the construct on the given
9656   /// OpenMP level.
9657   int getNumberOfConstructScopes(unsigned Level) const;
9658 
9659   /// Push new OpenMP function region for non-capturing function.
9660   void pushOpenMPFunctionRegion();
9661 
9662   /// Pop OpenMP function region for non-capturing function.
9663   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9664 
9665   /// Check whether we're allowed to call Callee from the current function.
9666   void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
9667                                  bool CheckForDelayedContext = true);
9668 
9669   /// Check whether we're allowed to call Callee from the current function.
9670   void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
9671                                bool CheckCaller = true);
9672 
9673   /// Check if the expression is allowed to be used in expressions for the
9674   /// OpenMP devices.
9675   void checkOpenMPDeviceExpr(const Expr *E);
9676 
9677   /// Finishes analysis of the deferred functions calls that may be declared as
9678   /// host/nohost during device/host compilation.
9679   void finalizeOpenMPDelayedAnalysis();
9680 
9681   /// Checks if a type or a declaration is disabled due to the owning extension
9682   /// being disabled, and emits diagnostic messages if it is disabled.
9683   /// \param D type or declaration to be checked.
9684   /// \param DiagLoc source location for the diagnostic message.
9685   /// \param DiagInfo information to be emitted for the diagnostic message.
9686   /// \param SrcRange source range of the declaration.
9687   /// \param Map maps type or declaration to the extensions.
9688   /// \param Selector selects diagnostic message: 0 for type and 1 for
9689   ///        declaration.
9690   /// \return true if the type or declaration is disabled.
9691   template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9692   bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9693                                      MapT &Map, unsigned Selector = 0,
9694                                      SourceRange SrcRange = SourceRange());
9695 
9696   /// Marks all the functions that might be required for the currently active
9697   /// OpenMP context.
9698   void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
9699                                                FunctionDecl *Func,
9700                                                bool MightBeOdrUse);
9701 
9702 public:
9703   /// Struct to store the context selectors info for declare variant directive.
9704   using OMPCtxStringType = SmallString<8>;
9705   using OMPCtxSelectorData =
9706       OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>;
9707 
9708   /// Checks if the variant/multiversion functions are compatible.
9709   bool areMultiversionVariantFunctionsCompatible(
9710       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9711       const PartialDiagnostic &NoProtoDiagID,
9712       const PartialDiagnosticAt &NoteCausedDiagIDAt,
9713       const PartialDiagnosticAt &NoSupportDiagIDAt,
9714       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9715       bool ConstexprSupported, bool CLinkageMayDiffer);
9716 
9717   /// Function tries to capture lambda's captured variables in the OpenMP region
9718   /// before the original lambda is captured.
9719   void tryCaptureOpenMPLambdas(ValueDecl *V);
9720 
9721   /// Return true if the provided declaration \a VD should be captured by
9722   /// reference.
9723   /// \param Level Relative level of nested OpenMP construct for that the check
9724   /// is performed.
9725   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
9726   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
9727                              unsigned OpenMPCaptureLevel) const;
9728 
9729   /// Check if the specified variable is used in one of the private
9730   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
9731   /// constructs.
9732   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
9733                                 unsigned StopAt = 0);
9734   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9735                                    ExprObjectKind OK, SourceLocation Loc);
9736 
9737   /// If the current region is a loop-based region, mark the start of the loop
9738   /// construct.
9739   void startOpenMPLoop();
9740 
9741   /// If the current region is a range loop-based region, mark the start of the
9742   /// loop construct.
9743   void startOpenMPCXXRangeFor();
9744 
9745   /// Check if the specified variable is used in 'private' clause.
9746   /// \param Level Relative level of nested OpenMP construct for that the check
9747   /// is performed.
9748   bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
9749 
9750   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
9751   /// for \p FD based on DSA for the provided corresponding captured declaration
9752   /// \p D.
9753   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
9754 
9755   /// Check if the specified variable is captured  by 'target' directive.
9756   /// \param Level Relative level of nested OpenMP construct for that the check
9757   /// is performed.
9758   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
9759 
9760   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
9761                                                     Expr *Op);
9762   /// Called on start of new data sharing attribute block.
9763   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
9764                            const DeclarationNameInfo &DirName, Scope *CurScope,
9765                            SourceLocation Loc);
9766   /// Start analysis of clauses.
9767   void StartOpenMPClause(OpenMPClauseKind K);
9768   /// End analysis of clauses.
9769   void EndOpenMPClause();
9770   /// Called on end of data sharing attribute block.
9771   void EndOpenMPDSABlock(Stmt *CurDirective);
9772 
9773   /// Check if the current region is an OpenMP loop region and if it is,
9774   /// mark loop control variable, used in \p Init for loop initialization, as
9775   /// private by default.
9776   /// \param Init First part of the for loop.
9777   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
9778 
9779   // OpenMP directives and clauses.
9780   /// Called on correct id-expression from the '#pragma omp
9781   /// threadprivate'.
9782   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9783                                      const DeclarationNameInfo &Id,
9784                                      OpenMPDirectiveKind Kind);
9785   /// Called on well-formed '#pragma omp threadprivate'.
9786   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
9787                                      SourceLocation Loc,
9788                                      ArrayRef<Expr *> VarList);
9789   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
9790   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
9791                                                   ArrayRef<Expr *> VarList);
9792   /// Called on well-formed '#pragma omp allocate'.
9793   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
9794                                               ArrayRef<Expr *> VarList,
9795                                               ArrayRef<OMPClause *> Clauses,
9796                                               DeclContext *Owner = nullptr);
9797   /// Called on well-formed '#pragma omp requires'.
9798   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
9799                                               ArrayRef<OMPClause *> ClauseList);
9800   /// Check restrictions on Requires directive
9801   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
9802                                         ArrayRef<OMPClause *> Clauses);
9803   /// Check if the specified type is allowed to be used in 'omp declare
9804   /// reduction' construct.
9805   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9806                                            TypeResult ParsedType);
9807   /// Called on start of '#pragma omp declare reduction'.
9808   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
9809       Scope *S, DeclContext *DC, DeclarationName Name,
9810       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
9811       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
9812   /// Initialize declare reduction construct initializer.
9813   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
9814   /// Finish current declare reduction construct initializer.
9815   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
9816   /// Initialize declare reduction construct initializer.
9817   /// \return omp_priv variable.
9818   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
9819   /// Finish current declare reduction construct initializer.
9820   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
9821                                                  VarDecl *OmpPrivParm);
9822   /// Called at the end of '#pragma omp declare reduction'.
9823   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
9824       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
9825 
9826   /// Check variable declaration in 'omp declare mapper' construct.
9827   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
9828   /// Check if the specified type is allowed to be used in 'omp declare
9829   /// mapper' construct.
9830   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
9831                                         TypeResult ParsedType);
9832   /// Called on start of '#pragma omp declare mapper'.
9833   OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
9834       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
9835       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
9836       Decl *PrevDeclInScope = nullptr);
9837   /// Build the mapper variable of '#pragma omp declare mapper'.
9838   void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
9839                                                 Scope *S, QualType MapperType,
9840                                                 SourceLocation StartLoc,
9841                                                 DeclarationName VN);
9842   /// Called at the end of '#pragma omp declare mapper'.
9843   DeclGroupPtrTy
9844   ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
9845                                        ArrayRef<OMPClause *> ClauseList);
9846 
9847   /// Called on the start of target region i.e. '#pragma omp declare target'.
9848   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
9849   /// Called at the end of target region i.e. '#pragme omp end declare target'.
9850   void ActOnFinishOpenMPDeclareTargetDirective();
9851   /// Searches for the provided declaration name for OpenMP declare target
9852   /// directive.
9853   NamedDecl *
9854   lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9855                                 const DeclarationNameInfo &Id,
9856                                 NamedDeclSetType &SameDirectiveDecls);
9857   /// Called on correct id-expression from the '#pragma omp declare target'.
9858   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
9859                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
9860                                     OMPDeclareTargetDeclAttr::DevTypeTy DT);
9861   /// Check declaration inside target region.
9862   void
9863   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
9864                                    SourceLocation IdLoc = SourceLocation());
9865   /// Return true inside OpenMP declare target region.
9866   bool isInOpenMPDeclareTargetContext() const {
9867     return DeclareTargetNestingLevel > 0;
9868   }
9869   /// Return true inside OpenMP target region.
9870   bool isInOpenMPTargetExecutionDirective() const;
9871 
9872   /// Return the number of captured regions created for an OpenMP directive.
9873   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
9874 
9875   /// Initialization of captured region for OpenMP region.
9876   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
9877   /// End of OpenMP region.
9878   ///
9879   /// \param S Statement associated with the current OpenMP region.
9880   /// \param Clauses List of clauses for the current OpenMP region.
9881   ///
9882   /// \returns Statement for finished OpenMP region.
9883   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
9884   StmtResult ActOnOpenMPExecutableDirective(
9885       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
9886       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
9887       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
9888   /// Called on well-formed '\#pragma omp parallel' after parsing
9889   /// of the  associated statement.
9890   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
9891                                           Stmt *AStmt,
9892                                           SourceLocation StartLoc,
9893                                           SourceLocation EndLoc);
9894   using VarsWithInheritedDSAType =
9895       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
9896   /// Called on well-formed '\#pragma omp simd' after parsing
9897   /// of the associated statement.
9898   StmtResult
9899   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9900                            SourceLocation StartLoc, SourceLocation EndLoc,
9901                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
9902   /// Called on well-formed '\#pragma omp for' after parsing
9903   /// of the associated statement.
9904   StmtResult
9905   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9906                           SourceLocation StartLoc, SourceLocation EndLoc,
9907                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
9908   /// Called on well-formed '\#pragma omp for simd' after parsing
9909   /// of the associated statement.
9910   StmtResult
9911   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9912                               SourceLocation StartLoc, SourceLocation EndLoc,
9913                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
9914   /// Called on well-formed '\#pragma omp sections' after parsing
9915   /// of the associated statement.
9916   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9917                                           Stmt *AStmt, SourceLocation StartLoc,
9918                                           SourceLocation EndLoc);
9919   /// Called on well-formed '\#pragma omp section' after parsing of the
9920   /// associated statement.
9921   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
9922                                          SourceLocation EndLoc);
9923   /// Called on well-formed '\#pragma omp single' after parsing of the
9924   /// associated statement.
9925   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9926                                         Stmt *AStmt, SourceLocation StartLoc,
9927                                         SourceLocation EndLoc);
9928   /// Called on well-formed '\#pragma omp master' after parsing of the
9929   /// associated statement.
9930   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
9931                                         SourceLocation EndLoc);
9932   /// Called on well-formed '\#pragma omp critical' after parsing of the
9933   /// associated statement.
9934   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
9935                                           ArrayRef<OMPClause *> Clauses,
9936                                           Stmt *AStmt, SourceLocation StartLoc,
9937                                           SourceLocation EndLoc);
9938   /// Called on well-formed '\#pragma omp parallel for' after parsing
9939   /// of the  associated statement.
9940   StmtResult ActOnOpenMPParallelForDirective(
9941       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9942       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9943   /// Called on well-formed '\#pragma omp parallel for simd' after
9944   /// parsing of the  associated statement.
9945   StmtResult ActOnOpenMPParallelForSimdDirective(
9946       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9947       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9948   /// Called on well-formed '\#pragma omp parallel master' after
9949   /// parsing of the  associated statement.
9950   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9951                                                 Stmt *AStmt,
9952                                                 SourceLocation StartLoc,
9953                                                 SourceLocation EndLoc);
9954   /// Called on well-formed '\#pragma omp parallel sections' after
9955   /// parsing of the  associated statement.
9956   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9957                                                   Stmt *AStmt,
9958                                                   SourceLocation StartLoc,
9959                                                   SourceLocation EndLoc);
9960   /// Called on well-formed '\#pragma omp task' after parsing of the
9961   /// associated statement.
9962   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9963                                       Stmt *AStmt, SourceLocation StartLoc,
9964                                       SourceLocation EndLoc);
9965   /// Called on well-formed '\#pragma omp taskyield'.
9966   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9967                                            SourceLocation EndLoc);
9968   /// Called on well-formed '\#pragma omp barrier'.
9969   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9970                                          SourceLocation EndLoc);
9971   /// Called on well-formed '\#pragma omp taskwait'.
9972   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9973                                           SourceLocation EndLoc);
9974   /// Called on well-formed '\#pragma omp taskgroup'.
9975   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9976                                            Stmt *AStmt, SourceLocation StartLoc,
9977                                            SourceLocation EndLoc);
9978   /// Called on well-formed '\#pragma omp flush'.
9979   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9980                                        SourceLocation StartLoc,
9981                                        SourceLocation EndLoc);
9982   /// Called on well-formed '\#pragma omp ordered' after parsing of the
9983   /// associated statement.
9984   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9985                                          Stmt *AStmt, SourceLocation StartLoc,
9986                                          SourceLocation EndLoc);
9987   /// Called on well-formed '\#pragma omp atomic' after parsing of the
9988   /// associated statement.
9989   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9990                                         Stmt *AStmt, SourceLocation StartLoc,
9991                                         SourceLocation EndLoc);
9992   /// Called on well-formed '\#pragma omp target' after parsing of the
9993   /// associated statement.
9994   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9995                                         Stmt *AStmt, SourceLocation StartLoc,
9996                                         SourceLocation EndLoc);
9997   /// Called on well-formed '\#pragma omp target data' after parsing of
9998   /// the associated statement.
9999   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10000                                             Stmt *AStmt, SourceLocation StartLoc,
10001                                             SourceLocation EndLoc);
10002   /// Called on well-formed '\#pragma omp target enter data' after
10003   /// parsing of the associated statement.
10004   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10005                                                  SourceLocation StartLoc,
10006                                                  SourceLocation EndLoc,
10007                                                  Stmt *AStmt);
10008   /// Called on well-formed '\#pragma omp target exit data' after
10009   /// parsing of the associated statement.
10010   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10011                                                 SourceLocation StartLoc,
10012                                                 SourceLocation EndLoc,
10013                                                 Stmt *AStmt);
10014   /// Called on well-formed '\#pragma omp target parallel' after
10015   /// parsing of the associated statement.
10016   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10017                                                 Stmt *AStmt,
10018                                                 SourceLocation StartLoc,
10019                                                 SourceLocation EndLoc);
10020   /// Called on well-formed '\#pragma omp target parallel for' after
10021   /// parsing of the  associated statement.
10022   StmtResult ActOnOpenMPTargetParallelForDirective(
10023       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10024       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10025   /// Called on well-formed '\#pragma omp teams' after parsing of the
10026   /// associated statement.
10027   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10028                                        Stmt *AStmt, SourceLocation StartLoc,
10029                                        SourceLocation EndLoc);
10030   /// Called on well-formed '\#pragma omp cancellation point'.
10031   StmtResult
10032   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10033                                         SourceLocation EndLoc,
10034                                         OpenMPDirectiveKind CancelRegion);
10035   /// Called on well-formed '\#pragma omp cancel'.
10036   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10037                                         SourceLocation StartLoc,
10038                                         SourceLocation EndLoc,
10039                                         OpenMPDirectiveKind CancelRegion);
10040   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10041   /// associated statement.
10042   StmtResult
10043   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10044                                SourceLocation StartLoc, SourceLocation EndLoc,
10045                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
10046   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10047   /// the associated statement.
10048   StmtResult ActOnOpenMPTaskLoopSimdDirective(
10049       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10050       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10051   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10052   /// associated statement.
10053   StmtResult ActOnOpenMPMasterTaskLoopDirective(
10054       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10055       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10056   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10057   /// the associated statement.
10058   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10059       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10060       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10061   /// Called on well-formed '\#pragma omp parallel master taskloop' after
10062   /// parsing of the associated statement.
10063   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10064       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10065       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10066   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10067   /// parsing of the associated statement.
10068   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10069       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10070       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10071   /// Called on well-formed '\#pragma omp distribute' after parsing
10072   /// of the associated statement.
10073   StmtResult
10074   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10075                                  SourceLocation StartLoc, SourceLocation EndLoc,
10076                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10077   /// Called on well-formed '\#pragma omp target update'.
10078   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10079                                               SourceLocation StartLoc,
10080                                               SourceLocation EndLoc,
10081                                               Stmt *AStmt);
10082   /// Called on well-formed '\#pragma omp distribute parallel for' after
10083   /// parsing of the associated statement.
10084   StmtResult ActOnOpenMPDistributeParallelForDirective(
10085       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10086       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10087   /// Called on well-formed '\#pragma omp distribute parallel for simd'
10088   /// after parsing of the associated statement.
10089   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10090       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10091       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10092   /// Called on well-formed '\#pragma omp distribute simd' after
10093   /// parsing of the associated statement.
10094   StmtResult ActOnOpenMPDistributeSimdDirective(
10095       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10096       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10097   /// Called on well-formed '\#pragma omp target parallel for simd' after
10098   /// parsing of the associated statement.
10099   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10100       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10101       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10102   /// Called on well-formed '\#pragma omp target simd' after parsing of
10103   /// the associated statement.
10104   StmtResult
10105   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10106                                  SourceLocation StartLoc, SourceLocation EndLoc,
10107                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10108   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10109   /// the associated statement.
10110   StmtResult ActOnOpenMPTeamsDistributeDirective(
10111       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10112       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10113   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10114   /// of the associated statement.
10115   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10116       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10117       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10118   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10119   /// after parsing of the associated statement.
10120   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10121       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10122       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10123   /// Called on well-formed '\#pragma omp teams distribute parallel for'
10124   /// after parsing of the associated statement.
10125   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10126       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10127       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10128   /// Called on well-formed '\#pragma omp target teams' after parsing of the
10129   /// associated statement.
10130   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10131                                              Stmt *AStmt,
10132                                              SourceLocation StartLoc,
10133                                              SourceLocation EndLoc);
10134   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10135   /// of the associated statement.
10136   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10137       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10138       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10139   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10140   /// after parsing of the associated statement.
10141   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10142       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10143       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10144   /// Called on well-formed '\#pragma omp target teams distribute parallel for
10145   /// simd' after parsing of the associated statement.
10146   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10147       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10148       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10149   /// Called on well-formed '\#pragma omp target teams distribute simd' after
10150   /// parsing of the associated statement.
10151   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10152       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10153       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10154 
10155   /// Checks correctness of linear modifiers.
10156   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10157                                  SourceLocation LinLoc);
10158   /// Checks that the specified declaration matches requirements for the linear
10159   /// decls.
10160   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10161                              OpenMPLinearClauseKind LinKind, QualType Type);
10162 
10163   /// Called on well-formed '\#pragma omp declare simd' after parsing of
10164   /// the associated method/function.
10165   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10166       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10167       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10168       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10169       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10170 
10171   /// Checks '\#pragma omp declare variant' variant function and original
10172   /// functions after parsing of the associated method/function.
10173   /// \param DG Function declaration to which declare variant directive is
10174   /// applied to.
10175   /// \param VariantRef Expression that references the variant function, which
10176   /// must be used instead of the original one, specified in \p DG.
10177   /// \returns None, if the function/variant function are not compatible with
10178   /// the pragma, pair of original function/variant ref expression otherwise.
10179   Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
10180       DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
10181 
10182   /// Called on well-formed '\#pragma omp declare variant' after parsing of
10183   /// the associated method/function.
10184   /// \param FD Function declaration to which declare variant directive is
10185   /// applied to.
10186   /// \param VariantRef Expression that references the variant function, which
10187   /// must be used instead of the original one, specified in \p DG.
10188   /// \param Data Set of context-specific data for the specified context
10189   /// selector.
10190   void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10191                                           SourceRange SR,
10192                                           ArrayRef<OMPCtxSelectorData> Data);
10193 
10194   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10195                                          Expr *Expr,
10196                                          SourceLocation StartLoc,
10197                                          SourceLocation LParenLoc,
10198                                          SourceLocation EndLoc);
10199   /// Called on well-formed 'allocator' clause.
10200   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10201                                         SourceLocation StartLoc,
10202                                         SourceLocation LParenLoc,
10203                                         SourceLocation EndLoc);
10204   /// Called on well-formed 'if' clause.
10205   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10206                                  Expr *Condition, SourceLocation StartLoc,
10207                                  SourceLocation LParenLoc,
10208                                  SourceLocation NameModifierLoc,
10209                                  SourceLocation ColonLoc,
10210                                  SourceLocation EndLoc);
10211   /// Called on well-formed 'final' clause.
10212   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10213                                     SourceLocation LParenLoc,
10214                                     SourceLocation EndLoc);
10215   /// Called on well-formed 'num_threads' clause.
10216   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10217                                          SourceLocation StartLoc,
10218                                          SourceLocation LParenLoc,
10219                                          SourceLocation EndLoc);
10220   /// Called on well-formed 'safelen' clause.
10221   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10222                                       SourceLocation StartLoc,
10223                                       SourceLocation LParenLoc,
10224                                       SourceLocation EndLoc);
10225   /// Called on well-formed 'simdlen' clause.
10226   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10227                                       SourceLocation LParenLoc,
10228                                       SourceLocation EndLoc);
10229   /// Called on well-formed 'collapse' clause.
10230   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10231                                        SourceLocation StartLoc,
10232                                        SourceLocation LParenLoc,
10233                                        SourceLocation EndLoc);
10234   /// Called on well-formed 'ordered' clause.
10235   OMPClause *
10236   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10237                            SourceLocation LParenLoc = SourceLocation(),
10238                            Expr *NumForLoops = nullptr);
10239   /// Called on well-formed 'grainsize' clause.
10240   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10241                                         SourceLocation LParenLoc,
10242                                         SourceLocation EndLoc);
10243   /// Called on well-formed 'num_tasks' clause.
10244   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10245                                        SourceLocation LParenLoc,
10246                                        SourceLocation EndLoc);
10247   /// Called on well-formed 'hint' clause.
10248   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10249                                    SourceLocation LParenLoc,
10250                                    SourceLocation EndLoc);
10251 
10252   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10253                                      unsigned Argument,
10254                                      SourceLocation ArgumentLoc,
10255                                      SourceLocation StartLoc,
10256                                      SourceLocation LParenLoc,
10257                                      SourceLocation EndLoc);
10258   /// Called on well-formed 'default' clause.
10259   OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10260                                       SourceLocation KindLoc,
10261                                       SourceLocation StartLoc,
10262                                       SourceLocation LParenLoc,
10263                                       SourceLocation EndLoc);
10264   /// Called on well-formed 'proc_bind' clause.
10265   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10266                                        SourceLocation KindLoc,
10267                                        SourceLocation StartLoc,
10268                                        SourceLocation LParenLoc,
10269                                        SourceLocation EndLoc);
10270 
10271   OMPClause *ActOnOpenMPSingleExprWithArgClause(
10272       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10273       SourceLocation StartLoc, SourceLocation LParenLoc,
10274       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10275       SourceLocation EndLoc);
10276   /// Called on well-formed 'schedule' clause.
10277   OMPClause *ActOnOpenMPScheduleClause(
10278       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10279       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10280       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10281       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10282 
10283   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10284                                SourceLocation EndLoc);
10285   /// Called on well-formed 'nowait' clause.
10286   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10287                                      SourceLocation EndLoc);
10288   /// Called on well-formed 'untied' clause.
10289   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10290                                      SourceLocation EndLoc);
10291   /// Called on well-formed 'mergeable' clause.
10292   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10293                                         SourceLocation EndLoc);
10294   /// Called on well-formed 'read' clause.
10295   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10296                                    SourceLocation EndLoc);
10297   /// Called on well-formed 'write' clause.
10298   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10299                                     SourceLocation EndLoc);
10300   /// Called on well-formed 'update' clause.
10301   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10302                                      SourceLocation EndLoc);
10303   /// Called on well-formed 'capture' clause.
10304   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10305                                       SourceLocation EndLoc);
10306   /// Called on well-formed 'seq_cst' clause.
10307   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10308                                      SourceLocation EndLoc);
10309   /// Called on well-formed 'threads' clause.
10310   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10311                                       SourceLocation EndLoc);
10312   /// Called on well-formed 'simd' clause.
10313   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10314                                    SourceLocation EndLoc);
10315   /// Called on well-formed 'nogroup' clause.
10316   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10317                                       SourceLocation EndLoc);
10318   /// Called on well-formed 'unified_address' clause.
10319   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10320                                              SourceLocation EndLoc);
10321 
10322   /// Called on well-formed 'unified_address' clause.
10323   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10324                                                   SourceLocation EndLoc);
10325 
10326   /// Called on well-formed 'reverse_offload' clause.
10327   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10328                                              SourceLocation EndLoc);
10329 
10330   /// Called on well-formed 'dynamic_allocators' clause.
10331   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10332                                                 SourceLocation EndLoc);
10333 
10334   /// Called on well-formed 'atomic_default_mem_order' clause.
10335   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10336       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10337       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10338 
10339   OMPClause *ActOnOpenMPVarListClause(
10340       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
10341       const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10342       CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10343       DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10344       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10345       ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10346       SourceLocation DepLinMapLastLoc);
10347   /// Called on well-formed 'allocate' clause.
10348   OMPClause *
10349   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
10350                             SourceLocation StartLoc, SourceLocation ColonLoc,
10351                             SourceLocation LParenLoc, SourceLocation EndLoc);
10352   /// Called on well-formed 'private' clause.
10353   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10354                                       SourceLocation StartLoc,
10355                                       SourceLocation LParenLoc,
10356                                       SourceLocation EndLoc);
10357   /// Called on well-formed 'firstprivate' clause.
10358   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10359                                            SourceLocation StartLoc,
10360                                            SourceLocation LParenLoc,
10361                                            SourceLocation EndLoc);
10362   /// Called on well-formed 'lastprivate' clause.
10363   OMPClause *ActOnOpenMPLastprivateClause(
10364       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
10365       SourceLocation LPKindLoc, SourceLocation ColonLoc,
10366       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10367   /// Called on well-formed 'shared' clause.
10368   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10369                                      SourceLocation StartLoc,
10370                                      SourceLocation LParenLoc,
10371                                      SourceLocation EndLoc);
10372   /// Called on well-formed 'reduction' clause.
10373   OMPClause *ActOnOpenMPReductionClause(
10374       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10375       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10376       CXXScopeSpec &ReductionIdScopeSpec,
10377       const DeclarationNameInfo &ReductionId,
10378       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10379   /// Called on well-formed 'task_reduction' clause.
10380   OMPClause *ActOnOpenMPTaskReductionClause(
10381       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10382       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10383       CXXScopeSpec &ReductionIdScopeSpec,
10384       const DeclarationNameInfo &ReductionId,
10385       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10386   /// Called on well-formed 'in_reduction' clause.
10387   OMPClause *ActOnOpenMPInReductionClause(
10388       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10389       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10390       CXXScopeSpec &ReductionIdScopeSpec,
10391       const DeclarationNameInfo &ReductionId,
10392       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10393   /// Called on well-formed 'linear' clause.
10394   OMPClause *
10395   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
10396                           SourceLocation StartLoc, SourceLocation LParenLoc,
10397                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10398                           SourceLocation ColonLoc, SourceLocation EndLoc);
10399   /// Called on well-formed 'aligned' clause.
10400   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10401                                       Expr *Alignment,
10402                                       SourceLocation StartLoc,
10403                                       SourceLocation LParenLoc,
10404                                       SourceLocation ColonLoc,
10405                                       SourceLocation EndLoc);
10406   /// Called on well-formed 'copyin' clause.
10407   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10408                                      SourceLocation StartLoc,
10409                                      SourceLocation LParenLoc,
10410                                      SourceLocation EndLoc);
10411   /// Called on well-formed 'copyprivate' clause.
10412   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10413                                           SourceLocation StartLoc,
10414                                           SourceLocation LParenLoc,
10415                                           SourceLocation EndLoc);
10416   /// Called on well-formed 'flush' pseudo clause.
10417   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10418                                     SourceLocation StartLoc,
10419                                     SourceLocation LParenLoc,
10420                                     SourceLocation EndLoc);
10421   /// Called on well-formed 'depend' clause.
10422   OMPClause *
10423   ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
10424                           SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
10425                           SourceLocation StartLoc, SourceLocation LParenLoc,
10426                           SourceLocation EndLoc);
10427   /// Called on well-formed 'device' clause.
10428   OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10429                                      SourceLocation LParenLoc,
10430                                      SourceLocation EndLoc);
10431   /// Called on well-formed 'map' clause.
10432   OMPClause *
10433   ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10434                        ArrayRef<SourceLocation> MapTypeModifiersLoc,
10435                        CXXScopeSpec &MapperIdScopeSpec,
10436                        DeclarationNameInfo &MapperId,
10437                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10438                        SourceLocation MapLoc, SourceLocation ColonLoc,
10439                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10440                        ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10441   /// Called on well-formed 'num_teams' clause.
10442   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
10443                                        SourceLocation LParenLoc,
10444                                        SourceLocation EndLoc);
10445   /// Called on well-formed 'thread_limit' clause.
10446   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10447                                           SourceLocation StartLoc,
10448                                           SourceLocation LParenLoc,
10449                                           SourceLocation EndLoc);
10450   /// Called on well-formed 'priority' clause.
10451   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
10452                                        SourceLocation LParenLoc,
10453                                        SourceLocation EndLoc);
10454   /// Called on well-formed 'dist_schedule' clause.
10455   OMPClause *ActOnOpenMPDistScheduleClause(
10456       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
10457       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
10458       SourceLocation CommaLoc, SourceLocation EndLoc);
10459   /// Called on well-formed 'defaultmap' clause.
10460   OMPClause *ActOnOpenMPDefaultmapClause(
10461       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10462       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10463       SourceLocation KindLoc, SourceLocation EndLoc);
10464   /// Called on well-formed 'to' clause.
10465   OMPClause *
10466   ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10467                       DeclarationNameInfo &MapperId,
10468                       const OMPVarListLocTy &Locs,
10469                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10470   /// Called on well-formed 'from' clause.
10471   OMPClause *ActOnOpenMPFromClause(
10472       ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10473       DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
10474       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10475   /// Called on well-formed 'use_device_ptr' clause.
10476   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10477                                            const OMPVarListLocTy &Locs);
10478   /// Called on well-formed 'is_device_ptr' clause.
10479   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10480                                           const OMPVarListLocTy &Locs);
10481   /// Called on well-formed 'nontemporal' clause.
10482   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
10483                                           SourceLocation StartLoc,
10484                                           SourceLocation LParenLoc,
10485                                           SourceLocation EndLoc);
10486 
10487   /// The kind of conversion being performed.
10488   enum CheckedConversionKind {
10489     /// An implicit conversion.
10490     CCK_ImplicitConversion,
10491     /// A C-style cast.
10492     CCK_CStyleCast,
10493     /// A functional-style cast.
10494     CCK_FunctionalCast,
10495     /// A cast other than a C-style cast.
10496     CCK_OtherCast,
10497     /// A conversion for an operand of a builtin overloaded operator.
10498     CCK_ForBuiltinOverloadedOp
10499   };
10500 
10501   static bool isCast(CheckedConversionKind CCK) {
10502     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
10503            CCK == CCK_OtherCast;
10504   }
10505 
10506   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
10507   /// cast.  If there is already an implicit cast, merge into the existing one.
10508   /// If isLvalue, the result of the cast is an lvalue.
10509   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
10510                                ExprValueKind VK = VK_RValue,
10511                                const CXXCastPath *BasePath = nullptr,
10512                                CheckedConversionKind CCK
10513                                   = CCK_ImplicitConversion);
10514 
10515   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
10516   /// to the conversion from scalar type ScalarTy to the Boolean type.
10517   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
10518 
10519   /// IgnoredValueConversions - Given that an expression's result is
10520   /// syntactically ignored, perform any conversions that are
10521   /// required.
10522   ExprResult IgnoredValueConversions(Expr *E);
10523 
10524   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
10525   // functions and arrays to their respective pointers (C99 6.3.2.1).
10526   ExprResult UsualUnaryConversions(Expr *E);
10527 
10528   /// CallExprUnaryConversions - a special case of an unary conversion
10529   /// performed on a function designator of a call expression.
10530   ExprResult CallExprUnaryConversions(Expr *E);
10531 
10532   // DefaultFunctionArrayConversion - converts functions and arrays
10533   // to their respective pointers (C99 6.3.2.1).
10534   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10535 
10536   // DefaultFunctionArrayLvalueConversion - converts functions and
10537   // arrays to their respective pointers and performs the
10538   // lvalue-to-rvalue conversion.
10539   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10540                                                   bool Diagnose = true);
10541 
10542   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10543   // the operand.  This is DefaultFunctionArrayLvalueConversion,
10544   // except that it assumes the operand isn't of function or array
10545   // type.
10546   ExprResult DefaultLvalueConversion(Expr *E);
10547 
10548   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10549   // do not have a prototype. Integer promotions are performed on each
10550   // argument, and arguments that have type float are promoted to double.
10551   ExprResult DefaultArgumentPromotion(Expr *E);
10552 
10553   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10554   /// it as an xvalue. In C++98, the result will still be a prvalue, because
10555   /// we don't have xvalues there.
10556   ExprResult TemporaryMaterializationConversion(Expr *E);
10557 
10558   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10559   enum VariadicCallType {
10560     VariadicFunction,
10561     VariadicBlock,
10562     VariadicMethod,
10563     VariadicConstructor,
10564     VariadicDoesNotApply
10565   };
10566 
10567   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10568                                        const FunctionProtoType *Proto,
10569                                        Expr *Fn);
10570 
10571   // Used for determining in which context a type is allowed to be passed to a
10572   // vararg function.
10573   enum VarArgKind {
10574     VAK_Valid,
10575     VAK_ValidInCXX11,
10576     VAK_Undefined,
10577     VAK_MSVCUndefined,
10578     VAK_Invalid
10579   };
10580 
10581   // Determines which VarArgKind fits an expression.
10582   VarArgKind isValidVarArgType(const QualType &Ty);
10583 
10584   /// Check to see if the given expression is a valid argument to a variadic
10585   /// function, issuing a diagnostic if not.
10586   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
10587 
10588   /// Check to see if a given expression could have '.c_str()' called on it.
10589   bool hasCStrMethod(const Expr *E);
10590 
10591   /// GatherArgumentsForCall - Collector argument expressions for various
10592   /// form of call prototypes.
10593   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
10594                               const FunctionProtoType *Proto,
10595                               unsigned FirstParam, ArrayRef<Expr *> Args,
10596                               SmallVectorImpl<Expr *> &AllArgs,
10597                               VariadicCallType CallType = VariadicDoesNotApply,
10598                               bool AllowExplicit = false,
10599                               bool IsListInitialization = false);
10600 
10601   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
10602   // will create a runtime trap if the resulting type is not a POD type.
10603   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
10604                                               FunctionDecl *FDecl);
10605 
10606   /// Context in which we're performing a usual arithmetic conversion.
10607   enum ArithConvKind {
10608     /// An arithmetic operation.
10609     ACK_Arithmetic,
10610     /// A bitwise operation.
10611     ACK_BitwiseOp,
10612     /// A comparison.
10613     ACK_Comparison,
10614     /// A conditional (?:) operator.
10615     ACK_Conditional,
10616     /// A compound assignment expression.
10617     ACK_CompAssign,
10618   };
10619 
10620   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
10621   // operands and then handles various conversions that are common to binary
10622   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
10623   // routine returns the first non-arithmetic type found. The client is
10624   // responsible for emitting appropriate error diagnostics.
10625   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
10626                                       SourceLocation Loc, ArithConvKind ACK);
10627 
10628   /// AssignConvertType - All of the 'assignment' semantic checks return this
10629   /// enum to indicate whether the assignment was allowed.  These checks are
10630   /// done for simple assignments, as well as initialization, return from
10631   /// function, argument passing, etc.  The query is phrased in terms of a
10632   /// source and destination type.
10633   enum AssignConvertType {
10634     /// Compatible - the types are compatible according to the standard.
10635     Compatible,
10636 
10637     /// PointerToInt - The assignment converts a pointer to an int, which we
10638     /// accept as an extension.
10639     PointerToInt,
10640 
10641     /// IntToPointer - The assignment converts an int to a pointer, which we
10642     /// accept as an extension.
10643     IntToPointer,
10644 
10645     /// FunctionVoidPointer - The assignment is between a function pointer and
10646     /// void*, which the standard doesn't allow, but we accept as an extension.
10647     FunctionVoidPointer,
10648 
10649     /// IncompatiblePointer - The assignment is between two pointers types that
10650     /// are not compatible, but we accept them as an extension.
10651     IncompatiblePointer,
10652 
10653     /// IncompatiblePointerSign - The assignment is between two pointers types
10654     /// which point to integers which have a different sign, but are otherwise
10655     /// identical. This is a subset of the above, but broken out because it's by
10656     /// far the most common case of incompatible pointers.
10657     IncompatiblePointerSign,
10658 
10659     /// CompatiblePointerDiscardsQualifiers - The assignment discards
10660     /// c/v/r qualifiers, which we accept as an extension.
10661     CompatiblePointerDiscardsQualifiers,
10662 
10663     /// IncompatiblePointerDiscardsQualifiers - The assignment
10664     /// discards qualifiers that we don't permit to be discarded,
10665     /// like address spaces.
10666     IncompatiblePointerDiscardsQualifiers,
10667 
10668     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
10669     /// changes address spaces in nested pointer types which is not allowed.
10670     /// For instance, converting __private int ** to __generic int ** is
10671     /// illegal even though __private could be converted to __generic.
10672     IncompatibleNestedPointerAddressSpaceMismatch,
10673 
10674     /// IncompatibleNestedPointerQualifiers - The assignment is between two
10675     /// nested pointer types, and the qualifiers other than the first two
10676     /// levels differ e.g. char ** -> const char **, but we accept them as an
10677     /// extension.
10678     IncompatibleNestedPointerQualifiers,
10679 
10680     /// IncompatibleVectors - The assignment is between two vector types that
10681     /// have the same size, which we accept as an extension.
10682     IncompatibleVectors,
10683 
10684     /// IntToBlockPointer - The assignment converts an int to a block
10685     /// pointer. We disallow this.
10686     IntToBlockPointer,
10687 
10688     /// IncompatibleBlockPointer - The assignment is between two block
10689     /// pointers types that are not compatible.
10690     IncompatibleBlockPointer,
10691 
10692     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
10693     /// id type and something else (that is incompatible with it). For example,
10694     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
10695     IncompatibleObjCQualifiedId,
10696 
10697     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
10698     /// object with __weak qualifier.
10699     IncompatibleObjCWeakRef,
10700 
10701     /// Incompatible - We reject this conversion outright, it is invalid to
10702     /// represent it in the AST.
10703     Incompatible
10704   };
10705 
10706   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
10707   /// assignment conversion type specified by ConvTy.  This returns true if the
10708   /// conversion was invalid or false if the conversion was accepted.
10709   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
10710                                 SourceLocation Loc,
10711                                 QualType DstType, QualType SrcType,
10712                                 Expr *SrcExpr, AssignmentAction Action,
10713                                 bool *Complained = nullptr);
10714 
10715   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
10716   /// enum. If AllowMask is true, then we also allow the complement of a valid
10717   /// value, to be used as a mask.
10718   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
10719                          bool AllowMask) const;
10720 
10721   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10722   /// integer not in the range of enum values.
10723   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10724                               Expr *SrcExpr);
10725 
10726   /// CheckAssignmentConstraints - Perform type checking for assignment,
10727   /// argument passing, variable initialization, and function return values.
10728   /// C99 6.5.16.
10729   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
10730                                                QualType LHSType,
10731                                                QualType RHSType);
10732 
10733   /// Check assignment constraints and optionally prepare for a conversion of
10734   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
10735   /// is true.
10736   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
10737                                                ExprResult &RHS,
10738                                                CastKind &Kind,
10739                                                bool ConvertRHS = true);
10740 
10741   /// Check assignment constraints for an assignment of RHS to LHSType.
10742   ///
10743   /// \param LHSType The destination type for the assignment.
10744   /// \param RHS The source expression for the assignment.
10745   /// \param Diagnose If \c true, diagnostics may be produced when checking
10746   ///        for assignability. If a diagnostic is produced, \p RHS will be
10747   ///        set to ExprError(). Note that this function may still return
10748   ///        without producing a diagnostic, even for an invalid assignment.
10749   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
10750   ///        in an audited Core Foundation API and does not need to be checked
10751   ///        for ARC retain issues.
10752   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
10753   ///        conversions necessary to perform the assignment. If \c false,
10754   ///        \p Diagnose must also be \c false.
10755   AssignConvertType CheckSingleAssignmentConstraints(
10756       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
10757       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
10758 
10759   // If the lhs type is a transparent union, check whether we
10760   // can initialize the transparent union with the given expression.
10761   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
10762                                                              ExprResult &RHS);
10763 
10764   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
10765 
10766   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
10767 
10768   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10769                                        AssignmentAction Action,
10770                                        bool AllowExplicit = false);
10771   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10772                                        AssignmentAction Action,
10773                                        bool AllowExplicit,
10774                                        ImplicitConversionSequence& ICS);
10775   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10776                                        const ImplicitConversionSequence& ICS,
10777                                        AssignmentAction Action,
10778                                        CheckedConversionKind CCK
10779                                           = CCK_ImplicitConversion);
10780   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10781                                        const StandardConversionSequence& SCS,
10782                                        AssignmentAction Action,
10783                                        CheckedConversionKind CCK);
10784 
10785   ExprResult PerformQualificationConversion(
10786       Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
10787       CheckedConversionKind CCK = CCK_ImplicitConversion);
10788 
10789   /// the following "Check" methods will return a valid/converted QualType
10790   /// or a null QualType (indicating an error diagnostic was issued).
10791 
10792   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
10793   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10794                            ExprResult &RHS);
10795   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10796                                  ExprResult &RHS);
10797   QualType CheckPointerToMemberOperands( // C++ 5.5
10798     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
10799     SourceLocation OpLoc, bool isIndirect);
10800   QualType CheckMultiplyDivideOperands( // C99 6.5.5
10801     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
10802     bool IsDivide);
10803   QualType CheckRemainderOperands( // C99 6.5.5
10804     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10805     bool IsCompAssign = false);
10806   QualType CheckAdditionOperands( // C99 6.5.6
10807     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10808     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
10809   QualType CheckSubtractionOperands( // C99 6.5.6
10810     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10811     QualType* CompLHSTy = nullptr);
10812   QualType CheckShiftOperands( // C99 6.5.7
10813     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10814     BinaryOperatorKind Opc, bool IsCompAssign = false);
10815   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
10816   QualType CheckCompareOperands( // C99 6.5.8/9
10817       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10818       BinaryOperatorKind Opc);
10819   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
10820       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10821       BinaryOperatorKind Opc);
10822   QualType CheckLogicalOperands( // C99 6.5.[13,14]
10823     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10824     BinaryOperatorKind Opc);
10825   // CheckAssignmentOperands is used for both simple and compound assignment.
10826   // For simple assignment, pass both expressions and a null converted type.
10827   // For compound assignment, pass both expressions and the converted type.
10828   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
10829     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
10830 
10831   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
10832                                      UnaryOperatorKind Opcode, Expr *Op);
10833   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
10834                                          BinaryOperatorKind Opcode,
10835                                          Expr *LHS, Expr *RHS);
10836   ExprResult checkPseudoObjectRValue(Expr *E);
10837   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
10838 
10839   QualType CheckConditionalOperands( // C99 6.5.15
10840     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
10841     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
10842   QualType CXXCheckConditionalOperands( // C++ 5.16
10843     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
10844     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
10845   QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
10846                                           ExprResult &RHS,
10847                                           SourceLocation QuestionLoc);
10848   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
10849                                     bool ConvertArgs = true);
10850   QualType FindCompositePointerType(SourceLocation Loc,
10851                                     ExprResult &E1, ExprResult &E2,
10852                                     bool ConvertArgs = true) {
10853     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
10854     QualType Composite =
10855         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
10856     E1 = E1Tmp;
10857     E2 = E2Tmp;
10858     return Composite;
10859   }
10860 
10861   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
10862                                         SourceLocation QuestionLoc);
10863 
10864   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
10865                                   SourceLocation QuestionLoc);
10866 
10867   void DiagnoseAlwaysNonNullPointer(Expr *E,
10868                                     Expr::NullPointerConstantKind NullType,
10869                                     bool IsEqual, SourceRange Range);
10870 
10871   /// type checking for vector binary operators.
10872   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10873                                SourceLocation Loc, bool IsCompAssign,
10874                                bool AllowBothBool, bool AllowBoolConversion);
10875   QualType GetSignedVectorType(QualType V);
10876   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10877                                       SourceLocation Loc,
10878                                       BinaryOperatorKind Opc);
10879   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10880                                       SourceLocation Loc);
10881 
10882   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
10883   bool isLaxVectorConversion(QualType srcType, QualType destType);
10884 
10885   /// type checking declaration initializers (C99 6.7.8)
10886   bool CheckForConstantInitializer(Expr *e, QualType t);
10887 
10888   // type checking C++ declaration initializers (C++ [dcl.init]).
10889 
10890   /// ReferenceCompareResult - Expresses the result of comparing two
10891   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10892   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10893   enum ReferenceCompareResult {
10894     /// Ref_Incompatible - The two types are incompatible, so direct
10895     /// reference binding is not possible.
10896     Ref_Incompatible = 0,
10897     /// Ref_Related - The two types are reference-related, which means
10898     /// that their unqualified forms (T1 and T2) are either the same
10899     /// or T1 is a base class of T2.
10900     Ref_Related,
10901     /// Ref_Compatible - The two types are reference-compatible.
10902     Ref_Compatible
10903   };
10904 
10905   // Fake up a scoped enumeration that still contextually converts to bool.
10906   struct ReferenceConversionsScope {
10907     /// The conversions that would be performed on an lvalue of type T2 when
10908     /// binding a reference of type T1 to it, as determined when evaluating
10909     /// whether T1 is reference-compatible with T2.
10910     enum ReferenceConversions {
10911       Qualification = 0x1,
10912       NestedQualification = 0x2,
10913       Function = 0x4,
10914       DerivedToBase = 0x8,
10915       ObjC = 0x10,
10916       ObjCLifetime = 0x20,
10917 
10918       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10919     };
10920   };
10921   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10922 
10923   ReferenceCompareResult
10924   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10925                                ReferenceConversions *Conv = nullptr);
10926 
10927   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10928                                  Expr *CastExpr, CastKind &CastKind,
10929                                  ExprValueKind &VK, CXXCastPath &Path);
10930 
10931   /// Force an expression with unknown-type to an expression of the
10932   /// given type.
10933   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
10934 
10935   /// Type-check an expression that's being passed to an
10936   /// __unknown_anytype parameter.
10937   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
10938                                 Expr *result, QualType &paramType);
10939 
10940   // CheckVectorCast - check type constraints for vectors.
10941   // Since vectors are an extension, there are no C standard reference for this.
10942   // We allow casting between vectors and integer datatypes of the same size.
10943   // returns true if the cast is invalid
10944   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
10945                        CastKind &Kind);
10946 
10947   /// Prepare `SplattedExpr` for a vector splat operation, adding
10948   /// implicit casts if necessary.
10949   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
10950 
10951   // CheckExtVectorCast - check type constraints for extended vectors.
10952   // Since vectors are an extension, there are no C standard reference for this.
10953   // We allow casting between vectors and integer datatypes of the same size,
10954   // or vectors and the element type of that vector.
10955   // returns the cast expr
10956   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
10957                                 CastKind &Kind);
10958 
10959   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
10960                                         SourceLocation LParenLoc,
10961                                         Expr *CastExpr,
10962                                         SourceLocation RParenLoc);
10963 
10964   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
10965 
10966   /// Checks for invalid conversions and casts between
10967   /// retainable pointers and other pointer kinds for ARC and Weak.
10968   ARCConversionResult CheckObjCConversion(SourceRange castRange,
10969                                           QualType castType, Expr *&op,
10970                                           CheckedConversionKind CCK,
10971                                           bool Diagnose = true,
10972                                           bool DiagnoseCFAudited = false,
10973                                           BinaryOperatorKind Opc = BO_PtrMemD
10974                                           );
10975 
10976   Expr *stripARCUnbridgedCast(Expr *e);
10977   void diagnoseARCUnbridgedCast(Expr *e);
10978 
10979   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
10980                                              QualType ExprType);
10981 
10982   /// checkRetainCycles - Check whether an Objective-C message send
10983   /// might create an obvious retain cycle.
10984   void checkRetainCycles(ObjCMessageExpr *msg);
10985   void checkRetainCycles(Expr *receiver, Expr *argument);
10986   void checkRetainCycles(VarDecl *Var, Expr *Init);
10987 
10988   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
10989   /// to weak/__unsafe_unretained type.
10990   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
10991 
10992   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
10993   /// to weak/__unsafe_unretained expression.
10994   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
10995 
10996   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
10997   /// \param Method - May be null.
10998   /// \param [out] ReturnType - The return type of the send.
10999   /// \return true iff there were any incompatible types.
11000   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11001                                  MultiExprArg Args, Selector Sel,
11002                                  ArrayRef<SourceLocation> SelectorLocs,
11003                                  ObjCMethodDecl *Method, bool isClassMessage,
11004                                  bool isSuperMessage, SourceLocation lbrac,
11005                                  SourceLocation rbrac, SourceRange RecRange,
11006                                  QualType &ReturnType, ExprValueKind &VK);
11007 
11008   /// Determine the result of a message send expression based on
11009   /// the type of the receiver, the method expected to receive the message,
11010   /// and the form of the message send.
11011   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11012                                     ObjCMethodDecl *Method, bool isClassMessage,
11013                                     bool isSuperMessage);
11014 
11015   /// If the given expression involves a message send to a method
11016   /// with a related result type, emit a note describing what happened.
11017   void EmitRelatedResultTypeNote(const Expr *E);
11018 
11019   /// Given that we had incompatible pointer types in a return
11020   /// statement, check whether we're in a method with a related result
11021   /// type, and if so, emit a note describing what happened.
11022   void EmitRelatedResultTypeNoteForReturn(QualType destType);
11023 
11024   class ConditionResult {
11025     Decl *ConditionVar;
11026     FullExprArg Condition;
11027     bool Invalid;
11028     bool HasKnownValue;
11029     bool KnownValue;
11030 
11031     friend class Sema;
11032     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11033                     bool IsConstexpr)
11034         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11035           HasKnownValue(IsConstexpr && Condition.get() &&
11036                         !Condition.get()->isValueDependent()),
11037           KnownValue(HasKnownValue &&
11038                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
11039     explicit ConditionResult(bool Invalid)
11040         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11041           HasKnownValue(false), KnownValue(false) {}
11042 
11043   public:
11044     ConditionResult() : ConditionResult(false) {}
11045     bool isInvalid() const { return Invalid; }
11046     std::pair<VarDecl *, Expr *> get() const {
11047       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11048                             Condition.get());
11049     }
11050     llvm::Optional<bool> getKnownValue() const {
11051       if (!HasKnownValue)
11052         return None;
11053       return KnownValue;
11054     }
11055   };
11056   static ConditionResult ConditionError() { return ConditionResult(true); }
11057 
11058   enum class ConditionKind {
11059     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11060     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11061     Switch       ///< An integral condition for a 'switch' statement.
11062   };
11063 
11064   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11065                                  Expr *SubExpr, ConditionKind CK);
11066 
11067   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11068                                          SourceLocation StmtLoc,
11069                                          ConditionKind CK);
11070 
11071   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11072 
11073   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11074                                     SourceLocation StmtLoc,
11075                                     ConditionKind CK);
11076   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11077 
11078   /// CheckBooleanCondition - Diagnose problems involving the use of
11079   /// the given expression as a boolean condition (e.g. in an if
11080   /// statement).  Also performs the standard function and array
11081   /// decays, possibly changing the input variable.
11082   ///
11083   /// \param Loc - A location associated with the condition, e.g. the
11084   /// 'if' keyword.
11085   /// \return true iff there were any errors
11086   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11087                                    bool IsConstexpr = false);
11088 
11089   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11090   /// found in an explicit(bool) specifier.
11091   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11092 
11093   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11094   /// Returns true if the explicit specifier is now resolved.
11095   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11096 
11097   /// DiagnoseAssignmentAsCondition - Given that an expression is
11098   /// being used as a boolean condition, warn if it's an assignment.
11099   void DiagnoseAssignmentAsCondition(Expr *E);
11100 
11101   /// Redundant parentheses over an equality comparison can indicate
11102   /// that the user intended an assignment used as condition.
11103   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11104 
11105   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11106   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11107 
11108   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11109   /// the specified width and sign.  If an overflow occurs, detect it and emit
11110   /// the specified diagnostic.
11111   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11112                                           unsigned NewWidth, bool NewSign,
11113                                           SourceLocation Loc, unsigned DiagID);
11114 
11115   /// Checks that the Objective-C declaration is declared in the global scope.
11116   /// Emits an error and marks the declaration as invalid if it's not declared
11117   /// in the global scope.
11118   bool CheckObjCDeclScope(Decl *D);
11119 
11120   /// Abstract base class used for diagnosing integer constant
11121   /// expression violations.
11122   class VerifyICEDiagnoser {
11123   public:
11124     bool Suppress;
11125 
11126     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
11127 
11128     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
11129     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
11130     virtual ~VerifyICEDiagnoser() { }
11131   };
11132 
11133   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
11134   /// and reports the appropriate diagnostics. Returns false on success.
11135   /// Can optionally return the value of the expression.
11136   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11137                                              VerifyICEDiagnoser &Diagnoser,
11138                                              bool AllowFold = true);
11139   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11140                                              unsigned DiagID,
11141                                              bool AllowFold = true);
11142   ExprResult VerifyIntegerConstantExpression(Expr *E,
11143                                              llvm::APSInt *Result = nullptr);
11144 
11145   /// VerifyBitField - verifies that a bit field expression is an ICE and has
11146   /// the correct width, and that the field type is valid.
11147   /// Returns false on success.
11148   /// Can optionally return whether the bit-field is of width 0
11149   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
11150                             QualType FieldTy, bool IsMsStruct,
11151                             Expr *BitWidth, bool *ZeroWidth = nullptr);
11152 
11153 private:
11154   unsigned ForceCUDAHostDeviceDepth = 0;
11155 
11156 public:
11157   /// Increments our count of the number of times we've seen a pragma forcing
11158   /// functions to be __host__ __device__.  So long as this count is greater
11159   /// than zero, all functions encountered will be __host__ __device__.
11160   void PushForceCUDAHostDevice();
11161 
11162   /// Decrements our count of the number of times we've seen a pragma forcing
11163   /// functions to be __host__ __device__.  Returns false if the count is 0
11164   /// before incrementing, so you can emit an error.
11165   bool PopForceCUDAHostDevice();
11166 
11167   /// Diagnostics that are emitted only if we discover that the given function
11168   /// must be codegen'ed.  Because handling these correctly adds overhead to
11169   /// compilation, this is currently only enabled for CUDA compilations.
11170   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11171                  std::vector<PartialDiagnosticAt>>
11172       DeviceDeferredDiags;
11173 
11174   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
11175   /// key in a hashtable, both the FD and location are hashed.
11176   struct FunctionDeclAndLoc {
11177     CanonicalDeclPtr<FunctionDecl> FD;
11178     SourceLocation Loc;
11179   };
11180 
11181   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11182   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
11183   /// same deferred diag twice.
11184   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11185 
11186   /// An inverse call graph, mapping known-emitted functions to one of their
11187   /// known-emitted callers (plus the location of the call).
11188   ///
11189   /// Functions that we can tell a priori must be emitted aren't added to this
11190   /// map.
11191   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11192                  /* Caller = */ FunctionDeclAndLoc>
11193       DeviceKnownEmittedFns;
11194 
11195   /// A partial call graph maintained during CUDA/OpenMP device code compilation
11196   /// to support deferred diagnostics.
11197   ///
11198   /// Functions are only added here if, at the time they're considered, they are
11199   /// not known-emitted.  As soon as we discover that a function is
11200   /// known-emitted, we remove it and everything it transitively calls from this
11201   /// set and add those functions to DeviceKnownEmittedFns.
11202   llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
11203                  /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
11204                                                  SourceLocation>>
11205       DeviceCallGraph;
11206 
11207   /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
11208   /// deferred.
11209   ///
11210   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
11211   /// which are not allowed to appear inside __device__ functions and are
11212   /// allowed to appear in __host__ __device__ functions only if the host+device
11213   /// function is never codegen'ed.
11214   ///
11215   /// To handle this, we use the notion of "deferred diagnostics", where we
11216   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
11217   ///
11218   /// This class lets you emit either a regular diagnostic, a deferred
11219   /// diagnostic, or no diagnostic at all, according to an argument you pass to
11220   /// its constructor, thus simplifying the process of creating these "maybe
11221   /// deferred" diagnostics.
11222   class DeviceDiagBuilder {
11223   public:
11224     enum Kind {
11225       /// Emit no diagnostics.
11226       K_Nop,
11227       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
11228       K_Immediate,
11229       /// Emit the diagnostic immediately, and, if it's a warning or error, also
11230       /// emit a call stack showing how this function can be reached by an a
11231       /// priori known-emitted function.
11232       K_ImmediateWithCallStack,
11233       /// Create a deferred diagnostic, which is emitted only if the function
11234       /// it's attached to is codegen'ed.  Also emit a call stack as with
11235       /// K_ImmediateWithCallStack.
11236       K_Deferred
11237     };
11238 
11239     DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
11240                       FunctionDecl *Fn, Sema &S);
11241     DeviceDiagBuilder(DeviceDiagBuilder &&D);
11242     DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
11243     ~DeviceDiagBuilder();
11244 
11245     /// Convertible to bool: True if we immediately emitted an error, false if
11246     /// we didn't emit an error or we created a deferred error.
11247     ///
11248     /// Example usage:
11249     ///
11250     ///   if (DeviceDiagBuilder(...) << foo << bar)
11251     ///     return ExprError();
11252     ///
11253     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
11254     /// want to use these instead of creating a DeviceDiagBuilder yourself.
11255     operator bool() const { return ImmediateDiag.hasValue(); }
11256 
11257     template <typename T>
11258     friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
11259                                                const T &Value) {
11260       if (Diag.ImmediateDiag.hasValue())
11261         *Diag.ImmediateDiag << Value;
11262       else if (Diag.PartialDiagId.hasValue())
11263         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
11264             << Value;
11265       return Diag;
11266     }
11267 
11268   private:
11269     Sema &S;
11270     SourceLocation Loc;
11271     unsigned DiagID;
11272     FunctionDecl *Fn;
11273     bool ShowCallStack;
11274 
11275     // Invariant: At most one of these Optionals has a value.
11276     // FIXME: Switch these to a Variant once that exists.
11277     llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
11278     llvm::Optional<unsigned> PartialDiagId;
11279   };
11280 
11281   /// Indicate that this function (and thus everything it transtively calls)
11282   /// will be codegen'ed, and emit any deferred diagnostics on this function and
11283   /// its (transitive) callees.
11284   void markKnownEmitted(
11285       Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
11286       SourceLocation OrigLoc,
11287       const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
11288 
11289   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11290   /// is "used as device code".
11291   ///
11292   /// - If CurContext is a __host__ function, does not emit any diagnostics.
11293   /// - If CurContext is a __device__ or __global__ function, emits the
11294   ///   diagnostics immediately.
11295   /// - If CurContext is a __host__ __device__ function and we are compiling for
11296   ///   the device, creates a diagnostic which is emitted if and when we realize
11297   ///   that the function will be codegen'ed.
11298   ///
11299   /// Example usage:
11300   ///
11301   ///  // Variable-length arrays are not allowed in CUDA device code.
11302   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11303   ///    return ExprError();
11304   ///  // Otherwise, continue parsing as normal.
11305   DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
11306 
11307   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11308   /// is "used as host code".
11309   ///
11310   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11311   DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11312 
11313   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11314   /// context is "used as device code".
11315   ///
11316   /// - If CurContext is a `declare target` function or it is known that the
11317   /// function is emitted for the device, emits the diagnostics immediately.
11318   /// - If CurContext is a non-`declare target` function and we are compiling
11319   ///   for the device, creates a diagnostic which is emitted if and when we
11320   ///   realize that the function will be codegen'ed.
11321   ///
11322   /// Example usage:
11323   ///
11324   ///  // Variable-length arrays are not allowed in NVPTX device code.
11325   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11326   ///    return ExprError();
11327   ///  // Otherwise, continue parsing as normal.
11328   DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
11329 
11330   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11331   /// context is "used as host code".
11332   ///
11333   /// - If CurContext is a `declare target` function or it is known that the
11334   /// function is emitted for the host, emits the diagnostics immediately.
11335   /// - If CurContext is a non-host function, just ignore it.
11336   ///
11337   /// Example usage:
11338   ///
11339   ///  // Variable-length arrays are not allowed in NVPTX device code.
11340   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11341   ///    return ExprError();
11342   ///  // Otherwise, continue parsing as normal.
11343   DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
11344 
11345   DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
11346 
11347   enum CUDAFunctionTarget {
11348     CFT_Device,
11349     CFT_Global,
11350     CFT_Host,
11351     CFT_HostDevice,
11352     CFT_InvalidTarget
11353   };
11354 
11355   /// Determines whether the given function is a CUDA device/host/kernel/etc.
11356   /// function.
11357   ///
11358   /// Use this rather than examining the function's attributes yourself -- you
11359   /// will get it wrong.  Returns CFT_Host if D is null.
11360   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11361                                         bool IgnoreImplicitHDAttr = false);
11362   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11363 
11364   /// Gets the CUDA target for the current context.
11365   CUDAFunctionTarget CurrentCUDATarget() {
11366     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
11367   }
11368 
11369   // CUDA function call preference. Must be ordered numerically from
11370   // worst to best.
11371   enum CUDAFunctionPreference {
11372     CFP_Never,      // Invalid caller/callee combination.
11373     CFP_WrongSide,  // Calls from host-device to host or device
11374                     // function that do not match current compilation
11375                     // mode.
11376     CFP_HostDevice, // Any calls to host/device functions.
11377     CFP_SameSide,   // Calls from host-device to host or device
11378                     // function matching current compilation mode.
11379     CFP_Native,     // host-to-host or device-to-device calls.
11380   };
11381 
11382   /// Identifies relative preference of a given Caller/Callee
11383   /// combination, based on their host/device attributes.
11384   /// \param Caller function which needs address of \p Callee.
11385   ///               nullptr in case of global context.
11386   /// \param Callee target function
11387   ///
11388   /// \returns preference value for particular Caller/Callee combination.
11389   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
11390                                                 const FunctionDecl *Callee);
11391 
11392   /// Determines whether Caller may invoke Callee, based on their CUDA
11393   /// host/device attributes.  Returns false if the call is not allowed.
11394   ///
11395   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
11396   /// semantically correct CUDA programs, but only if they're never codegen'ed.
11397   bool IsAllowedCUDACall(const FunctionDecl *Caller,
11398                          const FunctionDecl *Callee) {
11399     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
11400   }
11401 
11402   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
11403   /// depending on FD and the current compilation settings.
11404   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
11405                                    const LookupResult &Previous);
11406 
11407 public:
11408   /// Check whether we're allowed to call Callee from the current context.
11409   ///
11410   /// - If the call is never allowed in a semantically-correct program
11411   ///   (CFP_Never), emits an error and returns false.
11412   ///
11413   /// - If the call is allowed in semantically-correct programs, but only if
11414   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
11415   ///   be emitted if and when the caller is codegen'ed, and returns true.
11416   ///
11417   ///   Will only create deferred diagnostics for a given SourceLocation once,
11418   ///   so you can safely call this multiple times without generating duplicate
11419   ///   deferred errors.
11420   ///
11421   /// - Otherwise, returns true without emitting any diagnostics.
11422   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
11423 
11424   /// Set __device__ or __host__ __device__ attributes on the given lambda
11425   /// operator() method.
11426   ///
11427   /// CUDA lambdas declared inside __device__ or __global__ functions inherit
11428   /// the __device__ attribute.  Similarly, lambdas inside __host__ __device__
11429   /// functions become __host__ __device__ themselves.
11430   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
11431 
11432   /// Finds a function in \p Matches with highest calling priority
11433   /// from \p Caller context and erases all functions with lower
11434   /// calling priority.
11435   void EraseUnwantedCUDAMatches(
11436       const FunctionDecl *Caller,
11437       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11438 
11439   /// Given a implicit special member, infer its CUDA target from the
11440   /// calls it needs to make to underlying base/field special members.
11441   /// \param ClassDecl the class for which the member is being created.
11442   /// \param CSM the kind of special member.
11443   /// \param MemberDecl the special member itself.
11444   /// \param ConstRHS true if this is a copy operation with a const object on
11445   ///        its RHS.
11446   /// \param Diagnose true if this call should emit diagnostics.
11447   /// \return true if there was an error inferring.
11448   /// The result of this call is implicit CUDA target attribute(s) attached to
11449   /// the member declaration.
11450   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
11451                                                CXXSpecialMember CSM,
11452                                                CXXMethodDecl *MemberDecl,
11453                                                bool ConstRHS,
11454                                                bool Diagnose);
11455 
11456   /// \return true if \p CD can be considered empty according to CUDA
11457   /// (E.2.3.1 in CUDA 7.5 Programming guide).
11458   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
11459   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
11460 
11461   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
11462   // case of error emits appropriate diagnostic and invalidates \p Var.
11463   //
11464   // \details CUDA allows only empty constructors as initializers for global
11465   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
11466   // __shared__ variables whether they are local or not (they all are implicitly
11467   // static in CUDA). One exception is that CUDA allows constant initializers
11468   // for __constant__ and __device__ variables.
11469   void checkAllowedCUDAInitializer(VarDecl *VD);
11470 
11471   /// Check whether NewFD is a valid overload for CUDA. Emits
11472   /// diagnostics and invalidates NewFD if not.
11473   void checkCUDATargetOverload(FunctionDecl *NewFD,
11474                                const LookupResult &Previous);
11475   /// Copies target attributes from the template TD to the function FD.
11476   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
11477 
11478   /// Returns the name of the launch configuration function.  This is the name
11479   /// of the function that will be called to configure kernel call, with the
11480   /// parameters specified via <<<>>>.
11481   std::string getCudaConfigureFuncName() const;
11482 
11483   /// \name Code completion
11484   //@{
11485   /// Describes the context in which code completion occurs.
11486   enum ParserCompletionContext {
11487     /// Code completion occurs at top-level or namespace context.
11488     PCC_Namespace,
11489     /// Code completion occurs within a class, struct, or union.
11490     PCC_Class,
11491     /// Code completion occurs within an Objective-C interface, protocol,
11492     /// or category.
11493     PCC_ObjCInterface,
11494     /// Code completion occurs within an Objective-C implementation or
11495     /// category implementation
11496     PCC_ObjCImplementation,
11497     /// Code completion occurs within the list of instance variables
11498     /// in an Objective-C interface, protocol, category, or implementation.
11499     PCC_ObjCInstanceVariableList,
11500     /// Code completion occurs following one or more template
11501     /// headers.
11502     PCC_Template,
11503     /// Code completion occurs following one or more template
11504     /// headers within a class.
11505     PCC_MemberTemplate,
11506     /// Code completion occurs within an expression.
11507     PCC_Expression,
11508     /// Code completion occurs within a statement, which may
11509     /// also be an expression or a declaration.
11510     PCC_Statement,
11511     /// Code completion occurs at the beginning of the
11512     /// initialization statement (or expression) in a for loop.
11513     PCC_ForInit,
11514     /// Code completion occurs within the condition of an if,
11515     /// while, switch, or for statement.
11516     PCC_Condition,
11517     /// Code completion occurs within the body of a function on a
11518     /// recovery path, where we do not have a specific handle on our position
11519     /// in the grammar.
11520     PCC_RecoveryInFunction,
11521     /// Code completion occurs where only a type is permitted.
11522     PCC_Type,
11523     /// Code completion occurs in a parenthesized expression, which
11524     /// might also be a type cast.
11525     PCC_ParenthesizedExpression,
11526     /// Code completion occurs within a sequence of declaration
11527     /// specifiers within a function, method, or block.
11528     PCC_LocalDeclarationSpecifiers
11529   };
11530 
11531   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
11532   void CodeCompleteOrdinaryName(Scope *S,
11533                                 ParserCompletionContext CompletionContext);
11534   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
11535                             bool AllowNonIdentifiers,
11536                             bool AllowNestedNameSpecifiers);
11537 
11538   struct CodeCompleteExpressionData;
11539   void CodeCompleteExpression(Scope *S,
11540                               const CodeCompleteExpressionData &Data);
11541   void CodeCompleteExpression(Scope *S, QualType PreferredType,
11542                               bool IsParenthesized = false);
11543   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
11544                                        SourceLocation OpLoc, bool IsArrow,
11545                                        bool IsBaseExprStatement,
11546                                        QualType PreferredType);
11547   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
11548                                      QualType PreferredType);
11549   void CodeCompleteTag(Scope *S, unsigned TagSpec);
11550   void CodeCompleteTypeQualifiers(DeclSpec &DS);
11551   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
11552                                       const VirtSpecifiers *VS = nullptr);
11553   void CodeCompleteBracketDeclarator(Scope *S);
11554   void CodeCompleteCase(Scope *S);
11555   /// Reports signatures for a call to CodeCompleteConsumer and returns the
11556   /// preferred type for the current argument. Returned type can be null.
11557   QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
11558                                     SourceLocation OpenParLoc);
11559   QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
11560                                            SourceLocation Loc,
11561                                            ArrayRef<Expr *> Args,
11562                                            SourceLocation OpenParLoc);
11563   QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
11564                                               CXXScopeSpec SS,
11565                                               ParsedType TemplateTypeTy,
11566                                               ArrayRef<Expr *> ArgExprs,
11567                                               IdentifierInfo *II,
11568                                               SourceLocation OpenParLoc);
11569   void CodeCompleteInitializer(Scope *S, Decl *D);
11570   void CodeCompleteAfterIf(Scope *S);
11571 
11572   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
11573                                bool IsUsingDeclaration, QualType BaseType,
11574                                QualType PreferredType);
11575   void CodeCompleteUsing(Scope *S);
11576   void CodeCompleteUsingDirective(Scope *S);
11577   void CodeCompleteNamespaceDecl(Scope *S);
11578   void CodeCompleteNamespaceAliasDecl(Scope *S);
11579   void CodeCompleteOperatorName(Scope *S);
11580   void CodeCompleteConstructorInitializer(
11581                                 Decl *Constructor,
11582                                 ArrayRef<CXXCtorInitializer *> Initializers);
11583 
11584   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
11585                                     bool AfterAmpersand);
11586 
11587   void CodeCompleteObjCAtDirective(Scope *S);
11588   void CodeCompleteObjCAtVisibility(Scope *S);
11589   void CodeCompleteObjCAtStatement(Scope *S);
11590   void CodeCompleteObjCAtExpression(Scope *S);
11591   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
11592   void CodeCompleteObjCPropertyGetter(Scope *S);
11593   void CodeCompleteObjCPropertySetter(Scope *S);
11594   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
11595                                    bool IsParameter);
11596   void CodeCompleteObjCMessageReceiver(Scope *S);
11597   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
11598                                     ArrayRef<IdentifierInfo *> SelIdents,
11599                                     bool AtArgumentExpression);
11600   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
11601                                     ArrayRef<IdentifierInfo *> SelIdents,
11602                                     bool AtArgumentExpression,
11603                                     bool IsSuper = false);
11604   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
11605                                        ArrayRef<IdentifierInfo *> SelIdents,
11606                                        bool AtArgumentExpression,
11607                                        ObjCInterfaceDecl *Super = nullptr);
11608   void CodeCompleteObjCForCollection(Scope *S,
11609                                      DeclGroupPtrTy IterationVar);
11610   void CodeCompleteObjCSelector(Scope *S,
11611                                 ArrayRef<IdentifierInfo *> SelIdents);
11612   void CodeCompleteObjCProtocolReferences(
11613                                          ArrayRef<IdentifierLocPair> Protocols);
11614   void CodeCompleteObjCProtocolDecl(Scope *S);
11615   void CodeCompleteObjCInterfaceDecl(Scope *S);
11616   void CodeCompleteObjCSuperclass(Scope *S,
11617                                   IdentifierInfo *ClassName,
11618                                   SourceLocation ClassNameLoc);
11619   void CodeCompleteObjCImplementationDecl(Scope *S);
11620   void CodeCompleteObjCInterfaceCategory(Scope *S,
11621                                          IdentifierInfo *ClassName,
11622                                          SourceLocation ClassNameLoc);
11623   void CodeCompleteObjCImplementationCategory(Scope *S,
11624                                               IdentifierInfo *ClassName,
11625                                               SourceLocation ClassNameLoc);
11626   void CodeCompleteObjCPropertyDefinition(Scope *S);
11627   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
11628                                               IdentifierInfo *PropertyName);
11629   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
11630                                   ParsedType ReturnType);
11631   void CodeCompleteObjCMethodDeclSelector(Scope *S,
11632                                           bool IsInstanceMethod,
11633                                           bool AtParameterName,
11634                                           ParsedType ReturnType,
11635                                           ArrayRef<IdentifierInfo *> SelIdents);
11636   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
11637                                             SourceLocation ClassNameLoc,
11638                                             bool IsBaseExprStatement);
11639   void CodeCompletePreprocessorDirective(bool InConditional);
11640   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
11641   void CodeCompletePreprocessorMacroName(bool IsDefinition);
11642   void CodeCompletePreprocessorExpression();
11643   void CodeCompletePreprocessorMacroArgument(Scope *S,
11644                                              IdentifierInfo *Macro,
11645                                              MacroInfo *MacroInfo,
11646                                              unsigned Argument);
11647   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
11648   void CodeCompleteNaturalLanguage();
11649   void CodeCompleteAvailabilityPlatformName();
11650   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
11651                                    CodeCompletionTUInfo &CCTUInfo,
11652                   SmallVectorImpl<CodeCompletionResult> &Results);
11653   //@}
11654 
11655   //===--------------------------------------------------------------------===//
11656   // Extra semantic analysis beyond the C type system
11657 
11658 public:
11659   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
11660                                                 unsigned ByteNo) const;
11661 
11662 private:
11663   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11664                         const ArraySubscriptExpr *ASE=nullptr,
11665                         bool AllowOnePastEnd=true, bool IndexNegated=false);
11666   void CheckArrayAccess(const Expr *E);
11667   // Used to grab the relevant information from a FormatAttr and a
11668   // FunctionDeclaration.
11669   struct FormatStringInfo {
11670     unsigned FormatIdx;
11671     unsigned FirstDataArg;
11672     bool HasVAListArg;
11673   };
11674 
11675   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
11676                                   FormatStringInfo *FSI);
11677   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
11678                          const FunctionProtoType *Proto);
11679   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
11680                            ArrayRef<const Expr *> Args);
11681   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
11682                         const FunctionProtoType *Proto);
11683   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
11684   void CheckConstructorCall(FunctionDecl *FDecl,
11685                             ArrayRef<const Expr *> Args,
11686                             const FunctionProtoType *Proto,
11687                             SourceLocation Loc);
11688 
11689   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
11690                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
11691                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
11692                  VariadicCallType CallType);
11693 
11694   bool CheckObjCString(Expr *Arg);
11695   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
11696 
11697   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
11698                                       unsigned BuiltinID, CallExpr *TheCall);
11699   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
11700 
11701   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
11702                                     unsigned MaxWidth);
11703   bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11704   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11705   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11706 
11707   bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11708   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11709   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11710   bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11711   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11712   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11713   bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11714   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11715   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11716   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
11717   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
11718   bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11719   bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11720 
11721   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
11722   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
11723   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
11724   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
11725   bool SemaBuiltinVSX(CallExpr *TheCall);
11726   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
11727 
11728 public:
11729   // Used by C++ template instantiation.
11730   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
11731   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
11732                                    SourceLocation BuiltinLoc,
11733                                    SourceLocation RParenLoc);
11734 
11735 private:
11736   bool SemaBuiltinPrefetch(CallExpr *TheCall);
11737   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
11738   bool SemaBuiltinAssume(CallExpr *TheCall);
11739   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
11740   bool SemaBuiltinLongjmp(CallExpr *TheCall);
11741   bool SemaBuiltinSetjmp(CallExpr *TheCall);
11742   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
11743   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
11744   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
11745                                      AtomicExpr::AtomicOp Op);
11746   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
11747                                                     bool IsDelete);
11748   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
11749                               llvm::APSInt &Result);
11750   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
11751                                    int High, bool RangeIsError = true);
11752   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
11753                                       unsigned Multiple);
11754   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
11755   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
11756   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
11757   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
11758                                 int ArgNum, unsigned ExpectedFieldNum,
11759                                 bool AllowName);
11760   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
11761 public:
11762   enum FormatStringType {
11763     FST_Scanf,
11764     FST_Printf,
11765     FST_NSString,
11766     FST_Strftime,
11767     FST_Strfmon,
11768     FST_Kprintf,
11769     FST_FreeBSDKPrintf,
11770     FST_OSTrace,
11771     FST_OSLog,
11772     FST_Unknown
11773   };
11774   static FormatStringType GetFormatStringType(const FormatAttr *Format);
11775 
11776   bool FormatStringHasSArg(const StringLiteral *FExpr);
11777 
11778   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
11779 
11780 private:
11781   bool CheckFormatArguments(const FormatAttr *Format,
11782                             ArrayRef<const Expr *> Args,
11783                             bool IsCXXMember,
11784                             VariadicCallType CallType,
11785                             SourceLocation Loc, SourceRange Range,
11786                             llvm::SmallBitVector &CheckedVarArgs);
11787   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
11788                             bool HasVAListArg, unsigned format_idx,
11789                             unsigned firstDataArg, FormatStringType Type,
11790                             VariadicCallType CallType,
11791                             SourceLocation Loc, SourceRange range,
11792                             llvm::SmallBitVector &CheckedVarArgs);
11793 
11794   void CheckAbsoluteValueFunction(const CallExpr *Call,
11795                                   const FunctionDecl *FDecl);
11796 
11797   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
11798 
11799   void CheckMemaccessArguments(const CallExpr *Call,
11800                                unsigned BId,
11801                                IdentifierInfo *FnName);
11802 
11803   void CheckStrlcpycatArguments(const CallExpr *Call,
11804                                 IdentifierInfo *FnName);
11805 
11806   void CheckStrncatArguments(const CallExpr *Call,
11807                              IdentifierInfo *FnName);
11808 
11809   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11810                           SourceLocation ReturnLoc,
11811                           bool isObjCMethod = false,
11812                           const AttrVec *Attrs = nullptr,
11813                           const FunctionDecl *FD = nullptr);
11814 
11815 public:
11816   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
11817 
11818 private:
11819   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
11820   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
11821   void CheckForIntOverflow(Expr *E);
11822   void CheckUnsequencedOperations(const Expr *E);
11823 
11824   /// Perform semantic checks on a completed expression. This will either
11825   /// be a full-expression or a default argument expression.
11826   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
11827                           bool IsConstexpr = false);
11828 
11829   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
11830                                    Expr *Init);
11831 
11832   /// Check if there is a field shadowing.
11833   void CheckShadowInheritedFields(const SourceLocation &Loc,
11834                                   DeclarationName FieldName,
11835                                   const CXXRecordDecl *RD,
11836                                   bool DeclIsField = true);
11837 
11838   /// Check if the given expression contains 'break' or 'continue'
11839   /// statement that produces control flow different from GCC.
11840   void CheckBreakContinueBinding(Expr *E);
11841 
11842   /// Check whether receiver is mutable ObjC container which
11843   /// attempts to add itself into the container
11844   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
11845 
11846   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
11847   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
11848                                  bool DeleteWasArrayForm);
11849 public:
11850   /// Register a magic integral constant to be used as a type tag.
11851   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11852                                   uint64_t MagicValue, QualType Type,
11853                                   bool LayoutCompatible, bool MustBeNull);
11854 
11855   struct TypeTagData {
11856     TypeTagData() {}
11857 
11858     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
11859         Type(Type), LayoutCompatible(LayoutCompatible),
11860         MustBeNull(MustBeNull)
11861     {}
11862 
11863     QualType Type;
11864 
11865     /// If true, \c Type should be compared with other expression's types for
11866     /// layout-compatibility.
11867     unsigned LayoutCompatible : 1;
11868     unsigned MustBeNull : 1;
11869   };
11870 
11871   /// A pair of ArgumentKind identifier and magic value.  This uniquely
11872   /// identifies the magic value.
11873   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
11874 
11875 private:
11876   /// A map from magic value to type information.
11877   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
11878       TypeTagForDatatypeMagicValues;
11879 
11880   /// Peform checks on a call of a function with argument_with_type_tag
11881   /// or pointer_with_type_tag attributes.
11882   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11883                                 const ArrayRef<const Expr *> ExprArgs,
11884                                 SourceLocation CallSiteLoc);
11885 
11886   /// Check if we are taking the address of a packed field
11887   /// as this may be a problem if the pointer value is dereferenced.
11888   void CheckAddressOfPackedMember(Expr *rhs);
11889 
11890   /// The parser's current scope.
11891   ///
11892   /// The parser maintains this state here.
11893   Scope *CurScope;
11894 
11895   mutable IdentifierInfo *Ident_super;
11896   mutable IdentifierInfo *Ident___float128;
11897 
11898   /// Nullability type specifiers.
11899   IdentifierInfo *Ident__Nonnull = nullptr;
11900   IdentifierInfo *Ident__Nullable = nullptr;
11901   IdentifierInfo *Ident__Null_unspecified = nullptr;
11902 
11903   IdentifierInfo *Ident_NSError = nullptr;
11904 
11905   /// The handler for the FileChanged preprocessor events.
11906   ///
11907   /// Used for diagnostics that implement custom semantic analysis for #include
11908   /// directives, like -Wpragma-pack.
11909   sema::SemaPPCallbacks *SemaPPCallbackHandler;
11910 
11911 protected:
11912   friend class Parser;
11913   friend class InitializationSequence;
11914   friend class ASTReader;
11915   friend class ASTDeclReader;
11916   friend class ASTWriter;
11917 
11918 public:
11919   /// Retrieve the keyword associated
11920   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
11921 
11922   /// The struct behind the CFErrorRef pointer.
11923   RecordDecl *CFError = nullptr;
11924 
11925   /// Retrieve the identifier "NSError".
11926   IdentifierInfo *getNSErrorIdent();
11927 
11928   /// Retrieve the parser's current scope.
11929   ///
11930   /// This routine must only be used when it is certain that semantic analysis
11931   /// and the parser are in precisely the same context, which is not the case
11932   /// when, e.g., we are performing any kind of template instantiation.
11933   /// Therefore, the only safe places to use this scope are in the parser
11934   /// itself and in routines directly invoked from the parser and *never* from
11935   /// template substitution or instantiation.
11936   Scope *getCurScope() const { return CurScope; }
11937 
11938   void incrementMSManglingNumber() const {
11939     return CurScope->incrementMSManglingNumber();
11940   }
11941 
11942   IdentifierInfo *getSuperIdentifier() const;
11943   IdentifierInfo *getFloat128Identifier() const;
11944 
11945   Decl *getObjCDeclContext() const;
11946 
11947   DeclContext *getCurLexicalContext() const {
11948     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
11949   }
11950 
11951   const DeclContext *getCurObjCLexicalContext() const {
11952     const DeclContext *DC = getCurLexicalContext();
11953     // A category implicitly has the attribute of the interface.
11954     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
11955       DC = CatD->getClassInterface();
11956     return DC;
11957   }
11958 
11959   /// Determine the number of levels of enclosing template parameters. This is
11960   /// only usable while parsing. Note that this does not include dependent
11961   /// contexts in which no template parameters have yet been declared, such as
11962   /// in a terse function template or generic lambda before the first 'auto' is
11963   /// encountered.
11964   unsigned getTemplateDepth(Scope *S) const;
11965 
11966   /// To be used for checking whether the arguments being passed to
11967   /// function exceeds the number of parameters expected for it.
11968   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
11969                                bool PartialOverloading = false) {
11970     // We check whether we're just after a comma in code-completion.
11971     if (NumArgs > 0 && PartialOverloading)
11972       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
11973     return NumArgs > NumParams;
11974   }
11975 
11976   // Emitting members of dllexported classes is delayed until the class
11977   // (including field initializers) is fully parsed.
11978   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
11979   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
11980 
11981 private:
11982   int ParsingClassDepth = 0;
11983 
11984   class SavePendingParsedClassStateRAII {
11985   public:
11986     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
11987 
11988     ~SavePendingParsedClassStateRAII() {
11989       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
11990              "there shouldn't be any pending delayed exception spec checks");
11991       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
11992              "there shouldn't be any pending delayed exception spec checks");
11993       swapSavedState();
11994     }
11995 
11996   private:
11997     Sema &S;
11998     decltype(DelayedOverridingExceptionSpecChecks)
11999         SavedOverridingExceptionSpecChecks;
12000     decltype(DelayedEquivalentExceptionSpecChecks)
12001         SavedEquivalentExceptionSpecChecks;
12002 
12003     void swapSavedState() {
12004       SavedOverridingExceptionSpecChecks.swap(
12005           S.DelayedOverridingExceptionSpecChecks);
12006       SavedEquivalentExceptionSpecChecks.swap(
12007           S.DelayedEquivalentExceptionSpecChecks);
12008     }
12009   };
12010 
12011   /// Helper class that collects misaligned member designations and
12012   /// their location info for delayed diagnostics.
12013   struct MisalignedMember {
12014     Expr *E;
12015     RecordDecl *RD;
12016     ValueDecl *MD;
12017     CharUnits Alignment;
12018 
12019     MisalignedMember() : E(), RD(), MD(), Alignment() {}
12020     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12021                      CharUnits Alignment)
12022         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
12023     explicit MisalignedMember(Expr *E)
12024         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12025 
12026     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12027   };
12028   /// Small set of gathered accesses to potentially misaligned members
12029   /// due to the packed attribute.
12030   SmallVector<MisalignedMember, 4> MisalignedMembers;
12031 
12032   /// Adds an expression to the set of gathered misaligned members.
12033   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12034                                      CharUnits Alignment);
12035 
12036 public:
12037   /// Diagnoses the current set of gathered accesses. This typically
12038   /// happens at full expression level. The set is cleared after emitting the
12039   /// diagnostics.
12040   void DiagnoseMisalignedMembers();
12041 
12042   /// This function checks if the expression is in the sef of potentially
12043   /// misaligned members and it is converted to some pointer type T with lower
12044   /// or equal alignment requirements. If so it removes it. This is used when
12045   /// we do not want to diagnose such misaligned access (e.g. in conversions to
12046   /// void*).
12047   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12048 
12049   /// This function calls Action when it determines that E designates a
12050   /// misaligned member due to the packed attribute. This is used to emit
12051   /// local diagnostics like in reference binding.
12052   void RefersToMemberWithReducedAlignment(
12053       Expr *E,
12054       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12055           Action);
12056 
12057   /// Describes the reason a calling convention specification was ignored, used
12058   /// for diagnostics.
12059   enum class CallingConventionIgnoredReason {
12060     ForThisTarget = 0,
12061     VariadicFunction,
12062     ConstructorDestructor,
12063     BuiltinFunction
12064   };
12065 };
12066 
12067 /// RAII object that enters a new expression evaluation context.
12068 class EnterExpressionEvaluationContext {
12069   Sema &Actions;
12070   bool Entered = true;
12071 
12072 public:
12073   EnterExpressionEvaluationContext(
12074       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12075       Decl *LambdaContextDecl = nullptr,
12076       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12077           Sema::ExpressionEvaluationContextRecord::EK_Other,
12078       bool ShouldEnter = true)
12079       : Actions(Actions), Entered(ShouldEnter) {
12080     if (Entered)
12081       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
12082                                               ExprContext);
12083   }
12084   EnterExpressionEvaluationContext(
12085       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12086       Sema::ReuseLambdaContextDecl_t,
12087       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12088           Sema::ExpressionEvaluationContextRecord::EK_Other)
12089       : Actions(Actions) {
12090     Actions.PushExpressionEvaluationContext(
12091         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
12092   }
12093 
12094   enum InitListTag { InitList };
12095   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
12096                                    bool ShouldEnter = true)
12097       : Actions(Actions), Entered(false) {
12098     // In C++11 onwards, narrowing checks are performed on the contents of
12099     // braced-init-lists, even when they occur within unevaluated operands.
12100     // Therefore we still need to instantiate constexpr functions used in such
12101     // a context.
12102     if (ShouldEnter && Actions.isUnevaluatedContext() &&
12103         Actions.getLangOpts().CPlusPlus11) {
12104       Actions.PushExpressionEvaluationContext(
12105           Sema::ExpressionEvaluationContext::UnevaluatedList);
12106       Entered = true;
12107     }
12108   }
12109 
12110   ~EnterExpressionEvaluationContext() {
12111     if (Entered)
12112       Actions.PopExpressionEvaluationContext();
12113   }
12114 };
12115 
12116 DeductionFailureInfo
12117 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
12118                          sema::TemplateDeductionInfo &Info);
12119 
12120 /// Contains a late templated function.
12121 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
12122 struct LateParsedTemplate {
12123   CachedTokens Toks;
12124   /// The template function declaration to be late parsed.
12125   Decl *D;
12126 };
12127 } // end namespace clang
12128 
12129 namespace llvm {
12130 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
12131 // SourceLocation.
12132 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
12133   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
12134   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
12135 
12136   static FunctionDeclAndLoc getEmptyKey() {
12137     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
12138   }
12139 
12140   static FunctionDeclAndLoc getTombstoneKey() {
12141     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
12142   }
12143 
12144   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
12145     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
12146                         FDL.Loc.getRawEncoding());
12147   }
12148 
12149   static bool isEqual(const FunctionDeclAndLoc &LHS,
12150                       const FunctionDeclAndLoc &RHS) {
12151     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
12152   }
12153 };
12154 } // namespace llvm
12155 
12156 #endif
12157